egui-map-view 0.5.0

An slippy map viewer for egui applications.
Documentation
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! A layer for placing polygons on the map.
//!
//! # Example
//!
//! ```no_run
//! use eframe::egui;
//! use egui_map_view::{Map, config::OpenStreetMapConfig, layers::{area::{Area, AreaLayer, AreaMode, AreaShape::Polygon, FillType}, Layer}, projection::GeoPos};
//! use egui::{Color32, Stroke};
//!
//! struct MyApp {
//!     map: Map,
//! }
//!
//! impl Default for MyApp {
//!   fn default() -> Self {
//!     let mut map = Map::new(OpenStreetMapConfig::default());
//!
//!     let mut area_layer = AreaLayer::default();
//!     area_layer.add_area(Area {
//!         shape: Polygon(vec![
//!             GeoPos { lon: 10.0, lat: 55.0 },
//!             GeoPos { lon: 11.0, lat: 55.0 },
//!             GeoPos { lon: 10.5, lat: 55.5 },
//!         ]),
//!         stroke: Stroke::new(2.0, Color32::from_rgb(255, 0, 0)),
//!         fill: Color32::from_rgba_unmultiplied(255, 0, 0, 50),
//!         fill_type: FillType::Solid,
//!     });
//!     area_layer.mode = AreaMode::Modify;
//!
//!     map.add_layer("areas", area_layer);
//!
//!     Self { map }
//!   }
//! }
//!
//! impl eframe::App for MyApp {
//!     fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
//!         egui::CentralPanel::default().show_inside(ui, |ui| {
//!             ui.add(&mut self.map);
//!         });
//!     }
//! }
//! ```

use crate::layers::{
    Layer, dist_sq_to_segment, projection_factor, segments_intersect, serde_color32, serde_stroke,
};
use crate::projection::{GeoPos, MapProjection};
use egui::{Color32, Mesh, Painter, Pos2, Response, Shape, Stroke};
use log::warn;
use serde::{Deserialize, Serialize};
use std::any::Any;

/// The mode of the `AreaLayer`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AreaMode {
    /// The layer is not interactive.
    #[default]
    Disabled,
    /// The user can add/remove/move nodes.
    Modify,
}

/// The shape of a polygon area on the map.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AreaShape {
    /// A freeform polygon defined by a list of points.
    Polygon(Vec<GeoPos>),
    /// A circle defined by its center and radius in meters.
    Circle {
        /// The geographical center of the circle.
        center: GeoPos,
        /// The radius of the circle in meters.
        radius: f64,
        /// How many points should be used to draw the circle. If None the the point count is determined automatically which might look edged depending on zoom and projection.
        points: Option<i64>,
    },
}

/// How the interior of an area is filled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum FillType {
    /// No fill — only the outline is drawn.
    None,
    /// Solid color fill.
    #[default]
    Solid,
    /// Diagonal hatching lines using the stroke style.
    Hatching,
}

/// A polygon area on the map.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Area {
    /// The shape of the area.
    pub shape: AreaShape,

    /// The stroke style for drawing the polygon outlines.
    #[serde(with = "serde_stroke")]
    pub stroke: Stroke,

    /// The fill color of the polygon.
    #[serde(with = "serde_color32")]
    pub fill: Color32,

    /// How the interior of the area is filled.
    #[serde(default)]
    pub fill_type: FillType,
}

/// Represents what part of an area is being dragged.
#[derive(Clone, Debug)]
enum DraggedObject {
    PolygonNode {
        area_index: usize,
        node_index: usize,
    },
    CircleCenter {
        area_index: usize,
    },
    CircleRadius {
        area_index: usize,
    },
}

/// Layer implementation that allows the user to draw polygons on the map.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AreaLayer {
    areas: Vec<Area>,

    #[serde(skip)]
    /// The radius of the nodes.
    pub node_radius: f32,

    #[serde(skip)]
    /// The fill color of the nodes.
    pub node_fill: Color32,

    #[serde(skip)]
    /// The current drawing mode.
    pub mode: AreaMode,

    #[serde(skip)]
    dragged_object: Option<DraggedObject>,
}

impl Default for AreaLayer {
    fn default() -> Self {
        Self::new()
    }
}

impl AreaLayer {
    /// Creates a new `AreaLayer`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            areas: Vec::new(),
            node_radius: 5.0,
            node_fill: Color32::from_rgb(0, 128, 0),
            mode: AreaMode::default(),
            dragged_object: None,
        }
    }

    /// Adds a new area to the layer.
    pub fn add_area(&mut self, area: Area) {
        self.areas.push(area);
    }

    /// Returns a reference to the areas in the layer.
    #[must_use]
    pub fn areas(&self) -> &Vec<Area> {
        &self.areas
    }

    /// Returns a mutable reference to the areas in the layer.
    pub fn areas_mut(&mut self) -> &mut Vec<Area> {
        &mut self.areas
    }

    /// Serializes the layer to a `GeoJSON` `FeatureCollection`.
    #[cfg(feature = "geojson")]
    pub fn to_geojson_str(&self) -> Result<String, serde_json::Error> {
        let features: Vec<geojson::Feature> = self
            .areas
            .clone()
            .into_iter()
            .map(geojson::Feature::from)
            .collect();
        let feature_collection = geojson::FeatureCollection {
            bbox: None,
            features,
            foreign_members: None,
        };
        serde_json::to_string(&feature_collection)
    }

    /// Deserializes a `GeoJSON` `FeatureCollection` and adds the features to the layer.
    #[cfg(feature = "geojson")]
    pub fn from_geojson_str(&mut self, s: &str) -> Result<(), serde_json::Error> {
        let feature_collection: geojson::FeatureCollection = serde_json::from_str(s)?;
        let new_areas: Vec<Area> = feature_collection
            .features
            .into_iter()
            .filter_map(|f| Area::try_from(f).ok())
            .collect();
        self.areas.extend(new_areas);
        Ok(())
    }

    fn handle_modify_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
        if response.double_clicked()
            && let Some(pointer_pos) = response.interact_pointer_pos()
        {
            // TODO: This only works for polygons.
            if self.find_node_at(pointer_pos, projection).is_none()
                && let Some((area_idx, node_idx)) =
                    self.find_line_segment_at(pointer_pos, projection)
                && let Some(area) = self.areas.get_mut(area_idx)
                && let AreaShape::Polygon(points) = &mut area.shape
            {
                let p1_screen = projection.project(points[node_idx]);
                let p2_screen = projection.project(points[(node_idx + 1) % points.len()]);

                let t = projection_factor(pointer_pos, p1_screen, p2_screen);

                // Interpolate in screen space and unproject to get the new geographical position.
                let new_pos_screen = p1_screen.lerp(p2_screen, t);
                let new_pos_geo = projection.unproject(new_pos_screen);

                points.insert(node_idx + 1, new_pos_geo);

                // This interaction is fully handled, so we can return.
                return response.hovered();
            }
        }

        if response.drag_started()
            && let Some(pointer_pos) = response.interact_pointer_pos()
        {
            self.dragged_object = self.find_object_at(pointer_pos, projection);
        }

        if response.dragged()
            && let Some(dragged_object) = self.dragged_object.clone()
            && let Some(pointer_pos) = response.interact_pointer_pos()
        {
            match dragged_object {
                DraggedObject::PolygonNode {
                    area_index,
                    node_index,
                } => {
                    if self.is_move_valid(area_index, node_index, pointer_pos, projection)
                        && let Some(area) = self.areas.get_mut(area_index)
                    {
                        let mut revert_info = None;
                        if let AreaShape::Polygon(points) = &mut area.shape
                            && let Some(node) = points.get_mut(node_index)
                        {
                            let old_pos = *node;
                            *node = projection.unproject(pointer_pos);
                            revert_info = Some(old_pos);
                        }

                        if let Some(old_pos) = revert_info
                            && !area.can_triangulate(projection)
                        {
                            warn!("Triangulation failed, cancelling drag");
                            self.dragged_object = None;
                            if let AreaShape::Polygon(points) = &mut area.shape {
                                points[node_index] = old_pos;
                            }
                        }
                    }
                }
                DraggedObject::CircleCenter { area_index } => {
                    if let Some(area) = self.areas.get_mut(area_index) {
                        let mut revert_center = None;
                        if let AreaShape::Circle { center, .. } = &mut area.shape {
                            revert_center = Some(*center);
                            *center = projection.unproject(pointer_pos);
                        }

                        if let Some(old_center) = revert_center
                            && !area.can_triangulate(projection)
                        {
                            warn!("Triangulation failed, cancelling drag");
                            self.dragged_object = None;
                            if let AreaShape::Circle { center, .. } = &mut area.shape {
                                *center = old_center;
                            }
                        }
                    }
                }
                DraggedObject::CircleRadius { area_index } => {
                    if let Some(area) = self.areas.get_mut(area_index) {
                        let mut revert_radius = None;
                        if let AreaShape::Circle {
                            center,
                            radius,
                            points: _,
                        } = &mut area.shape
                        {
                            revert_radius = Some(*radius);
                            // Convert the new screen-space radius back to meters.
                            let center_screen = projection.project(*center);
                            let new_radius_pixels = pointer_pos.distance(center_screen);
                            let new_edge_screen =
                                center_screen + egui::vec2(new_radius_pixels, 0.0);
                            let new_edge_geo = projection.unproject(new_edge_screen);

                            // Calculate distance in meters. This is an approximation that works well for smaller distances.
                            let distance_lon = (new_edge_geo.lon - center.lon).abs()
                                * (111_320.0 * center.lat.to_radians().cos());
                            let distance_lat = (new_edge_geo.lat - center.lat).abs() * 110_574.0;
                            *radius = (distance_lon.powi(2) + distance_lat.powi(2)).sqrt();
                        }

                        if let Some(old_radius) = revert_radius
                            && !area.can_triangulate(projection)
                        {
                            warn!("Triangulation failed, cancelling drag");
                            self.dragged_object = None;
                            if let AreaShape::Circle { radius, .. } = &mut area.shape {
                                *radius = old_radius;
                            }
                        }
                    }
                }
            }
        }

        if response.drag_stopped() {
            self.dragged_object = None;
        }

        let is_dragging = self.dragged_object.is_some();

        if is_dragging {
            response.ctx.set_cursor_icon(egui::CursorIcon::Grabbing);
        } else if let Some(pointer_pos) = response.hover_pos()
            && self.find_object_at(pointer_pos, projection).is_some()
        {
            response.ctx.set_cursor_icon(egui::CursorIcon::Grab);
        }

        is_dragging
            || (response.hovered()
                && self
                    .find_object_at(response.hover_pos().unwrap_or_default(), projection)
                    .is_some())
    }

    fn find_object_at(
        &self,
        screen_pos: Pos2,
        projection: &MapProjection,
    ) -> Option<DraggedObject> {
        let click_tolerance_sq = (self.node_radius * 3.0).powi(2);

        for (area_idx, area) in self.areas.iter().enumerate().rev() {
            match &area.shape {
                AreaShape::Polygon(points) => {
                    for (node_idx, node) in points.iter().enumerate() {
                        let node_screen_pos = projection.project(*node);
                        if node_screen_pos.distance_sq(screen_pos) < click_tolerance_sq {
                            return Some(DraggedObject::PolygonNode {
                                area_index: area_idx,
                                node_index: node_idx,
                            });
                        }
                    }
                }
                AreaShape::Circle {
                    center,
                    radius,
                    points: _,
                } => {
                    let center_screen = projection.project(*center);

                    // Convert radius from meters to screen pixels to correctly detect handle clicks.
                    let point_on_circle_geo = GeoPos {
                        lon: center.lon + (radius / (111_320.0 * center.lat.to_radians().cos())),
                        lat: center.lat,
                    };
                    let point_on_circle_screen = projection.project(point_on_circle_geo);
                    let radius_pixels = center_screen.distance(point_on_circle_screen);

                    // Check for radius handle
                    let distance_to_edge =
                        (center_screen.distance(screen_pos) - radius_pixels).abs();
                    if distance_to_edge < self.node_radius * 2.0 {
                        return Some(DraggedObject::CircleRadius {
                            area_index: area_idx,
                        });
                    }

                    // Check for center
                    if center_screen.distance_sq(screen_pos) < click_tolerance_sq {
                        return Some(DraggedObject::CircleCenter {
                            area_index: area_idx,
                        });
                    }
                }
            }
        }

        None
    }

    fn find_node_at(&self, screen_pos: Pos2, projection: &MapProjection) -> Option<(usize, usize)> {
        match self.find_object_at(screen_pos, projection) {
            Some(DraggedObject::PolygonNode {
                area_index,
                node_index,
            }) => Some((area_index, node_index)),
            _ => None,
        }
    }

    fn find_line_segment_at(
        &self,
        screen_pos: Pos2,
        projection: &MapProjection,
    ) -> Option<(usize, usize)> {
        let click_tolerance = (self.node_radius * 2.0).powi(2);

        for (area_idx, area) in self.areas.iter().enumerate().rev() {
            if let AreaShape::Polygon(points) = &area.shape {
                if points.len() < 2 {
                    continue;
                }
                for i in 0..points.len() {
                    let p1 = projection.project(points[i]);
                    let p2 = projection.project(points[(i + 1) % points.len()]);

                    if dist_sq_to_segment(screen_pos, p1, p2) < click_tolerance {
                        return Some((area_idx, i));
                    }
                }
            }
        }
        None
    }

    /// Checks if moving a node to a new position would cause the polygon to self-intersect.
    fn is_move_valid(
        &self,
        area_idx: usize,
        node_idx: usize,
        new_screen_pos: Pos2,
        projection: &MapProjection,
    ) -> bool {
        let area = if let Some(area) = self.areas.get(area_idx) {
            area
        } else {
            return false; // TODO: Should not happen
        };

        let points = match &area.shape {
            AreaShape::Polygon(points) => points,
            _ => return true, // Not a polygon, no intersections possible.
        };

        if points.len() < 3 {
            return true;
        }
        let screen_points: Vec<Pos2> = points.iter().map(|p| projection.project(*p)).collect();

        let n = screen_points.len();
        let prev_node_idx = (node_idx + n - 1) % n;
        let next_node_idx = (node_idx + 1) % n;

        // The two edges that are being modified by the drag.
        let new_edge1 = (screen_points[prev_node_idx], new_screen_pos);
        let new_edge2 = (new_screen_pos, screen_points[next_node_idx]);

        for i in 0..n {
            let p1_idx = i;
            let p2_idx = (i + 1) % n;

            // Don't check against the edges connected to the dragged node.
            if p1_idx == node_idx || p2_idx == node_idx {
                continue;
            }

            let edge_to_check = (screen_points[p1_idx], screen_points[p2_idx]);

            // Check against the first new edge.
            if p1_idx != prev_node_idx
                && p2_idx != prev_node_idx
                && segments_intersect(new_edge1.0, new_edge1.1, edge_to_check.0, edge_to_check.1)
            {
                return false;
            }

            // Check against the second new edge.
            if p1_idx != next_node_idx
                && p2_idx != next_node_idx
                && segments_intersect(new_edge2.0, new_edge2.1, edge_to_check.0, edge_to_check.1)
            {
                return false;
            }
        }

        true
    }
}

impl Area {
    /// Checks if the area can be successfully triangulated.
    fn can_triangulate(&self, projection: &MapProjection) -> bool {
        let points = self.get_points(projection);
        let screen_points: Vec<Pos2> = points.iter().map(|p| projection.project(*p)).collect();

        if screen_points.len() < 3 {
            return true;
        }

        let flat_points: Vec<f64> = screen_points
            .iter()
            .flat_map(|p| [f64::from(p.x), f64::from(p.y)])
            .collect();
        earcutr::earcut(&flat_points, &[], 2).is_ok()
    }

    /// Returns the points of the area. For a circle, it generates a polygon approximation.
    fn get_points(&self, projection: &MapProjection) -> Vec<GeoPos> {
        match &self.shape {
            AreaShape::Polygon(points) => points.clone(),
            AreaShape::Circle {
                center,
                radius,
                points,
            } => {
                // Convert radius from meters to screen pixels.
                let center_geo = *center;
                let point_on_circle_geo = GeoPos {
                    lon: center_geo.lon
                        + (radius / (111_320.0 * center_geo.lat.to_radians().cos())),
                    lat: center_geo.lat,
                };
                let center_screen = projection.project(center_geo);
                let point_on_circle_screen = projection.project(point_on_circle_geo);
                let radius_pixels = center_screen.distance(point_on_circle_screen);

                let num_points = if let Some(points) = points {
                    *points
                } else {
                    // Automatically determine the number of points based on the circle's radius
                    // to ensure it looks smooth.
                    (f64::from(radius_pixels) * 2.0 * std::f64::consts::PI / 10.0).ceil() as i64
                };
                let mut circle_points = Vec::with_capacity(num_points as usize);

                for i in 0..num_points {
                    let angle = (i as f64 / num_points as f64) * 2.0 * std::f64::consts::PI;
                    let point_screen = center_screen
                        + egui::vec2(
                            radius_pixels * angle.cos() as f32,
                            radius_pixels * angle.sin() as f32,
                        );
                    circle_points.push(projection.unproject(point_screen));
                }
                circle_points
            }
        }
    }
}

/// Generates diagonal hatching line segments clipped to the given polygon.
///
/// `screen_points` are the polygon vertices in screen space (must be >= 3 points).
/// `spacing` is the distance in pixels between parallel hatching lines.
/// `angle` is the angle of the hatching lines in radians (0 = horizontal, PI/4 = 45° diagonal).
///
/// Returns a list of line segments `(start, end)` that lie inside the polygon.
fn generate_hatching_lines(screen_points: &[Pos2], spacing: f32, angle: f32) -> Vec<(Pos2, Pos2)> {
    if screen_points.len() < 3 || spacing <= 0.0 {
        return Vec::new();
    }

    // Direction along the hatching lines and perpendicular to them.
    let dir = egui::vec2(angle.cos(), angle.sin());
    let perp = egui::vec2(-angle.sin(), angle.cos());

    // Project all polygon points onto the perpendicular axis to find the sweep range.
    let mut min_perp = f32::MAX;
    let mut max_perp = f32::MIN;
    for p in screen_points {
        let d = p.to_vec2().dot(perp);
        min_perp = min_perp.min(d);
        max_perp = max_perp.max(d);
    }

    let n = screen_points.len();
    let mut segments = Vec::new();

    // Sweep parallel lines across the polygon.
    let mut offset = min_perp + spacing;
    while offset < max_perp {
        // A point on the current sweep line: origin + offset along the perpendicular.
        let line_origin = Pos2::ZERO + perp * offset;

        // Find intersections of this sweep line with every polygon edge.
        let mut t_values: Vec<f32> = Vec::new();
        for i in 0..n {
            let a = screen_points[i];
            let b = screen_points[(i + 1) % n];
            let edge = b - a;

            // Solve: a + t_edge * edge = line_origin + t_line * dir
            // Cross product form: (a - line_origin) × dir = t_edge * (edge × dir)
            let denom = edge.x * dir.y - edge.y * dir.x;
            if denom.abs() < 1e-9 {
                continue; // Edge is parallel to the hatching line.
            }

            let diff = a - line_origin;
            let t_edge = -(diff.x * dir.y - diff.y * dir.x) / denom;

            if (0.0..=1.0).contains(&t_edge) {
                // Compute t_line: the parameter along the sweep line direction.
                let t_line = if dir.x.abs() > dir.y.abs() {
                    (a.x - line_origin.x + t_edge * edge.x) / dir.x
                } else {
                    (a.y - line_origin.y + t_edge * edge.y) / dir.y
                };
                t_values.push(t_line);
            }
        }

        // Sort intersections along the sweep line.
        t_values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        // Pair up intersections (even-odd rule) to get interior segments.
        for pair in t_values.chunks_exact(2) {
            let p1 = line_origin + dir * pair[0];
            let p2 = line_origin + dir * pair[1];
            segments.push((p1, p2));
        }

        offset += spacing;
    }

    segments
}

impl Layer for AreaLayer {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn handle_input(&mut self, response: &Response, projection: &MapProjection) -> bool {
        match self.mode {
            AreaMode::Disabled => false,
            AreaMode::Modify => self.handle_modify_input(response, projection),
        }
    }

    fn draw(&self, painter: &Painter, projection: &MapProjection) {
        for area in &self.areas {
            let points = area.get_points(projection);
            let screen_points: Vec<Pos2> = points.iter().map(|p| projection.project(*p)).collect();

            // Draw polygon outline
            if screen_points.len() >= 3 {
                // Use a generic path for the stroke.
                let path_shape = Shape::Path(egui::epaint::PathShape {
                    points: screen_points.clone(),
                    closed: true,
                    fill: Color32::TRANSPARENT,
                    stroke: area.stroke.into(),
                });
                painter.add(path_shape);

                match area.fill_type {
                    FillType::None => { /* No fill */ }
                    FillType::Solid => {
                        // Triangulate for the fill.
                        let flat_points: Vec<f64> = screen_points
                            .iter()
                            .flat_map(|p| [f64::from(p.x), f64::from(p.y)])
                            .collect();
                        match earcutr::earcut(&flat_points, &[], 2) {
                            Ok(indices) => {
                                let mesh = Mesh {
                                    vertices: screen_points
                                        .iter()
                                        .map(|p| egui::epaint::Vertex {
                                            pos: *p,
                                            uv: Default::default(),
                                            color: area.fill,
                                        })
                                        .collect(),
                                    indices: indices.into_iter().map(|i| i as u32).collect(),
                                    ..Default::default()
                                };
                                painter.add(Shape::Mesh(mesh.into()));
                            }
                            Err(e) => {
                                warn!("Failed to triangulate area: {e:?}");
                            }
                        }
                    }
                    FillType::Hatching => {
                        let segments = generate_hatching_lines(
                            &screen_points,
                            8.0,
                            std::f32::consts::FRAC_PI_4,
                        );
                        for (a, b) in segments {
                            painter.line_segment([a, b], area.stroke);
                        }
                    }
                }
            } else {
                warn!("Invalid amount of points in area. {area:?}");
            }

            // Draw nodes only when in modify mode
            if self.mode == AreaMode::Modify {
                match &area.shape {
                    AreaShape::Polygon(_) => {
                        for point in &screen_points {
                            painter.circle_filled(*point, self.node_radius, self.node_fill);
                        }
                    }
                    AreaShape::Circle {
                        center,
                        radius,
                        points: _,
                    } => {
                        let center_screen = projection.project(*center);

                        // Convert radius from meters to screen pixels to correctly position the handle.
                        let point_on_circle_geo = GeoPos {
                            lon: center.lon
                                + (radius / (111_320.0 * center.lat.to_radians().cos())),
                            lat: center.lat,
                        };
                        let point_on_circle_screen = projection.project(point_on_circle_geo);
                        let radius_pixels = center_screen.distance(point_on_circle_screen);

                        painter.circle_filled(center_screen, self.node_radius, self.node_fill);
                        let radius_handle_pos = center_screen + egui::vec2(radius_pixels, 0.0);
                        painter.circle_filled(radius_handle_pos, self.node_radius, self.node_fill);
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::projection::MapProjection;
    use egui::{Rect, pos2, vec2};

    // Helper for creating a dummy projection for tests
    fn dummy_projection() -> MapProjection {
        MapProjection::new(
            10,                // zoom
            (0.0, 0.0).into(), // center
            Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 1000.0)),
        )
    }

    #[test]
    fn area_layer_new() {
        let layer = AreaLayer::default();
        assert_eq!(layer.mode, AreaMode::Disabled);
        assert!(layer.areas.is_empty());
        assert_eq!(layer.node_radius, 5.0);
    }

    #[test]
    fn area_layer_add_area() {
        let mut layer = AreaLayer::default();
        assert_eq!(layer.areas.len(), 0);

        layer.add_area(Area {
            shape: AreaShape::Polygon(vec![
                (0.0, 0.0).into(),
                (1.0, 0.0).into(),
                (0.0, 1.0).into(),
            ]),
            stroke: Default::default(),
            fill: Default::default(),
            fill_type: Default::default(),
        });

        assert_eq!(layer.areas.len(), 1);
    }

    #[test]
    fn circle_get_points_with_fixed_number() {
        let projection = dummy_projection();
        let area = Area {
            shape: AreaShape::Circle {
                center: (0.0, 0.0).into(),
                radius: 1000.0,
                points: Some(16),
            },
            stroke: Default::default(),
            fill: Default::default(),
            fill_type: Default::default(),
        };

        let points = area.get_points(&projection);
        assert_eq!(points.len(), 16);
    }

    #[test]
    fn find_object_at_empty() {
        let layer = AreaLayer::default();
        let projection = dummy_projection();
        let position = pos2(100.0, 100.0);

        assert!(layer.find_object_at(position, &projection).is_none());
    }

    #[test]
    fn find_object_at_polygon_node() {
        let projection = dummy_projection();
        let mut layer = AreaLayer::default();
        let geo_pos = projection.unproject(pos2(100.0, 100.0));

        layer.add_area(Area {
            shape: AreaShape::Polygon(vec![geo_pos]),
            stroke: Default::default(),
            fill: Default::default(),
            fill_type: Default::default(),
        });

        // Position is exactly on the node
        let found = layer.find_object_at(pos2(100.0, 100.0), &projection);
        assert!(matches!(
            found,
            Some(DraggedObject::PolygonNode {
                area_index: 0,
                node_index: 0
            })
        ));

        // Position is slightly off but within tolerance
        let found_nearby = layer.find_object_at(pos2(101.0, 101.0), &projection);
        assert!(matches!(
            found_nearby,
            Some(DraggedObject::PolygonNode {
                area_index: 0,
                node_index: 0
            })
        ));

        // Position is too far
        let not_found = layer.find_object_at(pos2(200.0, 200.0), &projection);
        assert!(not_found.is_none());
    }

    #[test]
    fn area_layer_serde() {
        let mut layer = AreaLayer::default();
        layer.add_area(Area {
            shape: AreaShape::Polygon(vec![(0.0, 0.0).into()]),
            stroke: Stroke::new(1.0, Color32::RED),
            fill: Color32::BLUE,
            fill_type: Default::default(),
        });

        let json = serde_json::to_string(&layer).unwrap();
        let deserialized: AreaLayer = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.areas.len(), 1);
        assert_eq!(deserialized.mode, AreaMode::Disabled); // Restored to default
    }

    #[test]
    fn test_can_triangulate_valid() {
        let projection = dummy_projection();
        let area = Area {
            shape: AreaShape::Polygon(vec![
                (0.0, 0.0).into(),
                (10.0, 0.0).into(),
                (0.0, 10.0).into(),
            ]),
            stroke: Default::default(),
            fill: Default::default(),
            fill_type: Default::default(),
        };

        assert!(area.can_triangulate(&projection));
    }

    #[test]
    fn test_can_triangulate_insufficient_points() {
        let projection = dummy_projection();
        let area = Area {
            shape: AreaShape::Polygon(vec![(0.0, 0.0).into(), (10.0, 0.0).into()]),
            stroke: Default::default(),
            fill: Default::default(),
            fill_type: Default::default(),
        };

        // Should return true as we don't consider < 3 points as a triangulation failure
        // (it simply doesn't draw anything)
        assert!(area.can_triangulate(&projection));
    }

    #[cfg(feature = "geojson")]
    mod geojson_tests {
        use super::*;

        #[test]
        fn area_layer_geojson_polygon() {
            let mut layer = AreaLayer::default();
            layer.add_area(Area {
                shape: AreaShape::Polygon(vec![
                    (10.0, 20.0).into(),
                    (30.0, 40.0).into(),
                    (50.0, 60.0).into(),
                ]),
                stroke: Stroke::new(2.0, Color32::from_rgb(0, 0, 255)),
                fill: Color32::from_rgba_unmultiplied(255, 0, 0, 128),
                fill_type: Default::default(),
            });

            let geojson_str = layer.to_geojson_str().unwrap();

            let mut new_layer = AreaLayer::default();
            new_layer.from_geojson_str(&geojson_str).unwrap();

            assert_eq!(new_layer.areas.len(), 1);
            assert_eq!(layer.areas[0], new_layer.areas[0]);
        }

        #[test]
        fn area_layer_geojson_circle() {
            let mut layer = AreaLayer::default();
            layer.add_area(Area {
                shape: AreaShape::Circle {
                    center: (10.0, 20.0).into(),
                    radius: 1000.0,
                    points: Some(32),
                },
                stroke: Default::default(),
                fill: Default::default(),
                fill_type: Default::default(),
            });

            let geojson_str = layer.to_geojson_str().unwrap();
            let mut new_layer = AreaLayer::default();
            new_layer.from_geojson_str(&geojson_str).unwrap();

            assert_eq!(new_layer.areas.len(), 1);
            assert_eq!(layer.areas[0].shape, new_layer.areas[0].shape);
        }
    }

    #[test]
    fn find_node_at_on_segment() {
        let projection = dummy_projection();
        let mut layer = AreaLayer::default();

        let p1 = projection.unproject(pos2(100.0, 100.0));
        let p2 = projection.unproject(pos2(200.0, 100.0));

        layer.add_area(Area {
            shape: AreaShape::Polygon(vec![p1, p2, projection.unproject(pos2(150.0, 200.0))]), // Triangle
            stroke: Default::default(),
            fill: Default::default(),
            fill_type: Default::default(),
        });

        // Click exactly between p1 and p2
        let click_pos = pos2(150.0, 100.0);

        // Should NOT find a node
        assert!(layer.find_node_at(click_pos, &projection).is_none());

        // Should find the segment
        let segment = layer.find_line_segment_at(click_pos, &projection);
        assert!(segment.is_some());
        assert_eq!(segment.unwrap().0, 0); // area_index
        assert_eq!(segment.unwrap().1, 0);
    }
}