-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcsg.rs
More file actions
1920 lines (1702 loc) · 56 KB
/
csg.rs
File metadata and controls
1920 lines (1702 loc) · 56 KB
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
//! A Rust port of the CSG.js library by Evan Wallace
//! (https://github.com/evanw/csg.js/).
use std::ops::BitOr;
use arrayvec::ArrayVec;
use common::uninit;
use fxhash::{FxBuildHasher, FxHashMap, FxHashSet};
use lyon_tessellation::{
math::point, path::Path, FillGeometryBuilder, FillOptions, FillTessellator, GeometryBuilder,
};
use nalgebra::Point3;
use parry3d::{
math::Isometry,
shape::{TriMesh, TriMeshFlags},
transformation::{
intersect_meshes_with_tolerances, MeshIntersectionError, MeshIntersectionTolerances,
},
};
use slotmap::Key;
use smallvec::SmallVec;
use crate::{
linked_mesh::{self, DisplacementNormalMethod, Edge, EdgeSplitPos, FaceKey, Vec3, VertexKey},
LinkedMesh,
};
const EPSILON: f32 = 1e-5;
slotmap::new_key_type! {
pub struct NodeKey;
}
pub type NodeMap = slotmap::SlotMap<NodeKey, Node>;
static mut SPLIT_FACE_CACHE: *mut Vec<((FaceKey, FaceData), [FaceKey; 2])> = std::ptr::null_mut();
fn init_split_face_scratch() {
unsafe {
SPLIT_FACE_CACHE = Box::into_raw(Box::new(Vec::new()));
}
}
fn get_split_face_scratch() -> &'static mut Vec<((FaceKey, FaceData), [FaceKey; 2])> {
unsafe {
if SPLIT_FACE_CACHE.is_null() {
init_split_face_scratch();
}
&mut *SPLIT_FACE_CACHE
}
}
#[derive(Clone, Debug)]
pub struct Plane {
pub normal: Vec3,
pub w: f32,
}
#[derive(Debug)]
pub enum Coplanars {
UseFrontBack,
SingleBuffer(NodeKey),
}
#[derive(Clone, Debug)]
pub struct FaceData {
pub plane: Plane,
pub node_key: NodeKey,
}
impl Default for FaceData {
fn default() -> Self {
Self {
plane: Plane {
normal: Vec3::zeros(),
w: 0.,
},
node_key: NodeKey::null(),
}
}
}
impl Coplanars {
pub fn push_front(
&self,
polygon: Polygon,
front_key: NodeKey,
nodes: &mut NodeMap,
mesh: &mut LinkedMesh<FaceData>,
) {
match self {
Coplanars::UseFrontBack => {
polygon.set_node_key(front_key, mesh);
let front = &mut nodes[front_key].polygons;
front.push(polygon);
}
&Coplanars::SingleBuffer(node_key) => {
polygon.set_node_key(node_key, mesh);
let buffer = &mut nodes[node_key].polygons;
buffer.push(polygon);
}
}
}
pub fn push_back(
&self,
poly: Polygon,
back_key: NodeKey,
nodes: &mut NodeMap,
mesh: &mut LinkedMesh<FaceData>,
) {
match self {
Coplanars::UseFrontBack => {
poly.set_node_key(back_key, mesh);
let back = &mut nodes[back_key].polygons;
back.push(poly);
}
&Coplanars::SingleBuffer(node_key) => {
poly.set_node_key(node_key, mesh);
let buffer = &mut nodes[node_key].polygons;
buffer.push(poly);
}
}
}
}
// I'm pretty sure this only works for convex polygons
fn triangulate_polygon<'a>(
vertices: ArrayVec<VertexKey, 4>,
mesh: &'a mut LinkedMesh<FaceData>,
plane: &'a Plane,
node_key: NodeKey,
) -> impl Iterator<Item = Polygon> + 'a {
(2..vertices.len()).map(move |i| {
let face_key = mesh.add_face::<false>(
[vertices[0], vertices[i - 1], vertices[i]],
FaceData {
plane: plane.clone(),
node_key,
},
);
Polygon { key: face_key }
})
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum PolygonClass {
Coplanar = 0,
Front = 1,
Back = 2,
Spanning = 3,
}
impl From<u8> for PolygonClass {
fn from(val: u8) -> Self {
match val {
0 => PolygonClass::Coplanar,
1 => PolygonClass::Front,
2 => PolygonClass::Back,
3 => PolygonClass::Spanning,
_ => panic!("Invalid PolygonClass value"),
}
}
}
impl BitOr for PolygonClass {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
let out = self as u8 | rhs as u8;
out.into()
}
}
const TEMP_NODE_KEY_0: NodeKey = unsafe { std::mem::transmute((1u32, 1u32)) };
const TEMP_NODE_KEY_1: NodeKey = unsafe { std::mem::transmute((1u32, 2u32)) };
fn vtx_pos<T>(vtx_key: VertexKey, mesh: &LinkedMesh<T>) -> Vec3 {
if cfg!(feature = "unsafe_indexing") {
unsafe { mesh.vertices.get_unchecked(vtx_key).position }
} else {
mesh.vertices[vtx_key].position
}
}
fn handle_split_faces(
split_faces: &mut Vec<((FaceKey, FaceData), [FaceKey; 2])>,
mesh: &mut LinkedMesh<FaceData>,
nodes: &mut NodeMap,
) {
for ((old_face_key, old_face_data), new_face_keys) in split_faces.drain(..) {
let node_key = old_face_data.node_key;
let node = nodes.get_mut(node_key).unwrap_or_else(|| {
panic!(
"Couldn't find node with key={node_key:?} referenced by face with key={old_face_key:?}"
)
});
let old_poly_ix = node
.polygons
.iter()
.position(|poly| poly.key == old_face_key)
.unwrap_or_else(|| {
panic!(
"Couldn't find polygon with key={old_face_key:?} in node with key={node_key:?}: \n{:?}",
node.polygons
)
});
node.polygons.swap_remove(old_poly_ix);
node.polygons.extend((0..=1).filter_map(|face_ix| {
let new_face_key = new_face_keys[face_ix];
// if mesh.faces[new_face_keys[face_ix]].is_degenerate(&mesh.vertices) {
// log::warn!("Dropping degenerate face with key={new_face_key:?}");
// mesh.remove_face(new_face_key);
// return None;
// }
let poly = Polygon { key: new_face_key };
let user_data = poly.user_data_mut(mesh);
user_data.plane = old_face_data.plane.clone();
user_data.node_key = node_key;
Some(poly)
}));
}
}
impl Plane {
pub fn flip(&mut self) {
self.normal = -self.normal;
self.w = -self.w;
}
pub fn from_points(a: Vec3, b: Vec3, c: Vec3) -> Self {
let normal = (b - a).cross(&(c - a)).normalize();
let w = normal.dot(&a);
Self { normal, w }
}
// Finds an arbitrary point on the plane
fn point_on_plane(&self) -> Vec3 {
if self.normal.x.abs() > 0.1 {
// Avoid division by a small number
Vec3::new(-self.w / self.normal.x, 0.0, 0.0)
} else if self.normal.y.abs() > 0.1 {
Vec3::new(0.0, -self.w / self.normal.y, 0.0)
} else {
Vec3::new(0.0, 0.0, -self.w / self.normal.z)
}
}
// Compute two orthogonal vectors in the plane
pub fn compute_basis(&self) -> (Vec3, Vec3) {
let u = if self.normal.x.abs() > self.normal.z.abs() {
Vec3::new(-self.normal.y, self.normal.x, 0.0).normalize()
} else {
Vec3::new(0.0, -self.normal.z, self.normal.y).normalize()
};
let v = self.normal.cross(&u).normalize();
(u, v)
}
// Project a 3D point to this plane's 2D coordinates
pub fn to_2d(&self, point: Vec3, u: &Vec3, v: &Vec3) -> [f32; 2] {
let point_on_plane = self.point_on_plane();
let relative_point = point - point_on_plane;
let x = relative_point.dot(u);
let y = relative_point.dot(v);
[x, y]
}
// Reconstruct a 3D point from 2D coordinates in this plane
pub fn to_3d(&self, x: f32, y: f32, u: &Vec3, v: &Vec3) -> Vec3 {
let point_on_plane = self.point_on_plane();
point_on_plane + u * x + v * y
}
/// Split `polygon` by this plane if needed, then put the polygon or polygon
/// fragments in the appropriate lists.
///
/// Coplanar polygons go into either `coplanar_front` or `coplanar_back`
/// depending on their orientation with respect to this plane. Polygons in
/// front or in back of this plane go into either `front` or `back`.
pub fn split_polygon(
&self,
plane_node_key: Option<NodeKey>,
polygon: Polygon,
coplanars: Coplanars,
front_key: NodeKey,
back_key: NodeKey,
mesh: &mut LinkedMesh<FaceData>,
nodes: &mut NodeMap,
) {
let mut polygon_type = PolygonClass::Coplanar;
let mut types = [PolygonClass::Coplanar; 3];
for (vtx_ix, vtx) in mesh.faces[polygon.key].vertices.iter().copied().enumerate() {
let t = self.normal.dot(&vtx_pos(vtx, mesh)) - self.w;
let polygon_class = if t < -EPSILON {
PolygonClass::Back
} else if t > EPSILON {
PolygonClass::Front
} else {
PolygonClass::Coplanar
};
polygon_type = polygon_type | polygon_class;
types[vtx_ix] = polygon_class;
}
// Put the polygon in the correct list, splitting it when necessary.
match polygon_type {
PolygonClass::Coplanar => {
if self.normal.dot(&polygon.plane(mesh).normal) > 0. {
coplanars.push_front(polygon, front_key, nodes, mesh);
} else {
coplanars.push_back(polygon, back_key, nodes, mesh);
}
}
PolygonClass::Front => {
polygon.set_node_key(front_key, mesh);
nodes[front_key].polygons.push(polygon);
}
PolygonClass::Back => {
polygon.set_node_key(back_key, mesh);
nodes[back_key].polygons.push(polygon);
}
PolygonClass::Spanning => {
let mut f = ArrayVec::<VertexKey, 4>::new();
let mut b = ArrayVec::<VertexKey, 4>::new();
let mut split_vertices = ArrayVec::<_, 2>::new();
let verts = mesh.faces[polygon.key].vertices;
let old_poly_user_data = mesh.remove_face(polygon.key);
let split_faces = get_split_face_scratch();
assert!(split_faces.is_empty());
for i in 0..3 {
let j = (i + 1) % 3;
let ti = types[i];
let tj = types[j];
let vi_key = verts[i];
let vj_key = verts[j];
if ti != PolygonClass::Back {
f.push(vi_key);
}
if ti != PolygonClass::Front {
b.push(vi_key);
}
if (ti | tj) == PolygonClass::Spanning {
let vi = &mesh.vertices[vi_key];
let vj = &mesh.vertices[vj_key];
let t = (self.w - self.normal.dot(&vi.position))
/ self.normal.dot(&(vj.position - vi.position));
let middle_vtx_key = if let Some(edge_key) = mesh.get_edge_key([vi_key, vj_key]) {
mesh.split_edge_cb(
edge_key,
EdgeSplitPos {
pos: t,
start_vtx_key: vi_key,
},
DisplacementNormalMethod::Interpolate,
|_mesh, old_face_key, old_face_data, new_face_keys| {
split_faces.push(((old_face_key, old_face_data), new_face_keys))
},
)
} else {
// The face we're splitting is the only one that uses this edge, we can just
// add the new vertex to the mesh
let position = vi.position.lerp(&vj.position, t);
let shading_normal = match (vi.shading_normal, vj.shading_normal) {
(Some(n0), Some(n1)) => Some(n0.lerp(&n1, t).normalize()),
_ => None,
};
let displacement_normal = match (vi.displacement_normal, vj.displacement_normal) {
(Some(n0), Some(n1)) => Some(n0.lerp(&n1, t).normalize()),
_ => None,
};
mesh.vertices.insert(linked_mesh::Vertex {
position,
shading_normal,
displacement_normal,
edges: SmallVec::new(),
_padding: Default::default(),
})
};
f.push(middle_vtx_key);
b.push(middle_vtx_key);
split_vertices.push(middle_vtx_key);
}
}
if f.len() >= 3 {
nodes[front_key].polygons.extend(triangulate_polygon(
f,
mesh,
&old_poly_user_data.plane,
front_key,
));
}
if b.len() >= 3 {
nodes[back_key].polygons.extend(triangulate_polygon(
b,
mesh,
&old_poly_user_data.plane,
back_key,
));
}
handle_split_faces(split_faces, mesh, nodes);
if let Some(_plane_node_key) = plane_node_key {
// weld_polygons(&split_vertices, plane_node_key, mesh, nodes);
}
}
}
}
}
#[derive(Debug)]
pub struct Polygon {
pub key: FaceKey,
}
impl Polygon {
pub fn user_data<'a, T>(&self, mesh: &'a LinkedMesh<T>) -> &'a T {
if cfg!(feature = "unsafe_indexing") {
unsafe { &mesh.faces.get_unchecked(self.key).data }
} else {
&mesh.faces[self.key].data
}
}
pub fn user_data_mut<'a, T>(&self, mesh: &'a mut LinkedMesh<T>) -> &'a mut T {
if cfg!(feature = "unsafe_indexing") {
unsafe { &mut mesh.faces.get_unchecked_mut(self.key).data }
} else {
&mut mesh.faces[self.key].data
}
}
pub fn plane<'a>(&self, mesh: &'a LinkedMesh<FaceData>) -> &'a Plane {
&self.user_data(mesh).plane
}
pub fn plane_mut<'a>(&self, mesh: &'a mut LinkedMesh<FaceData>) -> &'a mut Plane {
&mut self.user_data_mut(mesh).plane
}
pub fn flip(&mut self, mesh: &mut LinkedMesh<FaceData>) {
let user_data = self.user_data_mut(mesh);
user_data.plane.flip();
let verts = &mut mesh.faces[self.key].vertices;
verts.swap(0, 2);
}
fn compute_plane(&self, mesh: &mut LinkedMesh<FaceData>) {
let [v0_pos, v1_pos, v2_pos] = self.vtx_coords(mesh);
*self.plane_mut(mesh) = Plane::from_points(v0_pos, v1_pos, v2_pos);
}
fn set_node_key(&self, node_key: NodeKey, mesh: &mut LinkedMesh<FaceData>) {
self.user_data_mut(mesh).node_key = node_key;
}
#[cfg(feature = "broken-csg-welding")]
fn vtx2(&self, ix0: usize, ix1: usize, mesh: &LinkedMesh<FaceData>) -> [VertexKey; 2] {
let face = if cfg!(feature = "unsafe_indexing") {
unsafe { mesh.faces.get_unchecked(self.key) }
} else {
&mesh.faces[self.key]
};
[face.vertices[ix0], face.vertices[ix1]]
}
fn vtx_coords(&self, mesh: &LinkedMesh<FaceData>) -> [Vec3; 3] {
if cfg!(feature = "unsafe_indexing") {
unsafe {
let face = mesh.faces.get_unchecked(self.key);
[
mesh.vertices.get_unchecked(face.vertices[0]).position,
mesh.vertices.get_unchecked(face.vertices[1]).position,
mesh.vertices.get_unchecked(face.vertices[2]).position,
]
}
} else {
let face = &mesh.faces[self.key];
[
mesh.vertices[face.vertices[0]].position,
mesh.vertices[face.vertices[1]].position,
mesh.vertices[face.vertices[2]].position,
]
}
}
}
#[cfg(feature = "broken-csg-welding")]
#[derive(Debug, Clone, Copy, PartialEq)]
enum Intersection {
NoIntersection,
WithinCenter,
OnEdge {
/// 0 -> (v0, v1); 1 -> (v1, v2); 2 -> (v2, v0)
edge_ix: u8,
/// Interpolation factor between the two vertices that the point is on
factor: f32,
},
OnVertex {
vtx_ix: u8,
},
}
#[cfg(feature = "broken-csg-welding")]
fn cartesian_vector_to_barycentric(vert_coords: &[Vec3; 3], face_vec: Vec3) -> Vec3 {
let v0 = vert_coords[1] - vert_coords[0];
let v1 = vert_coords[2] - vert_coords[0];
let v2 = face_vec - vert_coords[0];
let d00 = v0.dot(&v0);
let d01 = v0.dot(&v1);
let d11 = v1.dot(&v1);
let d20 = v2.dot(&v0);
let d21 = v2.dot(&v1);
let denom = d00 * d11 - d01 * d01;
let v = (d11 * d20 - d01 * d21) / denom;
let w = (d00 * d21 - d01 * d20) / denom;
let u = 1.0 - v - w;
Vec3::new(u, v, w)
}
#[cfg(feature = "broken-csg-welding")]
#[test]
fn barycentric_correctness() {
let tri = [
Vec3::new(0., 0., 0.),
Vec3::new(1., 0., 0.),
Vec3::new(0., 1., 0.),
];
let p = Vec3::new(0.5, 0.5, 0.);
let bary = cartesian_vector_to_barycentric(&tri, p);
assert_eq!(bary, Vec3::new(0., 0.5, 0.5));
}
#[cfg(feature = "broken-csg-welding")]
#[test]
fn barycentric_on_edge() {
let tri = [
Vec3::new(0., 0., 0.),
Vec3::new(1., 0., 0.),
Vec3::new(0., 1., 0.),
];
let p = Vec3::new(0., 0.5, 0.);
let bary = cartesian_vector_to_barycentric(&tri, p);
assert_eq!(bary, Vec3::new(0.5, 0., 0.5));
}
/// Determines if a point is inside a triangle in 3D space using barycentric coordinates.
#[cfg(feature = "broken-csg-welding")]
fn triangle_contains_point(vert_coords: &[Vec3; 3], p: Vec3, epsilon: f32) -> Intersection {
let barycentric = cartesian_vector_to_barycentric(vert_coords, p);
if barycentric.x < -epsilon || barycentric.y < -epsilon || barycentric.z < -epsilon {
return Intersection::NoIntersection;
}
// if any coordinate is equal to 1 (considering epsilon), the point is on a vertex
if barycentric.x > 1. - epsilon {
return Intersection::OnVertex { vtx_ix: 0 };
} else if barycentric.y > 1. - epsilon {
return Intersection::OnVertex { vtx_ix: 1 };
} else if barycentric.z > 1. - epsilon {
return Intersection::OnVertex { vtx_ix: 2 };
}
// If any coordinate is equal to 0 (considering epsilon), the point is on an edge
if barycentric.x < epsilon {
return Intersection::OnEdge {
edge_ix: 1,
factor: barycentric.z,
};
} else if barycentric.y < epsilon {
return Intersection::OnEdge {
edge_ix: 2,
factor: barycentric.x,
};
} else if barycentric.z < epsilon {
return Intersection::OnEdge {
edge_ix: 0,
factor: barycentric.y,
};
}
// If none of the above conditions are met, the point is inside the triangle
Intersection::WithinCenter
}
#[cfg(feature = "broken-csg-welding")]
#[test]
fn contains_point_on_edge() {
let tri = [
Vec3::new(0., 0., 0.),
Vec3::new(1., 0., 0.),
Vec3::new(0., 1., 0.),
];
let p = Vec3::new(0., 0.5, 0.);
let res = triangle_contains_point(&tri, p, EPSILON);
assert_eq!(
res,
Intersection::OnEdge {
edge_ix: 2,
factor: 0.5
}
);
let p = Vec3::new(0.5, 0., 0.);
let res = triangle_contains_point(&tri, p, EPSILON);
assert_eq!(
res,
Intersection::OnEdge {
edge_ix: 0,
factor: 0.5
}
);
}
#[cfg(feature = "broken-csg-welding")]
#[test]
fn contains_point_on_vertex() {
let tri = [
Vec3::new(0., 0., 0.),
Vec3::new(1., 0., 0.),
Vec3::new(0., 1., 0.),
];
let p = Vec3::new(0., 0., 0.);
let res = triangle_contains_point(&tri, p, EPSILON);
assert_eq!(res, Intersection::OnVertex { vtx_ix: 0 });
let p = Vec3::new(1., 0., 0.);
let res = triangle_contains_point(&tri, p, EPSILON);
assert_eq!(res, Intersection::OnVertex { vtx_ix: 1 });
}
#[cfg(feature = "broken-csg-welding")]
fn weld_polygon_at_interior<'a>(
vtx: VertexKey,
poly: &Polygon,
mesh: &'a mut LinkedMesh<FaceData>,
) -> impl Iterator<Item = Polygon> + 'a {
let verts = &mesh.faces[poly.key].vertices;
let verts = [
[verts[0], verts[1], vtx],
[verts[2], vtx, verts[1]],
[verts[2], verts[0], vtx],
];
let old_user_data = mesh.remove_face(poly.key);
verts.into_iter().map(move |verts| {
let face_key = mesh.add_face(
verts,
FaceData {
plane: old_user_data.plane.clone(),
node_key: old_user_data.node_key,
},
);
Polygon { key: face_key }
})
}
/// `edge_pos` is the interpolation factor between the two vertices that the point is on
#[cfg(feature = "broken-csg-welding")]
fn weld_polygon_on_edge<'a>(
out_temp_node_key: NodeKey,
poly: Polygon,
edge_ix: u8,
mesh: &'a mut LinkedMesh<FaceData>,
nodes: &'a mut NodeMap,
edge_pos: f32,
) -> impl Iterator<Item = Polygon> + 'a {
let [v0, v1] = match edge_ix {
0 => poly.vtx2(0, 1, mesh),
1 => poly.vtx2(1, 2, mesh),
2 => poly.vtx2(2, 0, mesh),
_ => unreachable!(),
};
let split_faces = get_split_face_scratch();
assert!(split_faces.is_empty());
let edge = mesh
.get_edge_key([v0, v1])
.unwrap_or_else(|| panic!("Couldn't find edge key for vertices {v0:?} and {v1:?}",));
// Need to move the polygon into the temporary node so that we can split it
let poly_key = poly.key;
poly.set_node_key(out_temp_node_key, mesh);
nodes[out_temp_node_key].polygons.push(poly);
mesh.split_edge_cb(
edge,
EdgeSplitPos {
pos: edge_pos,
start_vtx_key: v0,
},
DisplacementNormalMethod::Interpolate,
|_mesh, old_face_key, old_face_data, new_face_keys| {
split_faces.push(((old_face_key, old_face_data), new_face_keys))
},
);
let new_poly_keys: [FaceKey; 2] = split_faces
.iter()
.find(|((old_key, _old_data), _new_keys)| *old_key == poly_key)
.unwrap()
.1;
handle_split_faces(split_faces, mesh, nodes);
// take the new polygons out of the temporary node so we can try them with the second vertex if
// needed
(0..2).filter_map(move |i| {
let poly = nodes[out_temp_node_key]
.polygons
.iter()
.position(|poly| poly.key == new_poly_keys[i])
.map(|ix| nodes[out_temp_node_key].polygons.swap_remove(ix))?;
poly.set_node_key(out_temp_node_key, mesh);
Some(poly)
})
}
/// Checks if `poly` contains `vtx`. If it does, the polygon is split into three
/// polygons and the new polygons are returned. If it doesn't, `None` is returned.
#[cfg(feature = "broken-csg-welding")]
fn maybe_weld_polygon(
vtx: VertexKey,
out_tmp_key: NodeKey,
poly: Polygon,
mesh: &mut LinkedMesh<FaceData>,
nodes: &mut NodeMap,
) -> ArrayVec<Polygon, 3> {
let vert_coords = poly.vtx_coords(mesh);
// the epsilon value below seems to matter quite a bit. The triangle intersection test seems
// quite prone to floating point precision issues.
let ixn = triangle_contains_point(&vert_coords, vtx_pos(vtx, mesh), 1e-4);
match ixn {
Intersection::NoIntersection => ArrayVec::from_iter(std::iter::once(poly)),
Intersection::WithinCenter => ArrayVec::from_iter(weld_polygon_at_interior(vtx, &poly, mesh)),
Intersection::OnEdge { edge_ix, factor } => {
let split_polys = weld_polygon_on_edge(out_tmp_key, poly, edge_ix, mesh, nodes, factor);
ArrayVec::from_iter(split_polys)
}
Intersection::OnVertex { vtx_ix: _ } => {
// I guess we ignore for now since vertices are merged at the end anyway...
ArrayVec::from_iter(std::iter::once(poly))
}
}
}
#[cfg(feature = "broken-csg-welding")]
fn weld_polygons(
split_vertices: &[VertexKey],
plane_node_key: NodeKey,
mesh: &mut LinkedMesh<FaceData>,
nodes: &mut NodeMap,
) {
if split_vertices.is_empty() {
return;
}
assert!(
split_vertices.len() <= 2,
"should only have a max of 2 vertices intersecting a triangle; weird co-incident or fully \
contained tri?"
);
let plane_node = &mut nodes[plane_node_key];
if plane_node.polygons.is_empty() {
return;
}
// Splitting edges during this process can cause arbitrary polygons in arbitrary nodes to be
// split, so all the in-flight/temp polygons have to live in nodes in order to keep things valid
// during this whole process.
let out_tmp_key = TEMP_NODE_KEY_0;
let intermediate_tmp_key = TEMP_NODE_KEY_1;
while let Some(poly) = nodes[plane_node_key].polygons.pop() {
let new_polys = maybe_weld_polygon(split_vertices[0], out_tmp_key, poly, mesh, nodes);
if split_vertices.len() < 2 {
for poly in &new_polys {
poly.set_node_key(out_tmp_key, mesh);
}
nodes[out_tmp_key].polygons.extend(new_polys);
continue;
}
for poly in &new_polys {
poly.set_node_key(intermediate_tmp_key, mesh);
}
nodes[intermediate_tmp_key].polygons.extend(new_polys);
// for each new poly, we check if it contains the second vertex and split/weld it as well
// if it does
while let Some(poly) = nodes[intermediate_tmp_key].polygons.pop() {
let new_polys = maybe_weld_polygon(split_vertices[1], out_tmp_key, poly, mesh, nodes);
for poly in &new_polys {
poly.set_node_key(out_tmp_key, mesh);
}
nodes[out_tmp_key].polygons.extend(new_polys);
}
}
assert!(nodes[intermediate_tmp_key].polygons.is_empty());
assert!(nodes[plane_node_key].polygons.is_empty());
let out_tmp_polys_ptr = &mut nodes[out_tmp_key].polygons as *mut Vec<Polygon>;
std::mem::swap(&mut nodes[plane_node_key].polygons, unsafe {
&mut *out_tmp_polys_ptr
});
for poly in &nodes[plane_node_key].polygons {
poly.set_node_key(plane_node_key, mesh);
}
}
pub struct Node {
pub plane: Option<Plane>,
pub front: Option<NodeKey>,
pub back: Option<NodeKey>,
pub polygons: Vec<Polygon>,
}
impl Node {
/// Convert solid space to empty space and empty space to solid space.
pub fn invert(self_key: NodeKey, nodes: &mut NodeMap, mesh: &mut LinkedMesh<FaceData>) {
let (front, back) = {
let this = &mut nodes[self_key];
for polygon in &mut this.polygons {
polygon.flip(mesh);
}
if let Some(plane) = &mut this.plane {
plane.flip();
}
std::mem::swap(&mut this.front, &mut this.back);
(this.front, this.back)
};
if let Some(front_key) = front {
Node::invert(front_key, nodes, mesh);
}
if let Some(back_key) = back {
Node::invert(back_key, nodes, mesh);
}
}
pub fn clip_polygons(
self_key: NodeKey,
from_key: NodeKey,
mesh: &mut LinkedMesh<FaceData>,
nodes: &mut NodeMap,
preserve_from_node: bool,
) -> Vec<Polygon> {
let (plane, front_key, back_key) = {
let this = &mut nodes[self_key];
let Some(plane) = &this.plane else {
return std::mem::take(&mut this.polygons);
};
(plane.clone(), this.front, this.back)
};
// create temporary nodes to hold the new front and back polys
let temp_front_key = nodes.insert(Node {
plane: None,
front: None,
back: None,
polygons: Vec::new(),
});
let temp_back_key = nodes.insert(Node {
plane: None,
front: None,
back: None,
polygons: Vec::new(),
});
while let Some(polygon) = nodes[from_key].polygons.pop() {
plane.split_polygon(
Some(self_key),
polygon,
Coplanars::UseFrontBack,
temp_front_key,
temp_back_key,
mesh,
nodes,
);
}
if !preserve_from_node {
assert!(nodes.remove(from_key).unwrap().polygons.is_empty());
}
let mut front;
let mut back = Vec::new();
if let Some(front_key) = front_key {
front = Node::clip_polygons(front_key, temp_front_key, mesh, nodes, true);
// we have to put them back into a temp node because clipping the back polys might cause some
// of them to be split
assert!(nodes[temp_front_key].polygons.is_empty());
for poly in &front {
poly.set_node_key(temp_front_key, mesh);
}
nodes[temp_front_key].polygons = front;
}
if let Some(back_key) = back_key {
back = Node::clip_polygons(back_key, temp_back_key, mesh, nodes, false);
} else {
for poly in nodes.remove(temp_back_key).unwrap().polygons {
mesh.remove_face(poly.key);
}
}
front = nodes.remove(temp_front_key).unwrap().polygons;
front.extend(back);
front
}
// Recursively remove all polygons in `polygons` that are inside this BSP tree.
pub fn clip_to(
self_key: NodeKey,
bsp_key: NodeKey,
mesh: &mut LinkedMesh<FaceData>,
nodes: &mut NodeMap,
) {
let new_this_polygons = Node::clip_polygons(bsp_key, self_key, mesh, nodes, true);
let (front, back) = {
let this = &mut nodes[self_key];
for poly in &new_this_polygons {
poly.set_node_key(self_key, mesh);
}
this.polygons = new_this_polygons;
(this.front, this.back)
};
if let Some(front_key) = front {
Node::clip_to(front_key, bsp_key, mesh, nodes);
}
if let Some(back_key) = back {
Node::clip_to(back_key, bsp_key, mesh, nodes);
}
}
fn compute_perimeter(
&self,
mesh: &LinkedMesh<FaceData>,
) -> Option<(Vec<VertexKey>, Vec<VertexKey>)> {
// don't bother re-meshing already trivial polygons
if self.polygons.len() < 3 {
return None;
}
let all_vtx_keys: FxHashSet<_> = self
.polygons
.iter()
.flat_map(|poly| mesh.faces[poly.key].vertices)
.collect();
let all_face_keys = self
.polygons
.iter()
.map(|poly| poly.key)
.collect::<FxHashSet<_>>();
fn is_boundary_edge(edge: &Edge, all_face_keys: &FxHashSet<FaceKey>) -> bool {
edge
.faces
.iter()
.filter(|&face| all_face_keys.contains(face))
.count()
== 1
}
fn is_interior_vtx(
vtx_key: VertexKey,
mesh: &LinkedMesh<FaceData>,
all_face_keys: &FxHashSet<FaceKey>,
) -> bool {
let vtx = &mesh.vertices[vtx_key];
vtx.edges.iter().all(|&edge_key| {
let edge = &mesh.edges[edge_key];
!is_boundary_edge(edge, all_face_keys)
})
}