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
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
use crate::AngleDir::Ccw;
use crate::common::points::dist;
use crate::common::{Intersection, PCoords, signed_compliment_2pi};
use crate::geom2::aabb2::circle_aabb2;
use crate::geom2::line2::intersect_lines;
use crate::geom2::{
Aabb2, Iso2, Line2, LineOps2, Manifold1Pos2, Point2, Segment2, Vector2, rot90, signed_angle,
};
use crate::na::SVector;
use crate::{AngleDir, AngleInterval, IntervalOps, SurfacePoint2, UnitVec2};
use crate::{Arc2, Result};
use serde::{Deserialize, Serialize};
use std::f64::consts::FRAC_PI_2;
use std::ops;
mod fitting;
/// A circle in 2D space, defined by a center point and a radius.
///
/// This is one of `engeom`'s 2D geometric primitives.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct Circle2 {
pub center: Point2,
pub radius: f64,
}
/// Lists the two ways one circle can be tangent to another.
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum CircleTangency {
/// The circles touch from the outside, neither containing the other. Their centers are the
/// sum of the two radii apart.
Outer,
/// One circle lies within the other, touching it from the inside. Their centers are the
/// difference of the two radii apart.
Inner,
}
//=============================================================================================
// Creation Methods
//=============================================================================================
impl Circle2 {
/// Create a new circle from the x and y coordinates of its center and its radius
///
/// # Arguments
///
/// * `x`: the x coordinate of the circle's center
/// * `y`: the y coordinate of the circle's center
/// * `r`: the radius of the circle
///
/// returns: Circle2
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// let circle = Circle2::new(1.0, 2.0, 3.0);
///
/// assert_eq!(circle.x(), 1.0);
/// assert_eq!(circle.y(), 2.0);
/// assert_eq!(circle.r(), 3.0);
/// ```
pub fn new(x: f64, y: f64, r: f64) -> Self {
let center = Point2::new(x, y);
Self::from_point(center, r)
}
/// Create a new circle from a center point and a radius
///
/// # Arguments
///
/// * `center`: the center point of the circle
/// * `r`: the radius of the circle
///
/// returns: Circle2
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// let circle = Circle2::from_point(Point2::new(1.0, 2.0), 3.0);
///
/// assert_eq!(circle.x(), 1.0);
/// assert_eq!(circle.y(), 2.0);
/// assert_eq!(circle.r(), 3.0);
/// ```
pub fn from_point(center: Point2, r: f64) -> Circle2 {
Circle2 { center, radius: r }
}
/// Attempt to create a fitting circle from three points. Will return an `Err` if the points
/// are collinear.
///
/// # Arguments
///
/// * `p0`: the first point
/// * `p1`: the second point
/// * `p2`: the third point
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// use approx::assert_relative_eq;
///
/// let p0 = Point2::new(-1.0, 0.0);
/// let p1 = Point2::new(0.0, 1.0);
/// let p2 = Point2::new(1.0, 0.0);
///
/// let circle = Circle2::from_3_points(&p0, &p1, &p2).unwrap();
/// assert_relative_eq!(circle.x(), 0.0);
/// assert_relative_eq!(circle.y(), 0.0);
/// assert_relative_eq!(circle.r(), 1.0);
///
/// ```
pub fn from_3_points(
p0: &impl PCoords<2>,
p1: &impl PCoords<2>,
p2: &impl PCoords<2>,
) -> Result<Circle2> {
let (p0, p1, p2) = (p0.coords(), p1.coords(), p2.coords());
let temp = p1.x.powi(2) + p1.y.powi(2);
let bc = (p0.x.powi(2) + p0.y.powi(2) - temp) / 2.0;
let cd = (temp - p2.x.powi(2) - p2.y.powi(2)) / 2.0;
let det = (p0.x - p1.x) * (p1.y - p2.y) - (p1.x - p2.x) * (p0.y - p1.y);
if det.abs() < 1.0e-6 {
Err("Points are collinear".into())
} else {
let cx = (bc * (p1.y - p2.y) - cd * (p0.y - p1.y)) / det;
let cy = ((p0.x - p1.x) * cd - (p1.x - p2.x) * bc) / det;
let radius = ((cx - p0.x).powi(2) + (cy - p0.y).powi(2)).sqrt();
Ok(Self::new(cx, cy, radius))
}
}
/// Creates the smallest circle containing every point in expected O(n) time.
///
/// A single point or identical points produce a zero-radius circle. Collinear points produce
/// the circle whose diameter is the extreme pair. Returns an error for an empty point set.
///
/// # Arguments
///
/// * `points`: a slice of points to enclose; must not be empty
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// use approx::assert_relative_eq;
///
/// let points = [
/// Point2::new(0.0, 0.0),
/// Point2::new(2.0, 0.0),
/// Point2::new(2.0, 2.0),
/// Point2::new(0.0, 2.0),
/// Point2::new(1.0, 1.5),
/// ];
///
/// let circle = Circle2::from_min_enclosing(&points).unwrap();
/// assert_relative_eq!(circle.x(), 1.0, epsilon = 1e-12);
/// assert_relative_eq!(circle.y(), 1.0, epsilon = 1e-12);
/// assert_relative_eq!(circle.r(), 2.0_f64.sqrt(), epsilon = 1e-12);
/// ```
pub fn from_min_enclosing(points: &[impl PCoords<2>]) -> Result<Self> {
let (center, radius) = crate::common::min_ball::compute_min_ball(points)?;
Ok(Self { center, radius })
}
/// Creates a circle at the tangent of a corner. The corner is defined by a corner point and
/// two direction vectors which define the directions of the two lines which meet at the corner.
/// The radius argument specifies the radius of the tangent circle. The circle is created by
/// finding the bisector of the angle formed by the two lines, and then offsetting each line
/// by the radius in the positive direction of the bisector. The intersection of the two offset
/// lines is the center of the tangent circle.
///
/// This method will return an error if the two direction vectors are collinear (i.e. the angle
/// between them is zero or 180 degrees), as in that case a unique tangent circle cannot be
/// defined.
///
/// This construction method is similar to putting a fillet on the corner formed by the two
/// lines.
///
/// # Arguments
///
/// * `corner`: the corner point where the two lines meet
/// * `d0`: the direction vector of the first line
/// * `d1`: the direction vector of the second line
/// * `radius`: the radius of the tangent circle
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2, Vector2};
/// use approx::assert_relative_eq;
/// let corner = Point2::new(1.0, 1.0);
/// let d0 = Vector2::new(1.0, 0.0); // Horizontal line to the right
/// let d1 = Vector2::new(0.0, 1.0); // Vertical line upwards
/// let radius = 1.0;
///
/// let circle = Circle2::from_tangent_to_corner(&corner, &d0, &d1, radius).unwrap();
/// assert_relative_eq!(circle.x(), 2.0);
/// assert_relative_eq!(circle.y(), 2.0);
/// assert_relative_eq!(circle.r(), radius);
/// ```
pub fn from_tangent_to_corner(
corner: &impl PCoords<2>,
d0: &Vector2,
d1: &Vector2,
radius: f64,
) -> Result<Circle2> {
// Compute the angle from the direction of line a to the direction of line b
let angle = signed_angle(d0, d1);
// Figure out the bisector direction
let bisector = Iso2::rotation(angle / 2.0) * d0.normalize();
let a = SurfacePoint2::new_normalize(Point2::from(corner.coords()), *d0);
let b = SurfacePoint2::new_normalize(Point2::from(corner.coords()), *d1);
let da = if bisector.dot(&a.orthogonal()) > 0.0 {
radius
} else {
-radius
};
let db = if bisector.dot(&b.orthogonal()) > 0.0 {
radius
} else {
-radius
};
let a1 = a.shifted_orthogonal(da);
let b1 = b.shifted_orthogonal(db);
let ts = intersect_lines(&a1, &b1);
if let Some((t_a, _t_b)) = ts {
let center = a1.at(t_a);
Ok(Circle2::from_point(center, radius))
} else {
Err("Failed to compute tangent circle from lines".into())
}
}
/// Create the circle which is tangent to a line at the line's origin and which passes
/// through a second point.
///
/// # Arguments
///
/// * `tangent`: the tangent line; the circle touches it at the line's origin
/// * `point`: a second point the circle must pass through
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Errors
///
/// Returns an error if `point` lies on the tangent line (within an absolute distance of
/// 1e-10), where no finite tangent circle exists.
pub fn from_tangent_and_point(
tangent: &impl LineOps2,
point: &impl PCoords<2>,
) -> Result<Self> {
let iso = tangent.to_iso_from_y().inverse();
let p = iso * Point2::from(point.coords());
// p.x is the point's signed perpendicular distance from the tangent line; at zero the
// construction is degenerate and no finite tangent circle exists.
if p.x.abs() < 1e-10 {
return Err("point lies on the tangent line; no finite tangent circle exists".into());
}
let cx = (p.x.powi(2) + p.y.powi(2)) / (2.0 * p.x);
let center = iso.inverse() * Point2::new(cx, 0.0);
Ok(Circle2::new(center.x, center.y, cx.abs()))
}
/// Compute the circles of a given radius which are tangent to both a line and another circle,
/// the construction which places a fillet of known size against a round.
///
/// A center at `radius` from the line lies on one of the two lines offset to either side of
/// it, and a center tangent to `circle` lies on a circle concentric with it, so the tangent
/// circles are centered where those two loci meet. There are up to four, and it is normal for
/// there to be none: a radius too large to fit between the line and the circle has no
/// solution, as does one too small to reach across the gap between them.
///
/// The results are ordered by the side of the line their centers fall on, taking the side the
/// line's normal points to first, and then by ascending parameter along the line. This makes
/// the ordering stable for a given input, but note that it says nothing about which result is
/// the one you want; the caller has to select on the geometry of its own problem.
///
/// # Arguments
///
/// * `line`: the line to be tangent to
/// * `circle`: the circle to be tangent to
/// * `radius`: the radius of the circles to construct, which must be positive
/// * `tangency`: whether to touch `circle` from the outside or from within
///
/// returns: Vec<Circle2>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Line2, Point2, Vector2};
/// use engeom::geom2::CircleTangency;
/// use approx::assert_relative_eq;
///
/// // The x axis, and a circle of radius 1 whose center is 3 above it. There is exactly one
/// // circle of radius 1 tangent to both: the one nestled between them.
/// let line = Line2::new(Point2::new(0.0, 0.0), Vector2::new(1.0, 0.0));
/// let circle = Circle2::new(0.0, 3.0, 1.0);
///
/// let found = Circle2::from_tangent_to_line_and_circle(
/// &line, &circle, 1.0, CircleTangency::Outer,
/// );
///
/// assert_eq!(found.len(), 1);
/// assert_relative_eq!(found[0].x(), 0.0, epsilon = 1e-10);
/// assert_relative_eq!(found[0].y(), 1.0, epsilon = 1e-10);
/// assert_relative_eq!(found[0].r(), 1.0, epsilon = 1e-10);
/// ```
pub fn from_tangent_to_line_and_circle(
line: &impl LineOps2,
circle: &Circle2,
radius: f64,
tangency: CircleTangency,
) -> Vec<Circle2> {
// Written as a single negated conjunction so that a NaN radius, which fails both tests,
// is rejected without relying on a negated comparison against a partially ordered type.
if !(radius > 0.0 && radius.is_finite()) {
return Vec::new();
}
// The locus of centers at `radius` from the given circle, which is what the tangency mode
// actually selects between.
let locus = match tangency {
CircleTangency::Outer => Circle2::from_point(circle.center, circle.radius + radius),
CircleTangency::Inner => {
Circle2::from_point(circle.center, (circle.radius - radius).abs())
}
};
let base = Line2::new(line.origin(), line.dir());
let mut result = Vec::new();
for side in [radius, -radius] {
let offset = base.offset_by(side);
for t in intersection_line_circle(&offset, &locus) {
result.push(Circle2::from_point(offset.at(t), radius));
}
}
result
}
}
//=============================================================================================
// Operational Methods
//=============================================================================================
impl Circle2 {
/// Returns the x coordinate of the circle's center
pub fn x(&self) -> f64 {
self.center.x
}
/// Returns the y coordinate of the circle's center
pub fn y(&self) -> f64 {
self.center.y
}
/// Returns the radius of the circle
pub fn r(&self) -> f64 {
self.radius
}
/// Returns the point on the circle's perimeter at the given angle (referenced as a
/// counter-clockwise angle where zero is the x-axis), measured in radians
///
/// # Arguments
///
/// * `angle`: the CCW angle from the x-axis in radians
///
/// returns: OPoint<f64, Const<2>>
///
/// # Examples
///
/// ```
/// use std::f64::consts::FRAC_PI_2;
/// use engeom::{Circle2, Point2};
/// use approx::assert_relative_eq;
///
/// let c = Circle2::new(0.0, 0.0, 1.0);
/// let p = c.point_at_angle(FRAC_PI_2);
///
/// assert_relative_eq!(p.x, 0.0);
/// assert_relative_eq!(p.y, 1.0);
/// ```
pub fn point_at_angle(&self, angle: f64) -> Point2 {
let v = Vector2::new(self.radius, 0.0);
let t = Iso2::rotation(angle);
self.center + (t * v)
}
pub fn at_angle(&self, angle: f64) -> Manifold1Pos2 {
let p = self.point_at_angle(angle);
let n = UnitVec2::new_normalize(p - self.center);
let d = rot90(Ccw) * n;
Manifold1Pos2::new(angle * self.r(), p, d, n)
}
/// Given a point, project it onto the perimeter of the circle. If the point is within 1.0e-10
/// of the center, then `None` is returned.
///
/// # Arguments
///
/// * `point`:
///
/// returns: Option<OPoint<f64, Const<2>>>
///
/// # Examples
///
/// ```
///
/// ```
pub fn project_point_to_perimeter(&self, point: &impl PCoords<2>) -> Option<Point2> {
let v = point.coords() - self.center.coords;
if v.norm() < 1.0e-10 {
None
} else {
let n = v.normalize();
Some(self.center + (n * self.radius))
}
}
/// Determines the angle of the given point relative to the circle's center, measured in
/// radians where zero is the x-axis and positive angles are counter-clockwise.
///
/// # Arguments
///
/// * `point`: the test point to measure the angle of
///
/// returns: f64
///
/// # Examples
///
/// ```
/// use std::f64::consts::FRAC_PI_2;
/// use engeom::{Circle2, Point2};
/// use approx::assert_relative_eq;
///
/// let c = Circle2::new(0.0, 0.0, 1.0);
/// let p = Point2::new(0.0, 1.0);
/// let a = c.angle_of_point(&p);
///
/// assert_relative_eq!(a, FRAC_PI_2);
/// ```
pub fn angle_of_point(&self, point: &impl PCoords<2>) -> f64 {
let v = point.coords() - self.center.coords;
v.y.atan2(v.x)
}
pub fn intersection_interval(&self, other: Circle2) -> Option<AngleInterval> {
let ints = self.intersections_with(&other);
if ints.is_empty() {
return None;
}
if ints.len() == 1 {
let start = self.angle_of_point(&ints[0]);
return Some(AngleInterval::new_start_angle(start, 0.0));
}
// There are two possible intervals, one going from the first point to the second in the
// clockwise direction, and one going via its signed compliment in the counter-clockwise
// direction. The valid interval is the one which also contains the center of the other
// circle.
let v0 = ints[0] - self.center;
let v1 = ints[1] - self.center;
let a = signed_angle(&v0, &v1);
let ac = signed_compliment_2pi(a);
let s = self.angle_of_point(&ints[0]);
let i0 = AngleInterval::new_start_angle(s, a);
let i1 = AngleInterval::new_start_angle(s, ac);
if i0.contains_value(self.angle_of_point(&other.center)) {
Some(i0)
} else {
Some(i1)
}
}
pub fn intersections_with(&self, other: &Circle2) -> Vec<Point2> {
const TOL: f64 = 1.0e-10;
let mut result = Vec::new();
let d = dist(&self.center, &other.center);
if d < TOL {
// Circles are concentric
return result;
}
let r_sum = self.radius + other.radius;
if d > r_sum {
// Circles are too far apart
return result;
}
let v = (other.center - self.center).normalize();
let a = (self.radius.powi(2) - other.radius.powi(2) + d.powi(2)) / (2.0 * d);
let p2 = self.center + (v * a);
if (d - r_sum).abs() < TOL {
// Circles are touching
result.push(p2);
return result;
}
let h = (self.radius.powi(2) - a.powi(2)).sqrt();
let n = Iso2::rotation(FRAC_PI_2) * v;
result.push(p2 + (n * h));
result.push(p2 - (n * h));
result
}
/// Create a full arc of the circle, starting at zero and extending for 2Ï€ radians.
pub fn to_arc(&self) -> Arc2 {
Arc2::from_circle(*self, 0.0, 2.0 * std::f64::consts::PI)
}
/// Create a partial arc of the circle, starting at `angle0` and extending for `angle` radians.
///
/// # Arguments
///
/// * `angle0`:
/// * `angle`:
///
/// returns: Arc2
///
/// # Examples
///
/// ```
///
/// ```
pub fn to_partial_arc(&self, angle0: f64, angle: f64) -> Arc2 {
Arc2::from_circle(*self, angle0, angle)
}
/// Computes the distance from the test point to the outer perimeter of the circle. If the
/// point lies within the circle boundary, the distance will be negative.
///
/// # Arguments
///
/// * `point`: the test point to check against the circle
///
/// returns: f64
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// let c = Circle2::new(0.0, 0.0, 1.0);
///
/// let d0 = c.distance_to(&Point2::new(0.0, 0.0));
/// assert_eq!(d0, -1.0);
///
/// let d1 = c.distance_to(&Point2::new(1.0, 0.0));
/// assert_eq!(d1, 0.0);
///
/// let d2 = c.distance_to(&Point2::new(2.0, 0.0));
/// assert_eq!(d2, 1.0);
/// ```
pub fn distance_to(&self, point: &impl PCoords<2>) -> f64 {
dist(&self.center, point) - self.radius
}
/// Returns `true` if the point lies at or inside the boundary of the circle.
pub fn contains_point(&self, point: &impl PCoords<2>) -> bool {
self.distance_to(point) <= 0.0
}
/// Returns a new `Vec` containing copies of only the points which lie at or inside the
/// boundary of the circle, in their original order. Points are tested with `contains_point`.
///
/// # Arguments
///
/// * `points`: the test points to filter
///
/// returns: Vec<Point2>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
///
/// let c = Circle2::new(0.0, 0.0, 1.0);
/// let points = vec![
/// Point2::new(0.0, 0.0),
/// Point2::new(2.0, 0.0),
/// Point2::new(0.5, 0.5),
/// ];
///
/// let inside = c.contained_points(&points);
/// assert_eq!(inside, vec![Point2::new(0.0, 0.0), Point2::new(0.5, 0.5)]);
/// ```
pub fn contained_points(&self, points: &[impl PCoords<2>]) -> Vec<Point2> {
points
.iter()
.filter(|p| self.contains_point(*p))
.map(|p| Point2::from(p.coords()))
.collect()
}
/// Compute and return the two tangent points on the circle from a given point. If the point is
/// on or within the circle, then `None` is returned.
///
/// If they exist, the tangent points will always be returned in the same order relative to the
/// line passing through the test point in the direction of the circle center. The first point
/// will be in the negative normal direction (to the left) of the line, and the second point
/// will be in the positive normal direction (to the right).
///
/// # Arguments
///
/// * `point`: the test point
///
/// returns: Option<(OPoint<f64, Const<2>>, OPoint<f64, Const<2>>)>
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::{Circle2, Point2};
/// let c = Circle2::new(0.0, 0.0, 1.0);
/// let p = Point2::new(-1.0, -1.0);
/// let (p0, p1) = c.tangent_points_to(&p).unwrap();
/// assert_relative_eq!(p0, Point2::new(-1.0, 0.0));
/// assert_relative_eq!(p1, Point2::new(0.0, -1.0));
/// ```
pub fn tangent_points_to(&self, point: &impl PCoords<2>) -> Option<(Point2, Point2)> {
let dv = point.coords() - self.center.coords;
let d = dv.norm();
if d <= self.radius {
return None;
}
let angle = f64::asin(self.radius / d);
let d1 = self.r() * f64::sin(angle);
let e0 = self.r() * f64::cos(angle);
let d_vec = SurfacePoint2::new_normalize(self.center, dv);
let e = d_vec.orthogonal();
let p0 = d_vec.at_distance(d1) + e * e0;
let p1 = d_vec.at_distance(d1) + e * -e0;
Some((p0, p1))
}
/// Compute and return two segments which are the outer tangents between this circle and another
/// circle.
///
/// Outer tangents only exist when neither circle contains the other, so the result will be
/// `None` if the circles are concentric or if one circle lies entirely within the other.
/// Otherwise, both segments will start on the tangency point on *this* circle and end on the
/// tangency point on the other circle. The segments will be symmetric about the line connecting
/// the two circle centers.
///
/// The segments will always be returned in the same order relative to the line passing through
/// this circle center in the direction of the other circle center. The first segment will be
/// the one in the negative half-space of the line (the negative normal direction, to the left),
/// and the second segment will be in the positive half-space of the line (the positive normal
/// direction, to the right).
///
/// # Arguments
///
/// * `other`: the circle to find the outer tangents to
///
/// returns: Option<(Segment2, Segment2)>
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::Circle2;
///
/// let c0 = Circle2::new(0.0, 0.0, 1.0);
/// let c1 = Circle2::new(5.0, 0.0, 2.0);
/// let (s0, s1) = c0.outer_tangents_to(&c1).unwrap();
///
/// // Each segment runs from a tangency point on `c0` to a tangency point on `c1`, and both
/// // have the outer tangent length sqrt(d^2 - (r1 - r0)^2) = sqrt(24)
/// for s in [s0, s1] {
/// assert_relative_eq!((s.a - c0.center).norm(), 1.0, epsilon = 1e-10);
/// assert_relative_eq!((s.b - c1.center).norm(), 2.0, epsilon = 1e-10);
/// assert_relative_eq!(s.length(), 24.0_f64.sqrt(), epsilon = 1e-10);
/// }
///
/// // A circle fully contained inside another has no outer tangents
/// let inner = Circle2::new(0.1, 0.0, 1.0);
/// let outer = Circle2::new(0.0, 0.0, 5.0);
/// assert!(inner.outer_tangents_to(&outer).is_none());
/// ```
pub fn outer_tangents_to(&self, other: &Circle2) -> Option<(Segment2, Segment2)> {
if dist(&self.center, &other.center) < 1.0e-10 {
// If the circles are concentric, there will be no outer tangents
None
} else if (self.radius - other.radius).abs() < 1.0e-10 {
// If the circles have the same radius, the outer tangent method must be computed
// by a simpler, special case
let s = Segment2::new(&self.center, &other.center).unwrap();
Some((s.offset_by(self.radius), s.offset_by(-self.radius)))
} else if self.radius > other.radius {
if let Some((seg0, seg1)) = other.outer_tangents_to(self) {
// Swap the segments and reverse them
Some((seg1.reversed(), seg0.reversed()))
} else {
// Shouldn't happen
None
}
} else {
// General case. At this point we know that this circle is smaller than the other, and
// that the circles are not concentric. From here we use the method shown in
// https://upload.wikimedia.org/wikipedia/commons/7/7c/Aeussere_tangente_computation.svg
// where we re-frame the problem as the point-to-circle tangent problem.
let proxy = Circle2::new(other.x(), other.y(), other.r() - self.r());
// p0 is in the negative half space and p1 is in the positive half space. This returns
// `None` when this circle lies entirely inside the other one, in which case there are
// genuinely no outer tangents to find.
let (p0, p1) = proxy.tangent_points_to(&self.center)?;
let s0 = Segment2::new(&self.center, &p0).ok()?;
let s1 = Segment2::new(&self.center, &p1).ok()?;
Some((s0.offset_by(-self.r()), s1.offset_by(self.r())))
}
}
/// Determine whether the circle center is on the clockwise or counter-clockwise side of a
/// line. The result is `AngleDir::Ccw` if the center is in the positive half-space of the
/// line (to the left of the direction of travel), and `AngleDir::Cw` if it is in the
/// negative half-space (to the right). If the line passes through the center, `AngleDir::Ccw`
/// is returned.
///
/// # Arguments
///
/// * `line`: the reference line
///
/// returns: AngleDir
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, AngleDir};
/// use engeom::geom2::Line2;
///
/// let c = Circle2::new(0.0, 1.0, 0.5);
/// // Line along the x-axis pointing right; circle center is above it (CCW side)
/// let line = Line2::new(engeom::Point2::new(0.0, 0.0), engeom::Vector2::new(1.0, 0.0));
/// assert_eq!(c.line_direction(&line), AngleDir::Ccw);
/// ```
pub fn line_direction(&self, line: &impl LineOps2) -> AngleDir {
line.winding_direction(&self.center)
}
/// Return a surface manifold position on the circle perimeter closest to a test entity.
///
/// # Arguments
///
/// * `p`: a test entity with coordinates
///
/// returns: Manifold1Pos2
pub fn at_closest_to_point(&self, p: &impl PCoords<2>) -> Manifold1Pos2 {
let theta = self.angle_of_point(p);
self.at_angle(theta)
}
/// Returns a new circle with its center moved by the given isometry, without modifying the
/// original. The radius is unaffected.
///
/// # Arguments
///
/// * `iso`: the isometry to transform the circle by
///
/// returns: Circle2
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Iso2, Vector2};
/// use engeom::geom2::IsoExtensions2;
/// use approx::assert_relative_eq;
///
/// let c = Circle2::new(1.0, 0.0, 2.0);
/// let moved = c.transformed_by(&Iso2::from_translation(0.0, 3.0));
///
/// assert_relative_eq!(moved.x(), 1.0);
/// assert_relative_eq!(moved.y(), 3.0);
/// assert_relative_eq!(moved.r(), 2.0);
/// ```
pub fn transformed_by(&self, iso: &Iso2) -> Self {
Self {
center: iso * self.center,
radius: self.radius,
}
}
/// Returns a new circle with its radius changed by `delta`, without modifying the original.
/// The center is unaffected.
///
/// A positive `delta` grows the circle and a negative one shrinks it. The result is not
/// clamped, so a large enough negative `delta` will produce a zero or negative radius.
///
/// # Arguments
///
/// * `delta`: the amount to add to the circle's radius
///
/// returns: Circle2
///
/// # Examples
///
/// ```
/// use engeom::Circle2;
/// use approx::assert_relative_eq;
///
/// let c = Circle2::new(1.0, 2.0, 3.0);
/// let bigger = c.resized_by(0.5);
///
/// assert_relative_eq!(bigger.x(), 1.0);
/// assert_relative_eq!(bigger.y(), 2.0);
/// assert_relative_eq!(bigger.r(), 3.5);
/// ```
pub fn resized_by(&self, delta: f64) -> Self {
Self {
center: self.center,
radius: self.radius + delta,
}
}
}
impl Circle2 {
/// Returns the axis-aligned bounding box of the circle, computed on demand.
pub fn aabb(&self) -> Aabb2 {
circle_aabb2(&self.center, self.radius)
}
}
/// Computes the intersection parameters of a line and a circle. The intersection parameters are
/// the values of the line's parameter at the intersection points. There will be zero, one, or two
/// intersection parameters. The intersection points can be recovered from the parameters by
/// calling `line.at(t)`.
///
/// # Arguments
///
/// * `line`:
/// * `circle`:
///
/// returns: Vec<f64, Global>
///
/// # Examples
///
/// ```
/// /// ```
pub fn intersection_line_circle(line: &impl LineOps2, circle: &Circle2) -> Vec<f64> {
// Get the parameter of the circle center onto the line
let tc = line.projected_parameter(&circle.center);
let d = dist(&circle.center, &line.projected_point(&circle.center));
if (d - circle.radius).abs() < 1.0e-10 {
// If the distance from the center to the line is equal to the radius, then there is one
// single intersection point at the tangency point
vec![tc]
} else if d > circle.radius {
// If the distance from the center to the line is greater than the radius, then there
// are no intersection points
Vec::new()
} else {
// There are two intersection points. The distance from the tangency point to the
// intersection points is the height of a right triangle with hypotenuse `r` and base
// `d`.
let h = (circle.radius.powi(2) - d.powi(2)).sqrt();
// We can't simply add and subtract `h` from `tc` because the line may not be
// normalized, so we need to scale the value `h` by the norm of the line's direction
// vector.
let th = h / line.dir().norm();
vec![tc - th, tc + th]
}
}
impl PCoords<2> for Circle2 {
fn coords(&self) -> SVector<f64, 2> {
self.center.coords
}
}
impl ops::Mul<Circle2> for Iso2 {
type Output = Circle2;
fn mul(self, rhs: Circle2) -> Circle2 {
rhs.transformed_by(&self)
}
}
impl ops::Mul<&Circle2> for Iso2 {
type Output = Circle2;
fn mul(self, rhs: &Circle2) -> Circle2 {
rhs.transformed_by(&self)
}
}
impl ops::Mul<Circle2> for &Iso2 {
type Output = Circle2;
fn mul(self, rhs: Circle2) -> Circle2 {
rhs.transformed_by(self)
}
}
impl ops::Mul<&Circle2> for &Iso2 {
type Output = Circle2;
fn mul(self, rhs: &Circle2) -> Circle2 {
rhs.transformed_by(self)
}
}
impl<T: LineOps2> Intersection<T, Vec<f64>> for Circle2 {
fn intersection(&self, other: T) -> Vec<f64> {
intersection_line_circle(&other, self)
}
}
impl Intersection<&Segment2, Vec<Point2>> for Circle2 {
fn intersection(&self, other: &Segment2) -> Vec<Point2> {
let line = other.to_line();
let ts = intersection_line_circle(&line, self);
ts.iter()
.filter_map(|&t| {
if (-1.0e-10..=1.0 + 1.0e-10).contains(&t) {
Some(line.at(t))
} else {
None
}
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geom2::Ray2;
use approx::assert_relative_eq;
use crate::common::random_geometry::RandomGeometry2;
use std::f64::consts::PI;
use test_case::test_case;
#[test]
fn min_enclosing_mixed_boundary_and_interior() {
// Two antipodal points fix the circle; everything else is strictly interior
let points = [
Point2::new(-3.0, 1.0),
Point2::new(5.0, 1.0),
Point2::new(1.0, 2.0),
Point2::new(0.0, 0.0),
Point2::new(3.0, -1.0),
];
let circle = Circle2::from_min_enclosing(&points).unwrap();
assert_relative_eq!(circle.center, Point2::new(1.0, 1.0), epsilon = 1e-12);
assert_relative_eq!(circle.r(), 4.0, epsilon = 1e-12);
}
#[test]
fn simple_tangent_corner() {
let corner = Point2::new(1.0, 1.0);
let v0 = Vector2::new(-1.0, 0.0);
let v1 = Vector2::new(0.0, -1.0);
let circle = Circle2::from_tangent_to_corner(&corner, &v0, &v1, 1.0).unwrap();
assert_relative_eq!(circle.center, Point2::new(0.0, 0.0), epsilon = 1.0e-8);
assert_relative_eq!(circle.r(), 1.0, epsilon = 1.0e-8);
}
/// Checks that every result really is tangent to both the line and the circle, which is the
/// whole contract of `from_tangent_to_line_and_circle`.
fn check_tangency(
found: &[Circle2],
line: &Line2,
circle: &Circle2,
radius: f64,
tangency: CircleTangency,
) {
let expected_center_dist = match tangency {
CircleTangency::Outer => circle.r() + radius,
CircleTangency::Inner => (circle.r() - radius).abs(),
};
for c in found {
assert_relative_eq!(c.r(), radius, epsilon = 1.0e-9);
assert_relative_eq!(
line.signed_projection_dist(&c.center).abs(),
radius,
epsilon = 1.0e-9
);
assert_relative_eq!(
dist(&c.center, &circle.center),
expected_center_dist,
epsilon = 1.0e-9
);
}
}
#[test]
fn tangent_to_line_and_circle_outer() {
// The x axis and a circle of radius 1 centered 2 above it. Two circles of radius 1 fit
// tangent to both, one either side of the circle.
let line = Line2::new(Point2::new(0.0, 0.0), Vector2::new(1.0, 0.0));
let circle = Circle2::new(0.0, 2.0, 1.0);
let found =
Circle2::from_tangent_to_line_and_circle(&line, &circle, 1.0, CircleTangency::Outer);
assert_eq!(found.len(), 2);
check_tangency(&found, &line, &circle, 1.0, CircleTangency::Outer);
// Ordered by ascending parameter along the line, which here is ascending x
assert!(found[0].x() < found[1].x());
assert_relative_eq!(found[0].x(), -3.0_f64.sqrt(), epsilon = 1.0e-9);
assert_relative_eq!(found[1].x(), 3.0_f64.sqrt(), epsilon = 1.0e-9);
}
#[test]
fn tangent_to_line_and_circle_inner() {
// A large circle straddling the x axis; a radius 1 circle tangent to the axis and touching
// the large one from within.
let line = Line2::new(Point2::new(0.0, 0.0), Vector2::new(1.0, 0.0));
let circle = Circle2::new(0.0, 0.0, 5.0);
let found =
Circle2::from_tangent_to_line_and_circle(&line, &circle, 1.0, CircleTangency::Inner);
// Two offset lines, each cutting the radius-4 locus twice
assert_eq!(found.len(), 4);
check_tangency(&found, &line, &circle, 1.0, CircleTangency::Inner);
}
#[test]
fn tangent_to_line_and_circle_ordering_is_stable() {
let line = Line2::new(Point2::new(0.0, 0.0), Vector2::new(1.0, 0.0));
let circle = Circle2::new(0.0, 2.0, 1.0);
let a =
Circle2::from_tangent_to_line_and_circle(&line, &circle, 1.0, CircleTangency::Outer);
let b =
Circle2::from_tangent_to_line_and_circle(&line, &circle, 1.0, CircleTangency::Outer);
assert_eq!(a.len(), b.len());
for (x, y) in a.iter().zip(b.iter()) {
assert_relative_eq!(x.center, y.center, epsilon = 1.0e-12);
}
}
#[test]
fn tangent_to_line_and_circle_impossible_cases() {
let line = Line2::new(Point2::new(0.0, 0.0), Vector2::new(1.0, 0.0));
// A circle far from the line, with a radius too small to bridge the gap
let far = Circle2::new(0.0, 50.0, 1.0);
assert!(
Circle2::from_tangent_to_line_and_circle(&line, &far, 1.0, CircleTangency::Outer)
.is_empty()
);
// A non-positive radius is not a circle
let circle = Circle2::new(0.0, 2.0, 1.0);
assert!(
Circle2::from_tangent_to_line_and_circle(&line, &circle, 0.0, CircleTangency::Outer)
.is_empty()
);
assert!(
Circle2::from_tangent_to_line_and_circle(&line, &circle, -1.0, CircleTangency::Outer)
.is_empty()
);
// Neither is a non-finite one, including NaN, which compares false against everything
for radius in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert!(
Circle2::from_tangent_to_line_and_circle(
&line,
&circle,
radius,
CircleTangency::Outer
)
.is_empty(),
"a radius of {radius} should produce no solutions"
);
}
}
/// The construction should hold up on arbitrary geometry, not just axis-aligned cases.
#[test]
fn stress_tangent_to_line_and_circle() {
let mut rng = RandomGeometry2::new();
let mut found_any = 0;
for _ in 0..1000 {
let circle = rng.circle2(5.0, 0.5, 2.0);
let line = Line2::new(rng.point(5.0), rng.unit_vec().into_inner());
for tangency in [CircleTangency::Outer, CircleTangency::Inner] {
let radius = 1.0;
let found =
Circle2::from_tangent_to_line_and_circle(&line, &circle, radius, tangency);
found_any += found.len();
check_tangency(&found, &line, &circle, radius, tangency);
}
}
assert!(found_any > 0, "the stress test never produced a solution");
}
#[test]
fn stress_tangent_lines() {
let mut rng = RandomGeometry2::new();
for _ in 0..1000 {
let expected = rng.circle2(5.0, 0.5, 2.0);
let tr = rng.f64(0.01, 5.0) + expected.r();
let tv = Iso2::rotation(rng.angle_sym_pi()) * Vector2::new(tr, 0.0);
let tc = expected.center + tv;
let (p0, p1) = expected.tangent_points_to(&tc).unwrap();
let result =
Circle2::from_tangent_to_corner(&tc, &(p0 - tc), &(p1 - tc), expected.r()).unwrap();
assert_relative_eq!(expected.center, result.center, epsilon = 1.0e-8);
assert_relative_eq!(expected.r(), result.r(), epsilon = 1.0e-8);
}
}
#[test_case((0.0, 0.0, 2.0), None)]
#[test_case((1.0, 0.0, 1.0), Some(((0.0, -1.0, 1.0, -1.0), (0.0, 1.0, 1.0, 1.0))))]
#[test_case((2.0, 2.0, 3.0), Some(((-1.0, 0.0, -1.0, 2.0), (0.0, -1.0, 2.0, -1.0))))]
#[test_case((0.5, 0.5, 0.5), Some(((0.0, 1.0, 0.5, 1.0), (1.0, 0.0, 1.0, 0.5))))]
// Tuple shape is dictated by the `test_case` rows below.
#[allow(clippy::type_complexity)]
fn outer_tangencies(
c: (f64, f64, f64),
e: Option<((f64, f64, f64, f64), (f64, f64, f64, f64))>,
) {
let c0 = Circle2::new(0.0, 0.0, 1.0);
let c1 = Circle2::new(c.0, c.1, c.2);
let result = c0.outer_tangents_to(&c1);
if let Some((e0, e1)) = e {
assert!(result.is_some());
let (s0, s1) = result.unwrap();
assert_relative_eq!(s0.a, Point2::new(e0.0, e0.1));
assert_relative_eq!(s0.b, Point2::new(e0.2, e0.3));
assert_relative_eq!(s1.a, Point2::new(e1.0, e1.1));
assert_relative_eq!(s1.b, Point2::new(e1.2, e1.3));
} else {
assert!(result.is_none());
}
}
#[test_case((0.0, 0.0), (1.0, 0.0), vec![-1.0, 1.0])]
#[test_case((0.0, 0.0), (2.0, 0.0), vec![-0.5, 0.5])]
#[test_case((1.0, 0.0), (1.0, 0.0), vec![-2.0, 0.0])]
#[test_case((0.0, 1.0), (1.0, 0.0), vec![0.0])]
#[test_case((0.0, 1.5), (1.0, 0.0), Vec::<f64>::new())]
fn simple_line_intersection(s: (f64, f64), d: (f64, f64), e: Vec<f64>) {
let c = Circle2::new(0.0, 0.0, 1.0);
let l = Ray2::new(Point2::new(s.0, s.1), Vector2::new(d.0, d.1));
// let result = c.intersection(&l);
let result = intersection_line_circle(&l, &c);
assert_eq!(result.len(), e.len());
for (r, e) in result.iter().zip(e.iter()) {
assert_relative_eq!(*e, *r, epsilon = 1.0e-10);
}
}
#[test_case((0.0, 0.0, 1.0), 0.0, (1.0, 0.0))]
#[test_case((0.0, 0.0, 1.0), 90.0, (0.0, 1.0))]
#[test_case((0.0, 0.0, 1.0), 180.0, (-1.0, 0.0))]
#[test_case((0.0, 0.0, 1.0), 360.0, (1.0, 0.0))]
#[test_case((1.0, 1.0, 1.0), 0.0, (2.0, 1.0))]
#[test_case((1.0, 1.0, 1.0), 90.0, (1.0, 2.0))]
#[test_case((1.0, 1.0, 1.0), 180.0, (0.0, 1.0))]
#[test_case((1.0, 1.0, 1.0), 360.0, (2.0, 1.0))]
fn test_circle_point(c: (f64, f64, f64), a: f64, r: (f64, f64)) {
let circle = Circle2::new(c.0, c.1, c.2);
let point = circle.point_at_angle(a * std::f64::consts::PI / 180.0);
assert_relative_eq!(r.0, point.x, epsilon = 1.0e-10);
assert_relative_eq!(r.1, point.y, epsilon = 1.0e-10);
}
#[test]
fn test_intersection_simple() {
let c0 = Circle2::new(0.0, 0.0, 1.0);
let c1 = Circle2::new(1.0, 0.0, 1.0);
let result = c0.intersections_with(&c1);
assert_eq!(result.len(), 2);
assert_relative_eq!(result[0].x, 0.5, epsilon = 1.0e-10);
assert_relative_eq!(result[0].y, 0.8660254037844386, epsilon = 1.0e-10);
assert_relative_eq!(result[1].x, 0.5, epsilon = 1.0e-10);
assert_relative_eq!(result[1].y, -0.8660254037844386, epsilon = 1.0e-10);
}
#[test]
fn tangent_points_to_simple() {
let c = Circle2::new(0.0, 0.0, 1.0);
let p = Point2::new(-1.0, -1.0);
let (p0, p1) = c.tangent_points_to(&p).unwrap();
assert_relative_eq!(p0, Point2::new(-1.0, 0.0));
assert_relative_eq!(p1, Point2::new(0.0, -1.0));
}
#[test]
fn tangent_points_to() {
let c = Circle2::new(0.5, -0.25, 1.1);
let p = Point2::new(-2.1, -3.0);
let (p0, p1) = c.tangent_points_to(&p).unwrap();
assert_relative_eq!(p0, Point2::new(-0.4844568895369135, 0.24075924101671814));
assert_relative_eq!(p1, Point2::new(1.045148109645135, -1.2054127582099456));
}
#[test]
fn outer_tangents_to_contained_circle_is_none() {
// A circle fully inside another has no outer tangents. Both orderings go through a
// different branch of the function, so both are checked.
let inner = Circle2::new(0.1, 0.0, 1.0);
let outer = Circle2::new(0.0, 0.0, 5.0);
assert!(inner.outer_tangents_to(&outer).is_none());
assert!(outer.outer_tangents_to(&inner).is_none());
}
#[test]
fn outer_tangents_to_internally_tangent_circle_is_none() {
// Touching from the inside is the boundary of the contained case
let inner = Circle2::new(4.0, 0.0, 1.0);
let outer = Circle2::new(0.0, 0.0, 5.0);
assert!(inner.outer_tangents_to(&outer).is_none());
assert!(outer.outer_tangents_to(&inner).is_none());
}
#[test]
fn outer_tangents_to_overlapping_circles() {
// Overlapping circles which do not contain each other still have outer tangents
let c0 = Circle2::new(0.0, 0.0, 1.0);
let c1 = Circle2::new(1.5, 0.0, 2.0);
let (s0, s1) = c0.outer_tangents_to(&c1).unwrap();
for s in [s0, s1] {
assert_relative_eq!((s.a - c0.center).norm(), 1.0, epsilon = 1e-10);
assert_relative_eq!((s.b - c1.center).norm(), 2.0, epsilon = 1e-10);
}
}
#[test]
fn ransac_fit() -> Result<()> {
let expected = Circle2::new(2.0, 3.0, 1.2);
let decoy = Circle2::new(0.0, 0.0, 1.0);
let samples = [
make_sample_circle_points(&expected, 100, None),
make_sample_circle_points(&decoy, 50, None),
]
.concat();
let result = Circle2::from_consensus(&samples, 0.005, None, None, None)?;
assert_relative_eq!(result.center, expected.center, epsilon = 3.0e-3);
assert_relative_eq!(result.r(), expected.r(), epsilon = 3.0e-3);
Ok(())
}
#[test]
fn stress_tangent_and_point() -> Result<()> {
// Seeded so a failure is reproducible and so this can never join the flaky-by-RNG set.
let mut random = RandomGeometry2::from_seed(0xc12c_1e2d);
for _ in 0..1000 {
let c = random.circle2(10.0, 0.5, 5.0);
let a0 = random.angle_sym_pi();
let m = c.at_angle(a0);
let line = match random.bool() {
true => m.direction_line(),
false => m.direction_line().reversed(),
};
// A target point near the tangent line (angle near the tangency angle) makes the
// construction ill-conditioned relative to the 1e-5 round-trip tolerance, so draws
// whose perpendicular distance from the line is below 1e-2 are resampled.
let p = loop {
let a1 = random.angle_sym_pi();
let p = c.point_at_angle(a1);
if line.distance_to(&p) > 1e-2 {
break p;
}
};
let result = Circle2::from_tangent_and_point(&line, &p)?;
assert_relative_eq!(result.center, c.center, epsilon = 1.0e-5);
assert_relative_eq!(result.r(), c.r(), epsilon = 1.0e-5);
}
Ok(())
}
#[test]
fn tangent_and_point_on_line_is_error() {
let line = Line2::new(Point2::origin(), Vector2::x());
// A point on the tangent line away from the tangency point
assert!(Circle2::from_tangent_and_point(&line, &Point2::new(3.0, 0.0)).is_err());
// The tangency point itself
assert!(Circle2::from_tangent_and_point(&line, &Point2::origin()).is_err());
}
#[test]
fn stress_transformed_by() {
let mut rng = RandomGeometry2::new();
for _ in 0..1000 {
let original = rng.circle2(5.0, 0.5, 2.0);
let iso = rng.iso2(10.0);
let moved = original.transformed_by(&iso);
assert_relative_eq!(moved.center, iso * original.center, epsilon = 1.0e-10);
assert_relative_eq!(moved.r(), original.r(), epsilon = 1.0e-10);
// A point on the original perimeter must map onto the transformed perimeter
let p = iso * original.point_at_angle(rng.angle_sym_pi());
assert_relative_eq!(moved.distance_to(&p), 0.0, epsilon = 1.0e-10);
// The multiplication operator is an alias for `transformed_by`
let by_mul = iso * original;
assert_relative_eq!(by_mul.center, moved.center, epsilon = 1.0e-12);
assert_relative_eq!(by_mul.r(), moved.r(), epsilon = 1.0e-12);
}
}
#[test]
fn contained_points_keeps_inside_and_boundary_in_order() {
let c = Circle2::new(1.0, 1.0, 1.0);
let points = vec![
Point2::new(1.0, 1.0), // center, inside
Point2::new(5.0, 5.0), // far outside
Point2::new(2.0, 1.0), // exactly on the boundary, counts as inside
Point2::new(1.0, -1.0), // outside
Point2::new(1.5, 1.0), // inside
];
let result = c.contained_points(&points);
assert_eq!(
result,
vec![
Point2::new(1.0, 1.0),
Point2::new(2.0, 1.0),
Point2::new(1.5, 1.0)
]
);
}
#[test]
fn contained_points_matches_contains_point() {
let mut rng = RandomGeometry2::new();
let c = rng.circle2(5.0, 0.5, 2.0);
let points = (0..500).map(|_| rng.point(8.0)).collect::<Vec<_>>();
let expected = points
.iter()
.filter(|p| c.contains_point(*p))
.copied()
.collect::<Vec<_>>();
assert_eq!(c.contained_points(&points), expected);
}
#[test_case(3.0, 0.5, 3.5)]
#[test_case(3.0, -0.5, 2.5)]
#[test_case(3.0, 0.0, 3.0)]
fn resized_by_changes_radius_only(r: f64, delta: f64, expected: f64) {
let c = Circle2::new(1.0, 2.0, r);
let result = c.resized_by(delta);
assert_relative_eq!(result.center, c.center, epsilon = 1.0e-12);
assert_relative_eq!(result.r(), expected, epsilon = 1.0e-12);
}
fn make_sample_circle_points(c: &Circle2, n: usize, sigma: Option<f64>) -> Vec<Point2> {
let mut points = Vec::with_capacity(n);
let angle_step = 2.0 * PI / (n as f64);
let mut rng = RandomGeometry2::new();
for i in 0..n {
let angle = angle_step * i as f64;
let r = if let Some(sigma) = sigma {
rng.gaussian_f64(0.0, sigma)
} else {
0.0
} + c.r();
let point = c.center + Vector2::new(r * angle.cos(), r * angle.sin());
points.push(point);
}
points
}
}