skia-rs-path 0.2.7

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
//! Path utility functions.
//!
//! This module provides utility functions for path manipulation,
//! including stroke-to-fill conversion.

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

/// Stroke cap style for stroke-to-fill conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(u8)]
pub enum StrokeCap {
    /// Flat cap - no extension beyond the endpoint.
    #[default]
    Butt = 0,
    /// Round cap - semicircle at each endpoint.
    Round,
    /// Square cap - extends by half the stroke width.
    Square,
}

/// Stroke join style for stroke-to-fill conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(u8)]
pub enum StrokeJoin {
    /// Miter join - sharp corners.
    #[default]
    Miter = 0,
    /// Round join - rounded corners.
    Round,
    /// Bevel join - flat corners.
    Bevel,
}

/// Parameters for stroke-to-fill conversion.
#[derive(Debug, Clone)]
pub struct StrokeParams {
    /// Stroke width.
    pub width: Scalar,
    /// Stroke cap style.
    pub cap: StrokeCap,
    /// Stroke join style.
    pub join: StrokeJoin,
    /// Miter limit (for miter joins).
    pub miter_limit: Scalar,
}

impl Default for StrokeParams {
    fn default() -> Self {
        Self {
            width: 1.0,
            cap: StrokeCap::Butt,
            join: StrokeJoin::Miter,
            miter_limit: 4.0,
        }
    }
}

impl StrokeParams {
    /// Create new stroke parameters.
    pub fn new(width: Scalar) -> Self {
        Self {
            width,
            ..Default::default()
        }
    }

    /// Set the stroke cap.
    pub fn with_cap(mut self, cap: StrokeCap) -> Self {
        self.cap = cap;
        self
    }

    /// Set the stroke join.
    pub fn with_join(mut self, join: StrokeJoin) -> Self {
        self.join = join;
        self
    }

    /// Set the miter limit.
    pub fn with_miter_limit(mut self, limit: Scalar) -> Self {
        self.miter_limit = limit;
        self
    }
}

/// Convert a stroked path to a filled path.
///
/// This creates an outline around the input path that, when filled,
/// would produce the same visual result as stroking the original path.
///
/// # Arguments
/// * `path` - The input path to stroke.
/// * `params` - Stroke parameters (width, cap, join, miter limit).
///
/// # Returns
/// The stroked path as a fillable outline, or `None` if the path is empty.
pub fn stroke_to_fill(path: &Path, params: &StrokeParams) -> Option<Path> {
    if path.is_empty() || params.width <= 0.0 {
        return None;
    }

    let half_width = params.width / 2.0;
    let mut builder = PathBuilder::new();

    // Collect path elements into contours, tracking closed state per contour
    let mut contours: Vec<(Vec<Point>, bool)> = Vec::new();
    let mut current_contour: Vec<Point> = Vec::new();
    let mut current_closed = false;

    for element in path.iter() {
        match element {
            PathElement::Move(p) => {
                if !current_contour.is_empty() {
                    contours.push((std::mem::take(&mut current_contour), current_closed));
                }
                current_contour.push(p);
                current_closed = false;
            }
            PathElement::Line(p) => {
                current_contour.push(p);
            }
            PathElement::Quad(ctrl, end) => {
                // Flatten quadratic to lines
                if let Some(&start) = current_contour.last() {
                    flatten_quad(&mut current_contour, start, ctrl, end, 4);
                }
            }
            PathElement::Cubic(ctrl1, ctrl2, end) => {
                // Flatten cubic to lines
                if let Some(&start) = current_contour.last() {
                    flatten_cubic(&mut current_contour, start, ctrl1, ctrl2, end, 8);
                }
            }
            PathElement::Conic(ctrl, end, weight) => {
                // Flatten conic to lines (approximate as quad)
                if let Some(&start) = current_contour.last() {
                    let mid_ctrl = Point::new(
                        start.x * (1.0 - weight) / 2.0
                            + ctrl.x * weight
                            + end.x * (1.0 - weight) / 2.0,
                        start.y * (1.0 - weight) / 2.0
                            + ctrl.y * weight
                            + end.y * (1.0 - weight) / 2.0,
                    );
                    flatten_quad(&mut current_contour, start, mid_ctrl, end, 4);
                }
            }
            PathElement::Close => {
                current_closed = true;
            }
        }
    }

    if !current_contour.is_empty() {
        contours.push((current_contour, current_closed));
    }

    // Process each contour using its own closed state
    for (contour, is_closed) in &contours {
        if contour.len() < 2 {
            continue;
        }

        stroke_contour(&mut builder, contour, *is_closed, half_width, params);
    }

    Some(builder.build())
}

fn stroke_contour(
    builder: &mut PathBuilder,
    points: &[Point],
    is_closed: bool,
    half_width: Scalar,
    params: &StrokeParams,
) {
    if points.len() < 2 {
        return;
    }

    let n = points.len();

    // Compute normals for each segment
    let mut normals: Vec<Point> = Vec::with_capacity(n - 1);
    for i in 0..n - 1 {
        let dx = points[i + 1].x - points[i].x;
        let dy = points[i + 1].y - points[i].y;
        let len = (dx * dx + dy * dy).sqrt();
        if len > 0.0 {
            normals.push(Point::new(-dy / len, dx / len));
        } else {
            normals.push(Point::new(0.0, 1.0));
        }
    }

    if normals.is_empty() {
        return;
    }

    // Build left side (offset by +half_width)
    let mut left_side: Vec<Point> = Vec::with_capacity(n);
    // Build right side (offset by -half_width)
    let mut right_side: Vec<Point> = Vec::with_capacity(n);

    // First point
    let first_normal = normals[0];
    left_side.push(Point::new(
        points[0].x + first_normal.x * half_width,
        points[0].y + first_normal.y * half_width,
    ));
    right_side.push(Point::new(
        points[0].x - first_normal.x * half_width,
        points[0].y - first_normal.y * half_width,
    ));

    // Interior points with join handling
    for i in 1..n - 1 {
        let n1 = normals[i - 1];
        let n2 = normals[i];

        // Average normal for the join
        let avg = Point::new(n1.x + n2.x, n1.y + n2.y);
        let avg_len = avg.length();

        if avg_len > 0.001 {
            let scale = half_width / avg_len;
            let offset = Point::new(avg.x * scale, avg.y * scale);

            match params.join {
                StrokeJoin::Miter => {
                    // Compute miter length
                    let miter_len = 1.0 / (avg_len / 2.0);
                    if miter_len <= params.miter_limit {
                        left_side.push(Point::new(
                            points[i].x + offset.x * miter_len,
                            points[i].y + offset.y * miter_len,
                        ));
                        right_side.push(Point::new(
                            points[i].x - offset.x * miter_len,
                            points[i].y - offset.y * miter_len,
                        ));
                    } else {
                        // Fallback to bevel
                        left_side.push(Point::new(
                            points[i].x + n1.x * half_width,
                            points[i].y + n1.y * half_width,
                        ));
                        left_side.push(Point::new(
                            points[i].x + n2.x * half_width,
                            points[i].y + n2.y * half_width,
                        ));
                        right_side.push(Point::new(
                            points[i].x - n1.x * half_width,
                            points[i].y - n1.y * half_width,
                        ));
                        right_side.push(Point::new(
                            points[i].x - n2.x * half_width,
                            points[i].y - n2.y * half_width,
                        ));
                    }
                }
                StrokeJoin::Bevel => {
                    left_side.push(Point::new(
                        points[i].x + n1.x * half_width,
                        points[i].y + n1.y * half_width,
                    ));
                    left_side.push(Point::new(
                        points[i].x + n2.x * half_width,
                        points[i].y + n2.y * half_width,
                    ));
                    right_side.push(Point::new(
                        points[i].x - n1.x * half_width,
                        points[i].y - n1.y * half_width,
                    ));
                    right_side.push(Point::new(
                        points[i].x - n2.x * half_width,
                        points[i].y - n2.y * half_width,
                    ));
                }
                StrokeJoin::Round => {
                    // Generate arc segments for the outer side of the join.
                    // Both the left and right sides sweep from their incoming
                    // normal offset to their outgoing normal offset around the
                    // join vertex, using line subdivision scaled to the angular
                    // sweep (minimum 4 segments).
                    let left_start_angle =
                        (n1.y * half_width).atan2(n1.x * half_width);
                    let left_end_angle =
                        (n2.y * half_width).atan2(n2.x * half_width);
                    let mut left_delta = left_end_angle - left_start_angle;
                    if left_delta > std::f32::consts::PI {
                        left_delta -= std::f32::consts::TAU;
                    } else if left_delta < -std::f32::consts::PI {
                        left_delta += std::f32::consts::TAU;
                    }
                    let n_segs = ((left_delta.abs()
                        / std::f32::consts::FRAC_PI_4)
                        .ceil() as usize)
                        .max(4);
                    for k in 0..=n_segs {
                        let t = k as Scalar / n_segs as Scalar;
                        let a = left_start_angle + left_delta * t;
                        left_side.push(Point::new(
                            points[i].x + a.cos() * half_width,
                            points[i].y + a.sin() * half_width,
                        ));
                        right_side.push(Point::new(
                            points[i].x - a.cos() * half_width,
                            points[i].y - a.sin() * half_width,
                        ));
                    }
                }
            }
        } else {
            // Parallel segments, use normal offset
            left_side.push(Point::new(
                points[i].x + n1.x * half_width,
                points[i].y + n1.y * half_width,
            ));
            right_side.push(Point::new(
                points[i].x - n1.x * half_width,
                points[i].y - n1.y * half_width,
            ));
        }
    }

    // Last point
    let last_normal = normals[normals.len() - 1];
    left_side.push(Point::new(
        points[n - 1].x + last_normal.x * half_width,
        points[n - 1].y + last_normal.y * half_width,
    ));
    right_side.push(Point::new(
        points[n - 1].x - last_normal.x * half_width,
        points[n - 1].y - last_normal.y * half_width,
    ));

    // Build the outline path
    if is_closed {
        // For closed paths, connect left to right
        if !left_side.is_empty() {
            builder.move_to(left_side[0].x, left_side[0].y);
            for p in &left_side[1..] {
                builder.line_to(p.x, p.y);
            }
            builder.close();
        }
        if !right_side.is_empty() {
            builder.move_to(right_side[0].x, right_side[0].y);
            for p in &right_side[1..] {
                builder.line_to(p.x, p.y);
            }
            builder.close();
        }
    } else {
        // For open paths, create a single outline with caps
        if !left_side.is_empty() {
            builder.move_to(left_side[0].x, left_side[0].y);

            // Add start cap
            add_cap(builder, points[0], normals[0], half_width, params.cap, true);

            // Left side (forward)
            for p in &left_side {
                builder.line_to(p.x, p.y);
            }

            // Add end cap
            add_cap(
                builder,
                points[n - 1],
                normals[normals.len() - 1],
                half_width,
                params.cap,
                false,
            );

            // Right side (reverse)
            for p in right_side.iter().rev() {
                builder.line_to(p.x, p.y);
            }

            builder.close();
        }
    }
}

fn add_cap(
    builder: &mut PathBuilder,
    center: Point,
    normal: Point,
    half_width: Scalar,
    cap: StrokeCap,
    is_start: bool,
) {
    match cap {
        StrokeCap::Butt => {
            // No extension
        }
        StrokeCap::Square => {
            // Extend by half_width in the direction perpendicular to normal
            let dir = if is_start {
                Point::new(-normal.y, normal.x)
            } else {
                Point::new(normal.y, -normal.x)
            };
            let ext = Point::new(dir.x * half_width, dir.y * half_width);
            builder.line_to(
                center.x + normal.x * half_width + ext.x,
                center.y + normal.y * half_width + ext.y,
            );
            builder.line_to(
                center.x - normal.x * half_width + ext.x,
                center.y - normal.y * half_width + ext.y,
            );
        }
        StrokeCap::Round => {
            // Approximate semicircle with line segments
            let steps = 8;
            let start_angle = if is_start {
                normal.y.atan2(normal.x)
            } else {
                (-normal.y).atan2(-normal.x)
            };

            for i in 0..=steps {
                let t = i as Scalar / steps as Scalar;
                let angle = start_angle + t * std::f32::consts::PI;
                let x = center.x + angle.cos() * half_width;
                let y = center.y + angle.sin() * half_width;
                builder.line_to(x, y);
            }
        }
    }
}

fn flatten_quad(points: &mut Vec<Point>, p0: Point, p1: Point, p2: Point, steps: usize) {
    for i in 1..=steps {
        let t = i as Scalar / steps as Scalar;
        let mt = 1.0 - t;
        let x = mt * mt * p0.x + 2.0 * mt * t * p1.x + t * t * p2.x;
        let y = mt * mt * p0.y + 2.0 * mt * t * p1.y + t * t * p2.y;
        points.push(Point::new(x, y));
    }
}

fn flatten_cubic(
    points: &mut Vec<Point>,
    p0: Point,
    p1: Point,
    p2: Point,
    p3: Point,
    steps: usize,
) {
    for i in 1..=steps {
        let t = i as Scalar / steps as Scalar;
        let mt = 1.0 - t;
        let mt2 = mt * mt;
        let t2 = t * t;
        let x = mt2 * mt * p0.x + 3.0 * mt2 * t * p1.x + 3.0 * mt * t2 * p2.x + t2 * t * p3.x;
        let y = mt2 * mt * p0.y + 3.0 * mt2 * t * p1.y + 3.0 * mt * t2 * p2.y + t2 * t * p3.y;
        points.push(Point::new(x, y));
    }
}

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

    #[test]
    fn test_stroke_to_fill_line() {
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.line_to(100.0, 0.0);
        let path = builder.build();

        let params = StrokeParams::new(10.0);
        let stroked = stroke_to_fill(&path, &params).unwrap();

        assert!(!stroked.is_empty());
    }

    #[test]
    fn test_stroke_to_fill_triangle() {
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.line_to(100.0, 0.0);
        builder.line_to(50.0, 100.0);
        builder.close();
        let path = builder.build();

        let params = StrokeParams::new(5.0).with_join(StrokeJoin::Round);
        let stroked = stroke_to_fill(&path, &params).unwrap();

        assert!(!stroked.is_empty());
    }

    #[test]
    fn test_stroke_to_fill_multi_contour_mixed_closed_open() {
        // Path with two contours: first closed (triangle), second open (line).
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.line_to(10.0, 0.0);
        builder.line_to(5.0, 10.0);
        builder.close();
        builder.move_to(20.0, 0.0);
        builder.line_to(30.0, 0.0);
        let path = builder.build();

        let params = StrokeParams::new(2.0);
        let result = stroke_to_fill(&path, &params);
        assert!(result.is_some(), "stroke_to_fill should succeed for valid input");
        let stroked = result.unwrap();
        assert!(stroked.iter().count() > 0, "stroked path should not be empty");
    }

    #[test]
    fn test_stroke_params() {
        let params = StrokeParams::new(2.0)
            .with_cap(StrokeCap::Round)
            .with_join(StrokeJoin::Bevel)
            .with_miter_limit(10.0);

        assert_eq!(params.width, 2.0);
        assert_eq!(params.cap, StrokeCap::Round);
        assert_eq!(params.join, StrokeJoin::Bevel);
        assert_eq!(params.miter_limit, 10.0);
    }

    #[test]
    fn test_stroke_to_fill_round_join_generates_arc() {
        // Two perpendicular lines meeting at right angle.
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.line_to(50.0, 0.0);
        builder.line_to(50.0, 50.0);
        let path = builder.build();

        let params = StrokeParams::new(10.0).with_join(StrokeJoin::Round);
        let result = stroke_to_fill(&path, &params);
        assert!(result.is_some());

        let stroked = result.unwrap();
        let count = stroked.iter().count();
        // Round join should produce more verbs than a straight-line join.
        // For 90-degree turn with default segment count, expect at least 8+ extra verbs
        // beyond the basic 5-6 a miter would emit.
        assert!(
            count > 10,
            "Round join should generate arc segments, got {} verbs",
            count
        );
    }
}