forked from miho/JCSG
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCSG.java
More file actions
4147 lines (3711 loc) · 119 KB
/
CSG.java
File metadata and controls
4147 lines (3711 loc) · 119 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
/*
* CSG.java
*
* Copyright 2014-2014 Michael Hoffer info@michaelhoffer.de. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY Michael Hoffer info@michaelhoffer.de "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL Michael Hoffer info@michaelhoffer.de OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of Michael Hoffer
* info@michaelhoffer.de.
*/
package eu.mihosoft.vrl.v3d;
import eu.mihosoft.vrl.v3d.ext.org.poly2tri.PolygonUtil;
import eu.mihosoft.vrl.v3d.ext.quickhull3d.HullUtil;
import eu.mihosoft.vrl.v3d.parametrics.CSGDatabase;
import eu.mihosoft.vrl.v3d.parametrics.CSGDatabaseInstance;
import eu.mihosoft.vrl.v3d.parametrics.IParametric;
import eu.mihosoft.vrl.v3d.parametrics.IRegenerate;
import eu.mihosoft.vrl.v3d.parametrics.LengthParameter;
import eu.mihosoft.vrl.v3d.parametrics.Parameter;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.aparapi.Kernel;
import com.aparapi.Kernel.EXECUTION_MODE;
import com.aparapi.Range;
import com.aparapi.device.Device;
import com.aparapi.internal.kernel.KernelManager;
import com.aparapi.internal.kernel.KernelRunner;
import com.neuronrobotics.interaction.CadInteractionEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.CullFace;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.MeshView;
import javafx.scene.text.Font;
import javafx.scene.transform.Affine;
/**
* Constructive Solid Geometry (CSG).
* <p>
* This implementation is a Java port of
* <p>
* <a href=
* "https://github.com/evanw/csg.js/">https://github.com/evanw/csg.js/</a> with
* some additional features like polygon extrude, transformations etc. Thanks to
* the author for creating the CSG.js library.<br>
* <p>
* <b>Implementation Details</b>
* <p>
* All CSG operations are implemented in terms of two functions,
* {@link Node#clipTo(eu.mihosoft.vrl.v3d.Node)} and {@link Node#invert()},
* which remove parts of a BSP tree inside another BSP tree and swap solid and
* empty space, respectively. To find the union of {@code a} and {@code b}, we
* want to remove everything in {@code a} inside {@code b} and everything in
* {@code b} inside {@code a}, then combine polygons from {@code a} and
* {@code b} into one solid:
* <p>
* <blockquote>
*
* <pre>
* a.clipTo(b);
* b.clipTo(a);
* a.build(b.allPolygons());
* </pre>
*
* </blockquote>
* <p>
* The only tricky part is handling overlapping coplanar polygons in both trees.
* The code above keeps both copies, but we need to keep them in one tree and
* remove them in the other tree. To remove them from {@code b} we can clip the
* inverse of {@code b} against {@code a}. The code for union now looks like
* this:
* <p>
* <blockquote>
*
* <pre>
* a.clipTo(b);
* b.clipTo(a);
* b.invert();
* b.clipTo(a);
* b.invert();
* a.build(b.allPolygons());
* </pre>
*
* </blockquote>
* <p>
* Subtraction and intersection naturally follow from set operations. If union
* is {@code A | B}, differenceion is {@code A - B = ~(~A | B)} and intersection
* is {@code A & B =
* ~(~A | ~B)} where {@code ~} is the complement operator.
*/
@SuppressWarnings("restriction")
public class CSG implements IuserAPI, Serializable {
transient private static final double POINTS_CONTACT_DISTANCE = Plane.getEPSILON();//0.0001;
transient private static int MinPolygonsForOffloading = 200;
transient private static final long serialVersionUID = 4071874097772427063L;
//transient private static IDebug3dProvider providerOf3d = null;
transient private static int numFacesInOffset = 15;
transient public static final int INDEX_OF_PARAMETRIC_DEFAULT = 0;
transient public static final int INDEX_OF_PARAMETRIC_LOWER = 1;
transient public static final int INDEX_OF_PARAMETRIC_UPPER = 2;
transient private static HashMap<String, PrepForManufacturing> manufactuingMap = new HashMap<String, PrepForManufacturing>();
transient private static HashMap<String, IRegenerate> regenerate = new HashMap<String, IRegenerate>();
transient private static HashMap<String, Affine> manipulator = new HashMap<String, Affine>();
transient private static OptType defaultOptType = OptType.CSG_BOUND;
transient private static String defaultcolor = "#007956";
// private boolean triangulated;
transient private static boolean useStackTraces = true;
transient private static boolean preventNonManifoldTriangles = false;
transient private static boolean warned = false;
// GPU processing
transient private static boolean useGPU = false;
transient private static int ExtraSpace = 100;
transient private static ICSGProgress progressMoniter = new ICSGProgress() {
@Override
public void progressUpdate(int currentIndex, int finalIndex, String type, CSG intermediateShape) {
System.err.println(type + " cur:" + currentIndex + " of " + finalIndex);
}
};
transient private static ForkJoinPool poolGlobal = null;
/** The polygons. */
private ArrayList<Polygon> polygons;
/** The default opt type. */
/** The opt type. */
private OptType optType = null;
/** The storage. */
private PropertyStorage str;
private PropertyStorage assembly;
/** The current. */
transient private MeshView current;
/** The color. */
// private Color color = getDefaultColor();
private double r = getDefaultColor().getRed();
private double g = getDefaultColor().getGreen();
private double b = getDefaultColor().getBlue();
private double o = getDefaultColor().getOpacity();
/** The manipulator. */
private Bounds bounds;
private ArrayList<String> groovyFileLines = new ArrayList<>();
private boolean markForRegeneration = false;
private String name = "";
private ArrayList<Transform> slicePlanes = null;
private ArrayList<String> exportFormats = null;
private ArrayList<Transform> datumReferences = null;
private int pointsAdded;
private String uniqueId = UUID.randomUUID().toString();
/**
* Instantiates a new csg.
*/
public CSG() {
setStorage(new PropertyStorage());
if (useStackTraces) {
// This is the trace for where this csg was created
addStackTrace(new Exception());
}
}
public CSG setID(CSG dying) {
uniqueId = dying.uniqueId;
return this;
}
@Override
public boolean equals(Object obj) {
// Check if same reference
if (this == obj)
return true;
// Check if null or different class
if (obj == null || getClass() != obj.getClass())
return false;
// Cast and compare fields
CSG test = (CSG) obj;
return this.getUniqueId().contentEquals(test.getUniqueId());
}
@Override
public int hashCode() {
return getUniqueId().hashCode();
}
public CSG addDatumReference(Transform t) {
if (getDatumReferences() == null)
setDatumReferences(new ArrayList<Transform>());
getDatumReferences().add(t);
return this;
}
public CSG prepForManufacturing() {
if (getManufacturing() == null)
return this;
CSG ret = getManufacturing().prep(this);
if (ret == null)
return null;
ret.setName(getName());
ret.setColor(getColor());
ret.slicePlanes = slicePlanes;
ret.exportFormats = exportFormats;
return ret;
}
/**
* Gets the color.
*
* @return the color
*/
public Color getColor() {
return new Color(r, g, b, o);
}
/**
* Sets the color.
*
* @param color the new color
*/
public CSG setColor(javafx.scene.paint.Color color) {
r = color.getRed();
g = color.getGreen();
b = color.getBlue();
o = color.getOpacity();
for (Polygon p : polygons)
p.setColor(color);
return this;
}
public void setMeshColor(javafx.scene.paint.Color color) {
if (getCurrentMeshView() != null) {
PhongMaterial m = new PhongMaterial(color);
getCurrentMeshView().setMaterial(m);
}
}
/**
* Sets the Temporary color.
*
* @param color the new Temporary color
*/
public CSG setTemporaryColor(Color color) {
if (getCurrentMeshView() != null) {
PhongMaterial m = new PhongMaterial(color);
getCurrentMeshView().setMaterial(m);
}
return this;
}
/**
* Sets the manipulator.
*
* @param manipulator the manipulator
* @return the affine
*/
public CSG setManipulator(javafx.scene.transform.Affine m) {
if (manipulator == null)
return this;
manipulator.put(getUniqueId(), m);
if (getCurrentMeshView() != null) {
getCurrentMeshView().getTransforms().clear();
getCurrentMeshView().getTransforms().add(m);
}
return this;
}
/**
* Gets the mesh.
*
* @return the mesh
*/
public MeshView getMesh() {
if (getCurrentMeshView() != null)
return getCurrentMeshView();
setCurrentMeshView(newMesh());
return getCurrentMeshView();
}
/**
* Gets the mesh.
*
* @return the mesh
*/
public MeshView newMesh() {
MeshContainer meshContainer = toJavaFXMesh(null);
MeshView current = meshContainer.getAsMeshViews().get(0);
PhongMaterial m = new PhongMaterial(getColor());
current.setMaterial(m);
boolean hasManipulator = hasManipulator();
boolean hasAssembly = getAssemblyStorage().getValue("AssembleAffine") != Optional.empty();
if (hasManipulator || hasAssembly)
current.getTransforms().clear();
if (hasManipulator)
try {
current.getTransforms().add(getManipulator());
} catch (MissingManipulatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (hasAssembly)
current.getTransforms().add((Affine) getAssemblyStorage().getValue("AssembleAffine").get());
current.setCullFace(CullFace.NONE);
if (isWireFrame())
current.setDrawMode(DrawMode.LINE);
else
current.setDrawMode(DrawMode.FILL);
return current;
}
/**
* To z min.
*
* @param target the target
* @return the csg
*/
public CSG toZMin(CSG target) {
return this.transformed(new Transform().translateZ(-target.getBounds().getMin().z));
}
/**
* To z max.
*
* @param target the target
* @return the csg
*/
public CSG toZMax(CSG target) {
return this.transformed(new Transform().translateZ(-target.getBounds().getMax().z));
}
/**
* To x min.
*
* @param target the target
* @return the csg
*/
public CSG toXMin(CSG target) {
return this.transformed(new Transform().translateX(-target.getBounds().getMin().x));
}
/**
* To x max.
*
* @param target the target
* @return the csg
*/
public CSG toXMax(CSG target) {
return this.transformed(new Transform().translateX(-target.getBounds().getMax().x));
}
/**
* To y min.
*
* @param target the target
* @return the csg
*/
public CSG toYMin(CSG target) {
return this.transformed(new Transform().translateY(-target.getBounds().getMin().y));
}
/**
* To y max.
*
* @param target the target
* @return the csg
*/
public CSG toYMax(CSG target) {
return this.transformed(new Transform().translateY(-target.getBounds().getMax().y));
}
/**
* To z min.
*
* @return the csg
*/
public CSG toZMin() {
return toZMin(this);
}
/**
* To z max.
*
* @return the csg
*/
public CSG toZMax() {
return toZMax(this);
}
/**
* To x min.
*
* @return the csg
*/
public CSG toXMin() {
return toXMin(this);
}
/**
* To x max.
*
* @return the csg
*/
public CSG toXMax() {
return toXMax(this);
}
/**
* To y min.
*
* @return the csg
*/
public CSG toYMin() {
return toYMin(this);
}
/**
* To y max.
*
* @return the csg
*/
public CSG toYMax() {
return toYMax(this);
}
public CSG move(Number x, Number y, Number z) {
return transformed(new Transform().translate(x.doubleValue(), y.doubleValue(), z.doubleValue()));
}
public CSG move(Vertex v) {
return transformed(new Transform().translate(v.getX(), v.getY(), v.getZ()));
}
public CSG move(Vector3d v) {
return transformed(new Transform().translate(v.x, v.y, v.z));
}
public CSG move(Number[] posVector) {
return move(posVector[0], posVector[1], posVector[2]);
}
/**
* Movey.
*
* @param howFarToMove the how far to move
* @return the csg
*/
// Helper/wrapper functions for movement
public CSG movey(Number howFarToMove) {
return this.transformed(Transform.unity().translateY(howFarToMove.doubleValue()));
}
/**
* Movez.
*
* @param howFarToMove the how far to move
* @return the csg
*/
public CSG movez(Number howFarToMove) {
return this.transformed(Transform.unity().translateZ(howFarToMove.doubleValue()));
}
/**
* Movex.
*
* @param howFarToMove the how far to move
* @return the csg
*/
public CSG movex(Number howFarToMove) {
return this.transformed(Transform.unity().translateX(howFarToMove.doubleValue()));
}
/**
* Helper function moving CSG to center X moveToCenterX.
*
* @return the csg
*/
public CSG moveToCenterX() {
return this.movex(-this.getCenterX());
}
/**
* Helper function moving CSG to center Y moveToCenterY.
*
* @return the csg
*/
public CSG moveToCenterY() {
return this.movey(-this.getCenterY());
}
/**
* Helper function moving CSG to center Z moveToCenterZ.
*
* @return the csg
*/
public CSG moveToCenterZ() {
return this.movez(-this.getCenterZ());
}
/**
* Helper function moving CSG to center X, Y, Z moveToCenter. Moves in x, y, z
*
* @return the csg
*/
public CSG moveToCenter() {
return this.movex(-this.getCenterX()).movey(-this.getCenterY()).movez(-this.getCenterZ());
}
public ArrayList<CSG> move(ArrayList<Transform> p) {
ArrayList<CSG> bits = new ArrayList<CSG>();
for (int i = 0; i < p.size(); i++) {
bits.add(this.clone());
}
return move(bits, p);
}
public static ArrayList<CSG> move(ArrayList<CSG> slice, ArrayList<Transform> p) {
ArrayList<CSG> s = new ArrayList<CSG>();
// s.add(slice.get(0));
for (int i = 0; i < slice.size() && i < p.size(); i++) {
s.add(slice.get(i).transformed(p.get(i)));
}
return s;
}
/**
* mirror about y axis.
*
*
* @return the csg
*/
// Helper/wrapper functions for movement
public CSG mirrory() {
return this.scaley(-1);
}
/**
* mirror about z axis.
*
* @return the csg
*/
public CSG mirrorz() {
return this.scalez(-1);
}
/**
* mirror about x axis.
*
* @return the csg
*/
public CSG mirrorx() {
return this.scalex(-1);
}
public CSG rot(Number x, Number y, Number z) {
return rotx(x.doubleValue()).roty(y.doubleValue()).rotz(z.doubleValue());
}
public CSG rot(Number[] posVector) {
return rot(posVector[0], posVector[1], posVector[2]);
}
/**
* Rotz.
*
* @param degreesToRotate the degrees to rotate
* @return the csg
*/
// Rotation function, rotates the object
public CSG rotz(Number degreesToRotate) {
return this.transformed(new Transform().rotZ(degreesToRotate.doubleValue()));
}
/**
* Roty.
*
* @param degreesToRotate the degrees to rotate
* @return the csg
*/
public CSG roty(Number degreesToRotate) {
return this.transformed(new Transform().rotY(degreesToRotate.doubleValue()));
}
/**
* Rotx.
*
* @param degreesToRotate the degrees to rotate
* @return the csg
*/
public CSG rotx(Number degreesToRotate) {
return this.transformed(new Transform().rotX(degreesToRotate.doubleValue()));
}
/**
* Scalez.
*
* @param scaleValue the scale value
* @return the csg
*/
// Scale function, scales the object
public CSG scalez(Number scaleValue) {
return this.transformed(new Transform().scaleZ(scaleValue.doubleValue()));
}
/**
* Scaley.
*
* @param scaleValue the scale value
* @return the csg
*/
public CSG scaley(Number scaleValue) {
return this.transformed(new Transform().scaleY(scaleValue.doubleValue()));
}
/**
* Scalex.
*
* @param scaleValue the scale value
* @return the csg
*/
public CSG scalex(Number scaleValue) {
return this.transformed(new Transform().scaleX(scaleValue.doubleValue()));
}
// Scale function, scales the object
public CSG scaleToMeasurmentZ(Number measurment) {
Number scaleValue = measurment.doubleValue() / getTotalZ();
return this.transformed(new Transform().scaleZ(scaleValue.doubleValue()));
}
/**
* Scaley.
*
* @param measurment the scale value
* @return the csg
*/
public CSG scaleToMeasurmentY(Number measurment) {
Number scaleValue = measurment.doubleValue() / getTotalY();
return this.transformed(new Transform().scaleY(scaleValue.doubleValue()));
}
/**
* Scalex.
*
* @param measurment the scale value
* @return the csg
*/
public CSG scaleToMeasurmentX(Number measurment) {
Number scaleValue = measurment.doubleValue() / getTotalX();
return this.transformed(new Transform().scaleX(scaleValue.doubleValue()));
}
/**
* Scale.
*
* @param scaleValue the scale value
* @return the csg
*/
public CSG scale(Number scaleValue) {
return this.transformed(new Transform().scale(scaleValue.doubleValue()));
}
/**
* Constructs a CSG from a list of {@link Polygon} instances.
*
* @param polygons polygons
* @return a CSG instance
*/
public static CSG fromPolygons(ArrayList<Polygon> polygons) {
CSG csg = new CSG();
csg.setPolygons(polygons);
return csg;
}
/**
* Constructs a CSG from the specified {@link Polygon} instances.
*
* @param polygons polygons
* @return a CSG instance
*/
public static CSG fromPolygons(Polygon... polygons) {
return fromPolygons(new ArrayList<>(Arrays.asList(polygons)));
}
/**
* Constructs a CSG from a list of {@link Polygon} instances.
*
* @param storage shared storage
* @param polygons polygons
* @return a CSG instance
*/
public static CSG fromPolygons(PropertyStorage storage, ArrayList<Polygon> polygons) {
CSG csg = new CSG();
csg.setPolygons(polygons);
csg.setStorage(storage);
for (Polygon polygon : polygons) {
polygon.setStorage(storage);
}
return csg;
}
/**
* Constructs a CSG from the specified {@link Polygon} instances.
*
* @param storage shared storage
* @param polygons polygons
* @return a CSG instance
*/
public static CSG fromPolygons(PropertyStorage storage, Polygon... polygons) {
return fromPolygons(storage, new ArrayList<>(Arrays.asList(polygons)));
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#clone()
*/
@Override
public CSG clone() {
CSG csg = cloneShallow();
CSG historySync = csg.historySync(this);
return historySync;
}
public CSG cloneShallow() {
ArrayList<Polygon> collect = new ArrayList<Polygon>();
for (Polygon p : polygons) {
if (p == null)
continue;
try {
Polygon my = p.clone();
collect.add(my);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return CSG.fromPolygons(collect);
}
/**
* Gets the polygons.
*
* @return the polygons of this CSG
*/
public ArrayList<Polygon> getPolygons() {
return polygons;
}
/**
* Defines the CSg optimization type.
*
* @param type optimization type
* @return this CSG
*/
public CSG optimization(OptType type) {
this.setOptType(type);
return this;
}
/**
* Return a new CSG solid representing the union of this csg and the specified
* csg.
* <p>
* <b>Note:</b> Neither this csg nor the specified csg are weighted.
* <p>
* <blockquote>
*
* <pre>
* A.union(B)
*
* +-------+ +-------+
* | | | |
* | A | | |
* | +--+----+ = | +----+
* +----+--+ | +----+ |
* | B | | |
* | | | |
* +-------+ +-------+
* </pre>
*
* </blockquote>
*
* @param csg other csg
*
* @return union of this csg and the specified csg
*/
public CSG union(CSG csg) {
if (this.polygons.size() > getMinPolygonsForOffloading() || csg.polygons.size() > getMinPolygonsForOffloading())
if (CSGClient.isRunning()) {
ArrayList<CSG> go = new ArrayList<CSG>(Arrays.asList(this, csg));
try {
return CSGClient.getClient().union(go).get(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// triangulate();
// csg.triangulate();
switch (getOptType()) {
case CSG_BOUND:
return _unionCSGBoundsOpt(csg).historySync(this).historySync(csg);
case POLYGON_BOUND:
return _unionPolygonBoundsOpt(csg).historySync(this).historySync(csg);
default:
// return _unionIntersectOpt(csg);
return _unionNoOpt(csg).historySync(this).historySync(csg);
}
}
/**
* Returns a csg consisting of the polygons of this csg and the specified csg.
* <p>
* The purpose of this method is to allow fast union operations for objects that
* do not intersect.
* <p>
* <b>WARNING:</b> this method does not apply the csg algorithms. Therefore,
* please ensure that this csg and the specified csg do not intersect.
*
* @param csg csg
*
* @return a csg consisting of the polygons of this csg and the specified csg
*/
public CSG dumbUnion(CSG csg) {
// boolean tri = triangulated && csg.triangulated;
CSG result = this.clone();
CSG other = csg.clone();
result.getPolygons().addAll(other.getPolygons());
bounds = null;
// result.triangulated = tri;
return result.historySync(other);
}
/**
* Return a new CSG solid representing the union of this csg and the specified
* csgs.
* <p>
* <b>Note:</b> Neither this csg nor the specified csg are weighted.
* <p>
* <blockquote>
*
* <pre>
* A.union(B)
*
* +-------+ +-------+
* | | | |
* | A | | |
* | +--+----+ = | +----+
* +----+--+ | +----+ |
* | B | | |
* | | | |
* +-------+ +-------+
* </pre>
*
* </blockquote>
*
* @param csgs other csgs
*
* @return union of this csg and the specified csgs
*/
public CSG union(List<CSG> incoming) {
if (CSGClient.isRunning()) {
ArrayList<CSG> go = new ArrayList<CSG>();
go.add(this);
go.addAll(incoming);
try {
return CSGClient.getClient().union(go).get(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
CSG solid = this.isHole() ? null : this;
CSG hole = this.isHole() ? this : null;
ArrayList<CSG> csgs = new ArrayList<CSG>();
CSG dumb = null;
if (incoming.size() < 10) {
csgs.addAll(incoming);
} else {
for (int i = 0; i < incoming.size(); i++) {
CSG test = incoming.get(i);
if (test == null)
continue;
boolean touching = false;
// int t=-1;
for (int j = 0; j < incoming.size(); j++) {
if (i == j)
continue;
if (test.isBoundsTouching(incoming.get(j))) {
touching = true;
// t=j;
break;
}
}
if (touching) {
csgs.add(test);
} else {
if (dumb == null) {
dumb = test;
} else
dumb = dumb.dumbUnion(test);
}
}
}
for (int i = 0; i < csgs.size(); i++) {
CSG csg = csgs.get(i);
if (!csg.isHole()) {
if (solid != null)
solid = solid.union(csg);
else
solid = csg;
if (Thread.interrupted())
break;
getProgressMoniter().progressUpdate(i, csgs.size(), "Union solid", solid);
} else {
if (hole != null)
hole = hole.union(csg);
else
hole = csg;
hole.setIsHole(true);
if (Thread.interrupted())
break;
getProgressMoniter().progressUpdate(i, csgs.size(), "Union hole", hole);
}
}
CSG result = null;
if (solid != null && hole == null)
result = solid;
else if (solid == null && hole != null)
result = hole;
else
result = solid.difference(hole);