plottery_lib 0.8.0

Core geometry library of Plottery, a creative coding framework for generative vector graphics and pen plotting.
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
use crate::{
    traits::{ClosestPoint, Normalize, Scale, Scale2D, Translate},
    Angle, BoundingBox, Circle, Containment, Line, LineIntersection, Mirror, Path, Plottable,
    PointLineRelation, Rotate90, SampleSettings, Shape, LARGE_EPSILON, V2,
};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
pub struct Rect {
    /// guaranteed: `bot_left.x <= top_right.x && bot_left.y <= top_right.y`
    bot_left: V2,
    /// guaranteed: `top_right.x >= bot_left.x && top_right.y >= bot_left.y`
    top_right: V2,
}

impl Rect {
    pub fn new(bl: V2, tr: V2) -> Self {
        Self {
            bot_left: bl.min(tr),
            top_right: tr.max(bl),
        }
    }
    pub fn new_shape(bl: V2, tr: V2) -> Shape {
        Shape::Rect(Rect::new(bl, tr))
    }
    pub fn new_from_center(center: V2, size: V2) -> Self {
        Self {
            bot_left: center - size * 0.5,
            top_right: center + size * 0.5,
        }
    }
    pub fn new_shape_from_center(center: V2, size: V2) -> Shape {
        Shape::Rect(Rect::new_from_center(center, size))
    }

    fn fix_corners_min_max(&mut self) {
        let bl = self.bot_left.min(self.top_right);
        let tr = self.bot_left.max(self.top_right);
        self.bot_left = bl;
        self.top_right = tr;
    }

    pub fn tr(&self) -> V2 {
        self.top_right
    }
    pub fn tl(&self) -> V2 {
        V2::new(self.bot_left.x, self.top_right.y)
    }
    pub fn bl(&self) -> V2 {
        self.bot_left
    }
    pub fn br(&self) -> V2 {
        V2::new(self.top_right.x, self.bot_left.y)
    }

    pub fn top_center(&self) -> V2 {
        V2::new(self.bot_left.x + self.width() * 0.5, self.top_right.y)
    }
    pub fn left_center(&self) -> V2 {
        V2::new(self.bot_left.x, self.bot_left.y + self.height() * 0.5)
    }
    pub fn right_center(&self) -> V2 {
        V2::new(self.top_right.x, self.bot_left.y + self.height() * 0.5)
    }
    pub fn bottom_center(&self) -> V2 {
        V2::new(self.bot_left.x + self.width() * 0.5, self.bot_left.y)
    }

    pub fn size(&self) -> V2 {
        self.top_right - self.bot_left
    }
    pub fn height(&self) -> f32 {
        self.top_right.y - self.bot_left.y
    }
    pub fn width(&self) -> f32 {
        self.top_right.x - self.bot_left.x
    }

    pub fn max_dist_to_any_corner(&self, point: V2) -> f32 {
        *[
            self.bl().dist(point),
            self.br().dist(point),
            self.tr().dist(point),
            self.tl().dist(point),
        ]
        .iter()
        .max_by(|a, b| a.partial_cmp(b).unwrap())
        .unwrap()
    }

    pub fn center(&self) -> V2 {
        V2::new(
            (self.bot_left.x + self.top_right.x) * 0.5,
            (self.bot_left.y + self.top_right.y) * 0.5,
        )
    }
    pub fn aspect_ratio(&self) -> f32 {
        self.width() / self.height()
    }
    pub fn is_square(&self) -> bool {
        (self.width() - self.height()).abs() < LARGE_EPSILON
    }

    pub fn left_mid(&self) -> V2 {
        V2::new(self.bot_left.x, self.bot_left.y + self.height() * 0.5)
    }
    pub fn right_mid(&self) -> V2 {
        V2::new(self.top_right.x, self.top_right.y - self.height() * 0.5)
    }
    pub fn top_mid(&self) -> V2 {
        V2::new(self.top_right.x - self.width() * 0.5, self.top_right.y)
    }
    pub fn bot_mid(&self) -> V2 {
        V2::new(self.bot_left.x + self.width() * 0.5, self.bot_left.y)
    }

    pub fn area(&self) -> f32 {
        self.width() * self.height()
    }

    /// Path to draw a rect with a given thickness.
    /// It creates a spiralling path from the rectangle border towards the center with `thickness`.
    pub fn filled_partially_towards_center(
        &self,
        mut thickness: f32,
        pen_width: f32,
    ) -> super::Path {
        if pen_width <= LARGE_EPSILON {
            return Path::new_from(self.get_points(SampleSettings::default()));
        }

        let max_thickness_x = (self.width() * 0.5 - pen_width * 0.5).max(0.0);
        let max_thickness_y = (self.height() * 0.5 - pen_width * 0.5).max(0.0);
        thickness = thickness.min(max_thickness_x.min(max_thickness_y));

        if thickness <= LARGE_EPSILON {
            return Path::new_from(self.get_points(SampleSettings::default()));
        }

        let thickness_x = thickness.min(max_thickness_x);
        let thickness_y = thickness.min(max_thickness_y);

        let num_steps_x = (thickness_x / pen_width).ceil().max(1.0) as usize;
        let num_steps_y = (thickness_y / pen_width).ceil().max(1.0) as usize;
        let spiral_steps = num_steps_x.min(num_steps_y);
        let step_x = thickness_x / num_steps_x as f32;
        let step_y = thickness_y / num_steps_y as f32;

        self.spiral_fill_with_steps(spiral_steps, step_x, step_y)
    }

    /// Path to draw a rect's outer border and spiral filling.
    pub fn filled_spiral(&self, pen_width: f32) -> super::Path {
        let max_thickness = (self.width().min(self.height()) * 0.5 - pen_width * 0.4).max(0.0);
        self.filled_partially_towards_center(max_thickness, pen_width)
    }

    fn spiral_fill_with_steps(&self, max_steps: usize, step_x: f32, step_y: f32) -> super::Path {
        let border = vec![self.bl(), self.tl(), self.tr(), self.br(), self.bl()];

        if max_steps == 0 || step_x <= LARGE_EPSILON || step_y <= LARGE_EPSILON {
            return Path::new_from(border);
        }

        let mut left = self.bot_left.x + step_x;
        let mut right = self.top_right.x - step_x;
        let mut bottom = self.bot_left.y + step_y;
        let mut top = self.top_right.y - step_y;

        if left > right || bottom > top {
            return Path::new_from(border);
        }

        let mut points = Vec::with_capacity(4 + 1 + max_steps * 4);
        for point in border {
            points.push(point);
        }
        points.push(V2::new(left, bottom));

        for _ in 0..max_steps {
            points.push(V2::new(left, top));
            left += step_x;
            if left > right + LARGE_EPSILON {
                break;
            }

            points.push(V2::new(right, top));
            top -= step_y;
            if bottom > top + LARGE_EPSILON {
                break;
            }

            points.push(V2::new(right, bottom));
            right -= step_x;
            if left > right + LARGE_EPSILON {
                break;
            }

            points.push(V2::new(left, bottom));
            bottom += step_y;
            if bottom > top + LARGE_EPSILON {
                break;
            }
        }

        Path::new_from(points)
    }

    /// Path to draw a rect's outer border and criss cross filling
    pub fn filled_criss_cross(&self, pen_width: f32) -> super::Path {
        if self.height() <= pen_width * 0.5 {
            return Path::new_from(self.get_points(SampleSettings::default()));
        }

        let smaller_inner = Rect::new(
            self.bot_left + V2::xy(pen_width),
            self.top_right - V2::xy(pen_width),
        );
        let filling = smaller_inner.criss_cross_filling(pen_width);

        Path::new_from_iter(
            [self.bl(), self.tl(), self.tr(), self.br(), self.bl()]
                .into_iter()
                .chain(filling),
        )
    }

    fn criss_cross_filling(&self, pen_width: f32) -> Vec<V2> {
        let height = self.height();
        if height <= pen_width * 0.05 {
            return Vec::new();
        }
        if self.height() <= pen_width * 0.5 {
            return self.get_points(SampleSettings::default());
        }

        let num_lines = (self.height() / pen_width).ceil() as usize;
        let height_per_line = self.height() / num_lines as f32;

        let mut points = Vec::with_capacity(num_lines * 2);
        for i in 0..(num_lines + 1) {
            let y = self.bot_left.y + i as f32 * height_per_line;
            if i % 2 == 0 {
                points.push(V2::new(self.bot_left.x, y));
                points.push(V2::new(self.top_right.x, y));
            } else {
                points.push(V2::new(self.top_right.x, y));
                points.push(V2::new(self.bot_left.x, y));
            }
        }

        points
    }

    pub fn intersects_rect(&self, other: &Rect) -> bool {
        let self_edges = [
            (self.bl(), self.tl()),
            (self.tl(), self.tr()),
            (self.tr(), self.br()),
            (self.br(), self.bl()),
        ];
        let other_edges = [
            (other.bl(), other.tl()),
            (other.tl(), other.tr()),
            (other.tr(), other.br()),
            (other.br(), other.bl()),
        ];

        self_edges.iter().any(|(self_from, self_to)| {
            let self_segment = Line::new(*self_from, *self_to);
            other_edges.iter().any(|(other_from, other_to)| {
                segments_intersect_or_touch(self_segment, Line::new(*other_from, *other_to))
            })
        })
    }

    pub fn intersects_circle(&self, other: &Circle) -> bool {
        let radius_squared = other.radius.powi(2);
        let edges = [
            (self.bl(), self.tl()),
            (self.tl(), self.tr()),
            (self.tr(), self.br()),
            (self.br(), self.bl()),
        ];

        edges.iter().any(|(from, to)| {
            let segment = Line::new(*from, *to);
            let from_dist_squared = from.dist_squared(other.center);
            let to_dist_squared = to.dist_squared(other.center);
            let closest_dist_squared = segment
                .closest_point(other.center)
                .dist_squared(other.center);

            closest_dist_squared <= radius_squared
                && (from_dist_squared >= radius_squared || to_dist_squared >= radius_squared)
        })
    }

    pub fn intersects_path(&self, other: &Path) -> bool {
        other.intersects_rect(self)
    }

    pub fn contains_circle(&self, other: &Circle) -> Containment {
        let fully_inside = other.center.x - other.radius >= self.bot_left.x
            && other.center.x + other.radius <= self.top_right.x
            && other.center.y - other.radius >= self.bot_left.y
            && other.center.y + other.radius <= self.top_right.y;

        if fully_inside {
            return Containment::Full;
        }

        if self.intersects_circle(other)
            || self.contains_point(other.center)
            || [self.bl(), self.tl(), self.tr(), self.br()]
                .iter()
                .any(|corner| corner.dist_squared(other.center) <= other.radius.powi(2))
        {
            return Containment::Partial;
        }

        Containment::None
    }

    pub fn contains_rect(&self, other: &Rect) -> Containment {
        let fully_inside = self.contains_point(other.bl())
            && self.contains_point(other.tl())
            && self.contains_point(other.tr())
            && self.contains_point(other.br());

        if fully_inside {
            return Containment::Full;
        }

        if self.intersects_rect(other) || self.overlaps_area_rect(other) {
            return Containment::Partial;
        }

        Containment::None
    }

    pub fn contains_path(&self, other: &Path) -> Containment {
        let other_points_closed = other.points_closed();
        if other_points_closed.is_empty() {
            return Containment::None;
        }

        if other_points_closed
            .iter()
            .all(|point| self.contains_point(*point))
        {
            return Containment::Full;
        }

        let other_closed = Path::new_from(other_points_closed.clone());
        if self.intersects_path(&other_closed)
            || other_points_closed
                .iter()
                .any(|point| self.contains_point(*point))
            || [self.bl(), self.tl(), self.tr(), self.br()]
                .iter()
                .any(|corner| other.contains_point_or_on_boundary_as_closed(*corner))
        {
            return Containment::Partial;
        }

        Containment::None
    }

    fn overlaps_area_rect(&self, other: &Rect) -> bool {
        self.bot_left.x < other.top_right.x
            && self.top_right.x > other.bot_left.x
            && self.bot_left.y < other.top_right.y
            && self.top_right.y > other.bot_left.y
    }

    pub fn contains_shape(&self, other: &Shape) -> Containment {
        match other {
            Shape::Circle(c) => self.contains_circle(c),
            Shape::Rect(r) => self.contains_rect(r),
            Shape::Path(p) => self.contains_path(p),
        }
    }

    pub fn rounded_corners(
        &self,
        radius: f32,
        sample_settings: SampleSettings,
    ) -> anyhow::Result<Path> {
        if self.width() < 2.0 * radius || self.height() < 2.0 * radius {
            return Err(anyhow::anyhow!("Radius too large for rectangle"));
        }
        let half_radius = radius * 0.5;

        let bl_inner = self.bl() + V2::xy(half_radius);
        let tr_inner = self.tr() - V2::xy(half_radius);
        let br_inner = self.br() + V2::new(-half_radius, half_radius);
        let tl_inner = self.tl() + V2::new(half_radius, -half_radius);

        let path = std::iter::once(bl_inner + V2::polar(Angle::left_cc(), half_radius))
            .chain(Path::arc(
                Angle::left_cc(),
                Angle::up_cc(),
                tl_inner,
                half_radius,
                sample_settings,
            ))
            .chain(Path::arc(
                Angle::up_cc(),
                Angle::right_cc(),
                tr_inner,
                half_radius,
                sample_settings,
            ))
            .chain(Path::arc(
                Angle::full_rotation(),
                Angle::down_cc(),
                br_inner,
                half_radius,
                sample_settings,
            ))
            .chain(Path::arc(
                Angle::down_cc(),
                Angle::left_cc(),
                bl_inner,
                half_radius,
                sample_settings,
            ))
            .collect();
        Ok(path)
    }
}

fn segments_intersect_or_touch(a: Line, b: Line) -> bool {
    if matches!(a.intersection(b), LineIntersection::Intersection(_)) {
        return true;
    }

    if a.point_relation(b.from) == PointLineRelation::OnLine
        && a.point_relation(b.to) == PointLineRelation::OnLine
    {
        let a_min_x = a.from.x.min(a.to.x);
        let a_max_x = a.from.x.max(a.to.x);
        let a_min_y = a.from.y.min(a.to.y);
        let a_max_y = a.from.y.max(a.to.y);

        let b_min_x = b.from.x.min(b.to.x);
        let b_max_x = b.from.x.max(b.to.x);
        let b_min_y = b.from.y.min(b.to.y);
        let b_max_y = b.from.y.max(b.to.y);

        let overlaps_x = a_min_x <= b_max_x && a_max_x >= b_min_x;
        let overlaps_y = a_min_y <= b_max_y && a_max_y >= b_min_y;

        return overlaps_x && overlaps_y;
    }

    false
}

impl Plottable for Rect {
    fn get_points(&self, _: SampleSettings) -> Vec<V2> {
        vec![self.bl(), self.tl(), self.tr(), self.br(), self.bl()]
    }
    fn get_points_from(
        &self,
        _current_drawing_head_pos: V2,
        sample_settings: SampleSettings,
    ) -> Vec<V2> {
        self.get_points(sample_settings)
    }

    fn length(&self) -> f32 {
        self.width() * 2.0 + self.height() * 2.0
    }

    fn is_closed(&self) -> bool {
        true
    }

    fn contains_point(&self, point: V2) -> bool {
        point.x >= self.bot_left.x
            && point.x <= self.top_right.x
            && point.y >= self.bot_left.y
            && point.y <= self.top_right.y
    }

    fn reduce_points(&self, _aggression_factor: f32) -> Self {
        *self
    }
}

impl Rotate90 for Rect {
    fn rotate_90(&self) -> Self {
        Rect::new(self.bot_left.rotate_90(), self.top_right.rotate_90())
    }
    fn rotate_90_mut(&mut self) {
        self.top_right = self.top_right.rotate_90();
        self.bot_left = self.bot_left.rotate_90();
        self.fix_corners_min_max();
    }
    fn rotate_180(&self) -> Self {
        Rect::new(self.bot_left.rotate_180(), self.top_right.rotate_180())
    }
    fn rotate_180_mut(&mut self) {
        self.top_right = self.top_right.rotate_180();
        self.bot_left = self.bot_left.rotate_180();
        self.fix_corners_min_max();
    }
    fn rotate_270(&self) -> Self {
        Rect::new(self.bot_left.rotate_270(), self.top_right.rotate_270())
    }
    fn rotate_270_mut(&mut self) {
        self.top_right = self.top_right.rotate_270();
        self.bot_left = self.bot_left.rotate_270();
        self.fix_corners_min_max();
    }

    fn rotate_90_around(&self, pivot: V2) -> Self {
        Rect::new(
            self.bot_left.rotate_90_around(pivot),
            self.top_right.rotate_90_around(pivot),
        )
    }
    fn rotate_90_around_mut(&mut self, pivot: V2) {
        self.top_right = self.top_right.rotate_90_around(pivot);
        self.bot_left = self.bot_left.rotate_90_around(pivot);
        self.fix_corners_min_max();
    }
    fn rotate_180_around(&self, pivot: V2) -> Self {
        Rect::new(
            self.bot_left.rotate_180_around(pivot),
            self.top_right.rotate_180_around(pivot),
        )
    }
    fn rotate_180_around_mut(&mut self, pivot: V2) {
        self.top_right = self.top_right.rotate_180_around(pivot);
        self.bot_left = self.bot_left.rotate_180_around(pivot);
        self.fix_corners_min_max();
    }
    fn rotate_270_around(&self, pivot: V2) -> Self {
        Rect::new(
            self.bot_left.rotate_270_around(pivot),
            self.top_right.rotate_270_around(pivot),
        )
    }
    fn rotate_270_around_mut(&mut self, pivot: V2) {
        self.top_right = self.top_right.rotate_270_around(pivot);
        self.bot_left = self.bot_left.rotate_270_around(pivot);
        self.fix_corners_min_max();
    }
}

impl Translate for Rect {
    fn translate(&self, dist: V2) -> Self {
        Rect::new(self.bot_left + dist, self.top_right + dist)
    }

    fn translate_mut(&mut self, dist: V2) {
        self.bot_left += dist;
        self.top_right += dist;
    }
}

impl Scale for Rect {
    fn scale(&self, scale: f32) -> Self {
        Rect::new(self.bot_left * scale, self.top_right * scale)
    }

    fn scale_mut(&mut self, scale: f32) {
        self.bot_left *= scale;
        self.top_right *= scale;
    }
}

impl Scale2D for Rect {
    fn scale_2d(&self, scale: V2) -> Self {
        Rect::new(self.bot_left * scale, self.top_right * scale)
    }

    fn scale_2d_mut(&mut self, scale: V2) {
        self.bot_left *= scale;
        self.top_right *= scale;
    }
}

impl Normalize for Rect {}

impl Mirror for Rect {
    fn mirror_x(&self) -> Self {
        Rect::new(self.bot_left.mirror_x(), self.top_right.mirror_x())
    }

    fn mirror_x_mut(&mut self) {
        self.bot_left.mirror_x_mut();
        self.top_right.mirror_x_mut();
        self.fix_corners_min_max();
    }

    fn mirror_y(&self) -> Self {
        Rect::new(self.bot_left.mirror_y(), self.top_right.mirror_y())
    }

    fn mirror_y_mut(&mut self) {
        self.bot_left.mirror_y_mut();
        self.top_right.mirror_y_mut();
        self.fix_corners_min_max();
    }
}

impl BoundingBox for Rect {
    fn bounding_box(&self) -> Option<Rect> {
        Some(*self)
    }
}

impl ClosestPoint for Rect {
    fn closest_point(&self, _: SampleSettings, point: V2) -> Option<V2> {
        Path::new_from(vec![self.bl(), self.tl(), self.tr(), self.br(), self.bl()])
            .closest_point(SampleSettings::default(), point)
    }
}