skia-rs-path 0.2.3

Path geometry and operations for skia-rs
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
//! Path boolean operations (union, intersect, difference, xor).
//!
//! This module implements boolean operations on paths using a scanline-based
//! algorithm inspired by the Bentley-Ottmann algorithm.

use crate::{Path, PathBuilder, PathElement};
use skia_rs_core::{Point, Rect, Scalar};

/// Operation type for path boolean operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum PathOp {
    /// Subtract the second path from the first.
    Difference = 0,
    /// Intersect the two paths.
    Intersect,
    /// Union the two paths.
    Union,
    /// XOR the two paths (areas in one but not both).
    Xor,
    /// Reverse difference (subtract first from second).
    ReverseDifference,
}

/// Perform a boolean operation on two paths.
///
/// # Arguments
/// * `path1` - The first path
/// * `path2` - The second path
/// * `op` - The operation to perform
///
/// # Returns
/// The resulting path, or None if the operation fails
///
/// # Limitations
///
/// The current polygon-based implementation has known correctness
/// issues for non-trivial inputs:
///
/// - `PathOp::Intersect` uses Sutherland-Hodgman clipping, which
///   only produces correct results when both inputs are convex
///   polygons. Concave inputs (circles, complex shapes) may produce
///   incorrect intersection results.
///
/// - `PathOp::Difference`, `PathOp::ReverseDifference`, and
///   `PathOp::Xor` only handle the trivial cases of full containment
///   or full disjointness. Partial overlaps return the unmodified
///   subject path.
///
/// A robust implementation requires either a Weiler-Atherton or
/// sweep-line clipping algorithm. Tracked as GAP-C4 and GAP-C5 in
/// the foundation audit; planned for a future release.
pub fn op(path1: &Path, path2: &Path, op: PathOp) -> Option<Path> {
    PathOps::new(path1, path2, op).compute()
}

/// Simplify a path by removing overlapping regions.
pub fn simplify(path: &Path) -> Option<Path> {
    // Simplification is union with self
    let empty = Path::new();
    op(path, &empty, PathOp::Union)
}

/// Internal path operations implementation.
struct PathOps<'a> {
    path1: &'a Path,
    path2: &'a Path,
    op: PathOp,
}

impl<'a> PathOps<'a> {
    fn new(path1: &'a Path, path2: &'a Path, op: PathOp) -> Self {
        Self { path1, path2, op }
    }

    fn compute(&self) -> Option<Path> {
        // Handle empty paths
        if self.path1.is_empty() && self.path2.is_empty() {
            return Some(Path::new());
        }

        if self.path1.is_empty() {
            return match self.op {
                PathOp::Union | PathOp::ReverseDifference | PathOp::Xor => Some(self.path2.clone()),
                PathOp::Difference | PathOp::Intersect => Some(Path::new()),
            };
        }

        if self.path2.is_empty() {
            return match self.op {
                PathOp::Union | PathOp::Difference | PathOp::Xor => Some(self.path1.clone()),
                PathOp::Intersect | PathOp::ReverseDifference => Some(Path::new()),
            };
        }

        // Check if bounding boxes intersect
        let bounds1 = self.path1.bounds();
        let bounds2 = self.path2.bounds();

        if !bounds_intersect(&bounds1, &bounds2) {
            return match self.op {
                PathOp::Union => {
                    // Combine both paths
                    let mut builder = PathBuilder::new();
                    self.add_path_to_builder(&mut builder, self.path1);
                    self.add_path_to_builder(&mut builder, self.path2);
                    Some(builder.build())
                }
                PathOp::Intersect => Some(Path::new()),
                PathOp::Difference => Some(self.path1.clone()),
                PathOp::ReverseDifference => Some(self.path2.clone()),
                PathOp::Xor => {
                    let mut builder = PathBuilder::new();
                    self.add_path_to_builder(&mut builder, self.path1);
                    self.add_path_to_builder(&mut builder, self.path2);
                    Some(builder.build())
                }
            };
        }

        // For complex cases, use polygon-based operations
        self.compute_polygon_ops()
    }

    fn add_path_to_builder(&self, builder: &mut PathBuilder, path: &Path) {
        for elem in path.iter() {
            match elem {
                PathElement::Move(p) => {
                    builder.move_to(p.x, p.y);
                }
                PathElement::Line(p) => {
                    builder.line_to(p.x, p.y);
                }
                PathElement::Quad(c, p) => {
                    builder.quad_to(c.x, c.y, p.x, p.y);
                }
                PathElement::Conic(c, p, w) => {
                    builder.conic_to(c.x, c.y, p.x, p.y, w);
                }
                PathElement::Cubic(c1, c2, p) => {
                    builder.cubic_to(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
                }
                PathElement::Close => {
                    builder.close();
                }
            }
        }
    }

    fn compute_polygon_ops(&self) -> Option<Path> {
        // Convert paths to polygons (linearize curves)
        let polys1 = path_to_polygons(self.path1, 0.5);
        let polys2 = path_to_polygons(self.path2, 0.5);

        // Perform the boolean operation
        let result_polys = match self.op {
            PathOp::Union => polygon_union(&polys1, &polys2),
            PathOp::Intersect => polygon_intersect(&polys1, &polys2),
            PathOp::Difference => polygon_difference(&polys1, &polys2),
            PathOp::ReverseDifference => polygon_difference(&polys2, &polys1),
            PathOp::Xor => polygon_xor(&polys1, &polys2),
        };

        // Convert result back to path
        Some(polygons_to_path(&result_polys))
    }
}

fn bounds_intersect(a: &Rect, b: &Rect) -> bool {
    a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top
}

/// A simple polygon represented as a list of points.
#[derive(Debug, Clone)]
struct Polygon {
    points: Vec<Point>,
    is_hole: bool,
}

impl Polygon {
    fn new() -> Self {
        Self {
            points: Vec::new(),
            is_hole: false,
        }
    }

    fn add_point(&mut self, p: Point) {
        self.points.push(p);
    }

    fn is_empty(&self) -> bool {
        self.points.len() < 3
    }

    fn bounds(&self) -> Rect {
        if self.points.is_empty() {
            return Rect::EMPTY;
        }

        let mut min_x = self.points[0].x;
        let mut max_x = self.points[0].x;
        let mut min_y = self.points[0].y;
        let mut max_y = self.points[0].y;

        for p in &self.points[1..] {
            min_x = min_x.min(p.x);
            max_x = max_x.max(p.x);
            min_y = min_y.min(p.y);
            max_y = max_y.max(p.y);
        }

        Rect::new(min_x, min_y, max_x, max_y)
    }

    fn signed_area(&self) -> Scalar {
        if self.points.len() < 3 {
            return 0.0;
        }

        let mut area = 0.0;
        let n = self.points.len();
        for i in 0..n {
            let j = (i + 1) % n;
            area += self.points[i].x * self.points[j].y;
            area -= self.points[j].x * self.points[i].y;
        }
        area / 2.0
    }

    fn contains_point(&self, p: Point) -> bool {
        if self.points.len() < 3 {
            return false;
        }

        let mut winding = 0;
        let n = self.points.len();

        for i in 0..n {
            let j = (i + 1) % n;
            let p1 = self.points[i];
            let p2 = self.points[j];

            if p1.y <= p.y {
                if p2.y > p.y {
                    // Upward crossing
                    if is_left(p1, p2, p) > 0.0 {
                        winding += 1;
                    }
                }
            } else if p2.y <= p.y {
                // Downward crossing
                if is_left(p1, p2, p) < 0.0 {
                    winding -= 1;
                }
            }
        }

        winding != 0
    }
}

fn is_left(p0: Point, p1: Point, p2: Point) -> Scalar {
    (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y)
}

/// Convert a path to a list of polygons.
fn path_to_polygons(path: &Path, tolerance: Scalar) -> Vec<Polygon> {
    let mut polygons = Vec::new();
    let mut current_poly = Polygon::new();
    let mut current_point = Point::new(0.0, 0.0);
    let mut first_point = Point::new(0.0, 0.0);

    for elem in path.iter() {
        match elem {
            PathElement::Move(p) => {
                if !current_poly.is_empty() {
                    polygons.push(current_poly);
                }
                current_poly = Polygon::new();
                current_poly.add_point(p);
                current_point = p;
                first_point = p;
            }
            PathElement::Line(p) => {
                current_poly.add_point(p);
                current_point = p;
            }
            PathElement::Quad(c, p) => {
                // Linearize quadratic bezier
                linearize_quad(&mut current_poly, current_point, c, p, tolerance);
                current_point = p;
            }
            PathElement::Conic(c, p, w) => {
                let pts = linearize_conic(current_point, c, p, w, tolerance);
                current_poly.points.extend_from_slice(&pts[1..]);
                current_point = p;
            }
            PathElement::Cubic(c1, c2, p) => {
                // Linearize cubic bezier
                linearize_cubic(&mut current_poly, current_point, c1, c2, p, tolerance);
                current_point = p;
            }
            PathElement::Close => {
                if !current_poly.is_empty() {
                    // Determine if this is a hole based on winding
                    current_poly.is_hole = current_poly.signed_area() < 0.0;
                    polygons.push(current_poly);
                }
                current_poly = Polygon::new();
                current_point = first_point;
            }
        }
    }

    if !current_poly.is_empty() {
        current_poly.is_hole = current_poly.signed_area() < 0.0;
        polygons.push(current_poly);
    }

    polygons
}

fn linearize_quad(poly: &mut Polygon, p0: Point, p1: Point, p2: Point, tolerance: Scalar) {
    // Check if curve is flat enough
    let d = distance_to_line(p1, p0, p2);
    if d < tolerance {
        poly.add_point(p2);
    } else {
        // Subdivide
        let q0 = p0.lerp(p1, 0.5);
        let q1 = p1.lerp(p2, 0.5);
        let r = q0.lerp(q1, 0.5);

        linearize_quad(poly, p0, q0, r, tolerance);
        linearize_quad(poly, r, q1, p2, tolerance);
    }
}

/// Linearize a conic (rational quadratic Bezier) into line segments.
fn linearize_conic(
    start: Point,
    ctrl: Point,
    end: Point,
    weight: Scalar,
    tolerance: Scalar,
) -> Vec<Point> {
    let mut output = vec![start];
    crate::flatten::flatten_conic_adaptive(&mut output, start, ctrl, end, weight, tolerance);
    output
}

fn linearize_cubic(
    poly: &mut Polygon,
    p0: Point,
    p1: Point,
    p2: Point,
    p3: Point,
    tolerance: Scalar,
) {
    // Check if curve is flat enough
    let d1 = distance_to_line(p1, p0, p3);
    let d2 = distance_to_line(p2, p0, p3);
    if d1.max(d2) < tolerance {
        poly.add_point(p3);
    } else {
        // Subdivide using de Casteljau's algorithm
        let q0 = p0.lerp(p1, 0.5);
        let q1 = p1.lerp(p2, 0.5);
        let q2 = p2.lerp(p3, 0.5);
        let r0 = q0.lerp(q1, 0.5);
        let r1 = q1.lerp(q2, 0.5);
        let s = r0.lerp(r1, 0.5);

        linearize_cubic(poly, p0, q0, r0, s, tolerance);
        linearize_cubic(poly, s, r1, q2, p3, tolerance);
    }
}

fn distance_to_line(p: Point, line_start: Point, line_end: Point) -> Scalar {
    let dx = line_end.x - line_start.x;
    let dy = line_end.y - line_start.y;
    let len_sq = dx * dx + dy * dy;

    if len_sq < 1e-10 {
        return p.distance(&line_start);
    }

    let cross = (p.x - line_start.x) * dy - (p.y - line_start.y) * dx;
    cross.abs() / len_sq.sqrt()
}

/// Union of two polygon sets.
fn polygon_union(polys1: &[Polygon], polys2: &[Polygon]) -> Vec<Polygon> {
    let mut result = Vec::new();

    // Simple implementation: add all polygons and merge overlapping ones
    for poly in polys1 {
        if !poly.is_empty() {
            result.push(poly.clone());
        }
    }

    for poly in polys2 {
        if !poly.is_empty() {
            // Check if this polygon is fully contained in any existing polygon
            let mut fully_contained = false;
            for existing in &result {
                if polygon_contains_polygon(existing, poly) {
                    fully_contained = true;
                    break;
                }
            }

            if !fully_contained {
                result.push(poly.clone());
            }
        }
    }

    result
}

/// Intersection of two polygon sets.
fn polygon_intersect(polys1: &[Polygon], polys2: &[Polygon]) -> Vec<Polygon> {
    let mut result = Vec::new();

    for poly1 in polys1 {
        for poly2 in polys2 {
            if let Some(intersection) = intersect_convex_polygons(poly1, poly2) {
                if !intersection.is_empty() {
                    result.push(intersection);
                }
            }
        }
    }

    result
}

/// Difference of two polygon sets (polys1 - polys2).
fn polygon_difference(polys1: &[Polygon], polys2: &[Polygon]) -> Vec<Polygon> {
    let mut result = Vec::new();

    for poly1 in polys1 {
        if poly1.is_empty() {
            continue;
        }

        let mut remaining = vec![poly1.clone()];

        for poly2 in polys2 {
            if poly2.is_empty() {
                continue;
            }

            let mut new_remaining = Vec::new();
            for rem in remaining {
                // Check bounds overlap
                let b1 = rem.bounds();
                let b2 = poly2.bounds();

                if !bounds_intersect(&b1, &b2) {
                    new_remaining.push(rem);
                } else {
                    // Subtract poly2 from rem
                    let subtracted = subtract_polygon(&rem, poly2);
                    new_remaining.extend(subtracted);
                }
            }
            remaining = new_remaining;
        }

        result.extend(remaining);
    }

    result
}

/// XOR of two polygon sets.
fn polygon_xor(polys1: &[Polygon], polys2: &[Polygon]) -> Vec<Polygon> {
    // XOR = (A - B) ∪ (B - A)
    let a_minus_b = polygon_difference(polys1, polys2);
    let b_minus_a = polygon_difference(polys2, polys1);

    let mut result = a_minus_b;
    result.extend(b_minus_a);
    result
}

/// Check if polygon a fully contains polygon b.
fn polygon_contains_polygon(a: &Polygon, b: &Polygon) -> bool {
    if b.points.is_empty() {
        return true;
    }

    // Check if all points of b are inside a
    for p in &b.points {
        if !a.contains_point(*p) {
            return false;
        }
    }

    true
}

/// Intersect two convex polygons using Sutherland-Hodgman algorithm.
fn intersect_convex_polygons(subject: &Polygon, clip: &Polygon) -> Option<Polygon> {
    if subject.is_empty() || clip.is_empty() {
        return None;
    }

    let mut output = subject.points.clone();

    let n = clip.points.len();
    for i in 0..n {
        if output.is_empty() {
            break;
        }

        let j = (i + 1) % n;
        let edge_start = clip.points[i];
        let edge_end = clip.points[j];

        let input = output;
        output = Vec::new();

        for k in 0..input.len() {
            let current = input[k];
            let next = input[(k + 1) % input.len()];

            let current_inside = is_left(edge_start, edge_end, current) >= 0.0;
            let next_inside = is_left(edge_start, edge_end, next) >= 0.0;

            if current_inside {
                output.push(current);

                if !next_inside {
                    if let Some(intersection) =
                        line_intersection(current, next, edge_start, edge_end)
                    {
                        output.push(intersection);
                    }
                }
            } else if next_inside {
                if let Some(intersection) = line_intersection(current, next, edge_start, edge_end) {
                    output.push(intersection);
                }
            }
        }
    }

    if output.len() >= 3 {
        let mut result = Polygon::new();
        result.points = output;
        Some(result)
    } else {
        None
    }
}

/// Subtract one polygon from another.
fn subtract_polygon(subject: &Polygon, clip: &Polygon) -> Vec<Polygon> {
    // Simplified implementation: if clip contains subject, return empty
    // Otherwise, return subject (proper implementation would clip)
    if polygon_contains_polygon(clip, subject) {
        return Vec::new();
    }

    // Check if there's any overlap
    let bounds1 = subject.bounds();
    let bounds2 = clip.bounds();

    if !bounds_intersect(&bounds1, &bounds2) {
        return vec![subject.clone()];
    }

    // For a proper implementation, we would:
    // 1. Find all intersection points
    // 2. Build a planar graph
    // 3. Walk the graph to find result polygons
    // For now, return subject if not fully contained
    vec![subject.clone()]
}

/// Find intersection point of two line segments.
fn line_intersection(p1: Point, p2: Point, p3: Point, p4: Point) -> Option<Point> {
    let d1 = p2 - p1;
    let d2 = p4 - p3;

    let cross = d1.x * d2.y - d1.y * d2.x;

    if cross.abs() < 1e-10 {
        return None; // Lines are parallel
    }

    let d3 = p3 - p1;
    let t = (d3.x * d2.y - d3.y * d2.x) / cross;

    if t >= 0.0 && t <= 1.0 {
        Some(p1 + d1 * t)
    } else {
        None
    }
}

/// Convert polygons back to a path.
fn polygons_to_path(polygons: &[Polygon]) -> Path {
    let mut builder = PathBuilder::new();

    for poly in polygons {
        if poly.points.len() < 3 {
            continue;
        }

        builder.move_to(poly.points[0].x, poly.points[0].y);
        for p in &poly.points[1..] {
            builder.line_to(p.x, p.y);
        }
        builder.close();
    }

    builder.build()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_paths() {
        let empty = Path::new();
        let result = op(&empty, &empty, PathOp::Union);
        assert!(result.is_some());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_union_non_overlapping() {
        let mut builder1 = PathBuilder::new();
        builder1.add_rect(&Rect::from_xywh(0.0, 0.0, 10.0, 10.0));
        let path1 = builder1.build();

        let mut builder2 = PathBuilder::new();
        builder2.add_rect(&Rect::from_xywh(20.0, 0.0, 10.0, 10.0));
        let path2 = builder2.build();

        let result = op(&path1, &path2, PathOp::Union);
        assert!(result.is_some());
        let result = result.unwrap();
        assert!(!result.is_empty());
    }

    #[test]
    fn test_intersect_non_overlapping() {
        let mut builder1 = PathBuilder::new();
        builder1.add_rect(&Rect::from_xywh(0.0, 0.0, 10.0, 10.0));
        let path1 = builder1.build();

        let mut builder2 = PathBuilder::new();
        builder2.add_rect(&Rect::from_xywh(20.0, 0.0, 10.0, 10.0));
        let path2 = builder2.build();

        let result = op(&path1, &path2, PathOp::Intersect);
        assert!(result.is_some());
        let result = result.unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_path_to_polygons_handles_conic_weight() {
        // Quarter circle: M (1,0), conic to (1,1) end (0,1) with weight sqrt(2)/2.
        // Close back through the origin so the polygon has enough points to be kept.
        // Linearized points along the arc should lie on the unit circle.
        let mut builder = PathBuilder::new();
        builder.move_to(1.0, 0.0);
        builder.conic_to(1.0, 1.0, 0.0, 1.0, std::f32::consts::FRAC_1_SQRT_2);
        builder.line_to(0.0, 0.0);
        builder.close();
        let path = builder.build();

        // Use a tight tolerance so the arc gets subdivided finely.
        let polygons = path_to_polygons(&path, 0.01);
        assert!(!polygons.is_empty(), "Should produce at least one polygon");

        // Filter to points on the arc portion (exclude origin and axes endpoints
        // that are trivially correct). Check every point that is NOT (0,0):
        // arc points should be near the unit circle, axis points are at radius 1
        // already, and the origin is at radius 0 — skip it.
        let polygon = &polygons[0];
        let mut arc_point_count = 0;
        for p in &polygon.points {
            let dist_sq = p.x * p.x + p.y * p.y;
            if dist_sq < 0.5 {
                // Origin — skip
                continue;
            }
            arc_point_count += 1;
            assert!(
                (dist_sq - 1.0).abs() < 0.05,
                "Point ({}, {}) should be near unit circle (dist² = {})",
                p.x, p.y, dist_sq
            );
        }
        // Verify we actually got subdivided arc points, not just endpoints.
        assert!(
            arc_point_count >= 4,
            "Expected at least 4 arc points from subdivision, got {}",
            arc_point_count
        );
    }

    #[test]
    fn test_polygon_contains_point() {
        let mut poly = Polygon::new();
        poly.add_point(Point::new(0.0, 0.0));
        poly.add_point(Point::new(10.0, 0.0));
        poly.add_point(Point::new(10.0, 10.0));
        poly.add_point(Point::new(0.0, 10.0));

        assert!(poly.contains_point(Point::new(5.0, 5.0)));
        assert!(!poly.contains_point(Point::new(15.0, 5.0)));
    }
}