1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.geometry.euclidean.threed.mesh;
18
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.NoSuchElementException;
28 import java.util.Objects;
29 import java.util.TreeMap;
30 import java.util.function.Function;
31 import java.util.stream.Stream;
32 import java.util.stream.StreamSupport;
33
34 import org.apache.commons.geometry.core.Transform;
35 import org.apache.commons.geometry.euclidean.internal.EuclideanUtils;
36 import org.apache.commons.geometry.euclidean.threed.BoundarySource3D;
37 import org.apache.commons.geometry.euclidean.threed.Bounds3D;
38 import org.apache.commons.geometry.euclidean.threed.PlaneConvexSubset;
39 import org.apache.commons.geometry.euclidean.threed.Planes;
40 import org.apache.commons.geometry.euclidean.threed.Triangle3D;
41 import org.apache.commons.geometry.euclidean.threed.Vector3D;
42 import org.apache.commons.numbers.core.Precision;
43
44
45
46
47
48
49
50
51
52
53
54
55 public final class SimpleTriangleMesh implements TriangleMesh {
56
57
58 private final List<Vector3D> vertices;
59
60
61 private final List<int[]> faces;
62
63
64 private final Bounds3D bounds;
65
66
67 private final Precision.DoubleEquivalence precision;
68
69
70
71
72
73
74
75
76 private SimpleTriangleMesh(final List<Vector3D> vertices, final List<int[]> faces, final Bounds3D bounds,
77 final Precision.DoubleEquivalence precision) {
78 this.vertices = Collections.unmodifiableList(vertices);
79 this.faces = Collections.unmodifiableList(faces);
80 this.bounds = bounds;
81 this.precision = precision;
82 }
83
84
85 @Override
86 public Iterable<Vector3D> vertices() {
87 return getVertices();
88 }
89
90
91 @Override
92 public List<Vector3D> getVertices() {
93 return vertices;
94 }
95
96
97 @Override
98 public int getVertexCount() {
99 return vertices.size();
100 }
101
102
103 @Override
104 public Iterable<TriangleMesh.Face> faces() {
105 return () -> new FaceIterator<>(Function.identity());
106 }
107
108
109 @Override
110 public List<TriangleMesh.Face> getFaces() {
111 final int count = getFaceCount();
112
113 final List<Face> faceList = new ArrayList<>(count);
114 for (int i = 0; i < count; ++i) {
115 faceList.add(getFace(i));
116 }
117
118 return faceList;
119 }
120
121
122 @Override
123 public int getFaceCount() {
124 return faces.size();
125 }
126
127
128 @Override
129 public TriangleMesh.Face getFace(final int index) {
130 return new SimpleTriangleFace(index, faces.get(index));
131 }
132
133
134 @Override
135 public Bounds3D getBounds() {
136 return bounds;
137 }
138
139
140
141
142
143 public Precision.DoubleEquivalence getPrecision() {
144 return precision;
145 }
146
147
148 @Override
149 public Stream<PlaneConvexSubset> boundaryStream() {
150 return createFaceStream(Face::getPolygon);
151 }
152
153
154 @Override
155 public Stream<Triangle3D> triangleStream() {
156 return createFaceStream(Face::getPolygon);
157 }
158
159
160 @Override
161 public SimpleTriangleMesh transform(final Transform<Vector3D> transform) {
162
163 final Bounds3D.Builder boundsBuilder = Bounds3D.builder();
164 final List<Vector3D> tVertices = new ArrayList<>(vertices.size());
165
166 Vector3D tVertex;
167 for (final Vector3D vertex : vertices) {
168 tVertex = transform.apply(vertex);
169
170 boundsBuilder.add(tVertex);
171 tVertices.add(tVertex);
172 }
173
174 final Bounds3D tBounds = boundsBuilder.hasBounds() ?
175 boundsBuilder.build() :
176 null;
177
178 return new SimpleTriangleMesh(tVertices, faces, tBounds, precision);
179 }
180
181
182
183
184
185
186
187
188 @Override
189 public SimpleTriangleMesh toTriangleMesh(final Precision.DoubleEquivalence meshPrecision) {
190 if (this.precision.equals(meshPrecision)) {
191 return this;
192 }
193
194 return new SimpleTriangleMesh(vertices, faces, bounds, meshPrecision);
195 }
196
197
198 @Override
199 public String toString() {
200 final StringBuilder sb = new StringBuilder();
201 sb.append(getClass().getSimpleName())
202 .append("[vertexCount= ")
203 .append(getVertexCount())
204 .append(", faceCount= ")
205 .append(getFaceCount())
206 .append(", bounds= ")
207 .append(getBounds())
208 .append(']');
209
210 return sb.toString();
211 }
212
213
214
215
216
217
218
219
220 private <T> Stream<T> createFaceStream(final Function<TriangleMesh.Face, T> fn) {
221 final Iterable<T> iterable = () -> new FaceIterator<>(fn);
222 return StreamSupport.stream(iterable.spliterator(), false);
223 }
224
225
226
227
228
229 public static Builder builder(final Precision.DoubleEquivalence precision) {
230 return new Builder(precision);
231 }
232
233
234
235
236
237
238
239
240
241 public static SimpleTriangleMesh from(final Vector3D[] vertices, final int[][] faces,
242 final Precision.DoubleEquivalence precision) {
243 return from(Arrays.asList(vertices), Arrays.asList(faces), precision);
244 }
245
246
247
248
249
250
251
252
253
254 public static SimpleTriangleMesh from(final Collection<Vector3D> vertices, final Collection<int[]> faces,
255 final Precision.DoubleEquivalence precision) {
256 final Builder builder = builder(precision);
257
258 return builder.addVertices(vertices)
259 .addFaces(faces)
260 .build();
261 }
262
263
264
265
266
267
268
269
270
271
272 public static SimpleTriangleMesh from(final BoundarySource3D boundarySrc,
273 final Precision.DoubleEquivalence precision) {
274 final Builder builder = builder(precision);
275 try (Stream<Triangle3D> stream = boundarySrc.triangleStream()) {
276 stream.forEach(tri -> builder.addFaceUsingVertices(
277 tri.getPoint1(),
278 tri.getPoint2(),
279 tri.getPoint3()));
280 }
281
282 return builder.build();
283 }
284
285
286
287 private final class SimpleTriangleFace implements TriangleMesh.Face {
288
289
290 private final int index;
291
292
293 private final int[] vertexIndices;
294
295 SimpleTriangleFace(final int index, final int[] vertexIndices) {
296 this.index = index;
297 this.vertexIndices = vertexIndices;
298 }
299
300
301 @Override
302 public int getIndex() {
303 return index;
304 }
305
306
307 @Override
308 public int[] getVertexIndices() {
309 return vertexIndices.clone();
310 }
311
312
313 @Override
314 public List<Vector3D> getVertices() {
315 return Arrays.asList(
316 getPoint1(),
317 getPoint2(),
318 getPoint3());
319 }
320
321
322 @Override
323 public Vector3D getPoint1() {
324 return vertices.get(vertexIndices[0]);
325 }
326
327
328 @Override
329 public Vector3D getPoint2() {
330 return vertices.get(vertexIndices[1]);
331 }
332
333
334 @Override
335 public Vector3D getPoint3() {
336 return vertices.get(vertexIndices[2]);
337 }
338
339
340 @Override
341 public boolean definesPolygon() {
342 final Vector3D p1 = getPoint1();
343 final Vector3D v1 = p1.vectorTo(getPoint2());
344 final Vector3D v2 = p1.vectorTo(getPoint3());
345
346 return !precision.eqZero(v1.cross(v2).norm());
347 }
348
349
350 @Override
351 public Triangle3D getPolygon() {
352 return Planes.triangleFromVertices(
353 getPoint1(),
354 getPoint2(),
355 getPoint3(),
356 precision);
357 }
358
359
360 @Override
361 public String toString() {
362 final StringBuilder sb = new StringBuilder();
363 sb.append(getClass().getSimpleName())
364 .append("[index= ")
365 .append(getIndex())
366 .append(", vertexIndices= ")
367 .append(Arrays.toString(getVertexIndices()))
368 .append(", vertices= ")
369 .append(getVertices())
370 .append(']');
371
372 return sb.toString();
373 }
374 }
375
376
377
378
379 private final class FaceIterator<T> implements Iterator<T> {
380
381
382 private int index;
383
384
385 private final Function<? super TriangleMesh.Face, T> fn;
386
387
388
389
390
391 FaceIterator(final Function<? super TriangleMesh.Face, T> fn) {
392 this.fn = fn;
393 }
394
395
396 @Override
397 public boolean hasNext() {
398 return index < faces.size();
399 }
400
401
402 @Override
403 public T next() {
404 if (hasNext()) {
405 final Face face = getFace(index++);
406 return fn.apply(face);
407 }
408 throw new NoSuchElementException();
409 }
410 }
411
412
413
414 public static final class Builder {
415
416
417 private final ArrayList<Vector3D> vertices = new ArrayList<>();
418
419
420 private Map<Vector3D, Integer> vertexIndexMap;
421
422
423 private final ArrayList<int[]> faces = new ArrayList<>();
424
425
426 private final Bounds3D.Builder boundsBuilder = Bounds3D.builder();
427
428
429
430
431 private final Precision.DoubleEquivalence precision;
432
433
434 private boolean built;
435
436
437
438
439
440 private Builder(final Precision.DoubleEquivalence precision) {
441 Objects.requireNonNull(precision, "Precision context must not be null");
442
443 this.precision = precision;
444 }
445
446
447
448
449
450
451
452
453
454
455 public int useVertex(final Vector3D vertex) {
456 final int nextIdx = vertices.size();
457 final int actualIdx = addToVertexIndexMap(vertex, nextIdx, getVertexIndexMap());
458
459
460 if (actualIdx == nextIdx) {
461 addToVertexList(vertex);
462 }
463
464 return actualIdx;
465 }
466
467
468
469
470
471
472
473
474
475 public int addVertex(final Vector3D vertex) {
476 final int idx = addToVertexList(vertex);
477
478 if (vertexIndexMap != null) {
479
480 addToVertexIndexMap(vertex, idx, vertexIndexMap);
481 }
482
483 return idx;
484 }
485
486
487
488
489
490
491 public Builder addVertices(final Vector3D[] newVertices) {
492 return addVertices(Arrays.asList(newVertices));
493 }
494
495
496
497
498
499
500 public Builder addVertices(final Collection<? extends Vector3D> newVertices) {
501 final int newSize = vertices.size() + newVertices.size();
502 ensureVertexCapacity(newSize);
503
504 for (final Vector3D vertex : newVertices) {
505 addVertex(vertex);
506 }
507
508 return this;
509 }
510
511
512
513
514
515
516
517 public Builder ensureVertexCapacity(final int numVertices) {
518 vertices.ensureCapacity(numVertices);
519 return this;
520 }
521
522
523
524
525 public int getVertexCount() {
526 return vertices.size();
527 }
528
529
530
531
532
533
534 public Vector3D getVertex(final int index) {
535 return vertices.get(index);
536 }
537
538
539
540
541
542
543
544
545
546 public Builder addFace(final int index1, final int index2, final int index3) {
547 validateCanModify();
548
549 final int[] indices = {
550 validateVertexIndex(index1),
551 validateVertexIndex(index2),
552 validateVertexIndex(index3)
553 };
554
555 faces.add(indices);
556
557 return this;
558 }
559
560
561
562
563
564
565
566 public Builder addFace(final int[] face) {
567 if (face.length != EuclideanUtils.TRIANGLE_VERTEX_COUNT) {
568 throw new IllegalArgumentException("Face must contain " + EuclideanUtils.TRIANGLE_VERTEX_COUNT +
569 " vertex indices; found " + face.length);
570 }
571
572 addFace(face[0], face[1], face[2]);
573
574 return this;
575 }
576
577
578
579
580
581
582
583 public Builder addFaces(final int[][] faceIndices) {
584 return addFaces(Arrays.asList(faceIndices));
585 }
586
587
588
589
590
591
592
593 public Builder addFaces(final Collection<int[]> faceIndices) {
594 final int newSize = faces.size() + faceIndices.size();
595 ensureFaceCapacity(newSize);
596
597 for (final int[] face : faceIndices) {
598 addFace(face);
599 }
600
601 return this;
602 }
603
604
605
606
607
608
609
610
611
612 public Builder addFaceUsingVertices(final Vector3D p1, final Vector3D p2, final Vector3D p3) {
613 return addFace(
614 useVertex(p1),
615 useVertex(p2),
616 useVertex(p3)
617 );
618 }
619
620
621
622
623
624
625
626
627
628 public Builder addFaceAndVertices(final Vector3D p1, final Vector3D p2, final Vector3D p3) {
629 return addFace(
630 addVertex(p1),
631 addVertex(p2),
632 addVertex(p3)
633 );
634 }
635
636
637
638
639
640
641
642 public Builder ensureFaceCapacity(final int numFaces) {
643 faces.ensureCapacity(numFaces);
644 return this;
645 }
646
647
648
649
650 public int getFaceCount() {
651 return faces.size();
652 }
653
654
655
656
657 public SimpleTriangleMesh build() {
658 built = true;
659
660 final Bounds3D bounds = boundsBuilder.hasBounds() ?
661 boundsBuilder.build() :
662 null;
663
664 vertices.trimToSize();
665 faces.trimToSize();
666
667 return new SimpleTriangleMesh(
668 vertices,
669 faces,
670 bounds,
671 precision);
672 }
673
674
675
676
677 private Map<Vector3D, Integer> getVertexIndexMap() {
678 if (vertexIndexMap == null) {
679 vertexIndexMap = new TreeMap<>(new FuzzyVectorComparator(precision));
680
681
682 final int size = vertices.size();
683 for (int i = 0; i < size; ++i) {
684 addToVertexIndexMap(vertices.get(i), i, vertexIndexMap);
685 }
686 }
687 return vertexIndexMap;
688 }
689
690
691
692
693
694
695
696
697
698
699 private int addToVertexIndexMap(final Vector3D vertex, final int targetIdx,
700 final Map<? super Vector3D, Integer> map) {
701 validateCanModify();
702
703 final Integer actualIdx = map.putIfAbsent(vertex, targetIdx);
704
705 return actualIdx != null ?
706 actualIdx :
707 targetIdx;
708 }
709
710
711
712
713
714 private int addToVertexList(final Vector3D vertex) {
715 validateCanModify();
716
717 boundsBuilder.add(vertex);
718
719 final int idx = vertices.size();
720 vertices.add(vertex);
721
722 return idx;
723 }
724
725
726
727
728
729
730
731 private int validateVertexIndex(final int idx) {
732 if (idx < 0 || idx >= vertices.size()) {
733 throw new IllegalArgumentException("Invalid vertex index: " + idx);
734 }
735
736 return idx;
737 }
738
739
740
741
742 private void validateCanModify() {
743 if (built) {
744 throw new IllegalStateException("Builder instance cannot be modified: mesh construction is complete");
745 }
746 }
747 }
748
749
750
751
752
753 private static final class FuzzyVectorComparator implements Comparator<Vector3D> {
754
755 private final Precision.DoubleEquivalence precision;
756
757
758
759
760
761 FuzzyVectorComparator(final Precision.DoubleEquivalence precision) {
762 this.precision = precision;
763 }
764
765
766 @Override
767 public int compare(final Vector3D a, final Vector3D b) {
768 int result = precision.compare(a.getX(), b.getX());
769 if (result == 0) {
770 result = precision.compare(a.getY(), b.getY());
771 if (result == 0) {
772 result = precision.compare(a.getZ(), b.getZ());
773 }
774 }
775
776 return result;
777 }
778 }
779 }