You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by ma...@apache.org on 2020/06/06 11:26:31 UTC
[commons-geometry] branch master updated: GEOMETRY-95: improving
implementation of Sphere.toTree();
removing HyperplaneSubset.Builder interface to improve performance and
numerical robustness
This is an automated email from the ASF dual-hosted git repository.
mattjuntunen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-geometry.git
The following commit(s) were added to refs/heads/master by this push:
new 843d6a9 GEOMETRY-95: improving implementation of Sphere.toTree(); removing HyperplaneSubset.Builder interface to improve performance and numerical robustness
843d6a9 is described below
commit 843d6a91abe72b7e8372c286a1e202622f7bc52f
Author: Matt Juntunen <ma...@apache.org>
AuthorDate: Sun May 31 11:44:09 2020 -0400
GEOMETRY-95: improving implementation of Sphere.toTree(); removing HyperplaneSubset.Builder interface to improve performance and numerical robustness
---
.../AbstractConvexHyperplaneBoundedRegion.java | 25 +-
.../core/partitioning/HyperplaneSubset.java | 29 --
.../partitioning/bsp/AbstractRegionBSPTree.java | 61 ++--
.../core/partitioning/bsp/RegionCutBoundary.java | 155 ++++++---
.../AbstractConvexHyperplaneBoundedRegionTest.java | 108 ++++++-
.../bsp/AbstractRegionBSPTreeTest.java | 26 +-
.../partitioning/bsp/RegionCutBoundaryTest.java | 75 ++++-
.../core/partitioning/test/TestLineSegment.java | 9 +-
.../test/TestLineSegmentCollection.java | 6 -
.../test/TestLineSegmentCollectionBuilder.java | 99 ------
.../geometry/euclidean/oned/OrientedPoint.java | 69 ----
.../euclidean/threed/AbstractPlaneSubset.java | 109 -------
.../commons/geometry/euclidean/threed/Planes.java | 1 -
.../geometry/euclidean/threed/RegionBSPTree3D.java | 15 +-
.../geometry/euclidean/threed/shape/Sphere.java | 352 ++++++++++-----------
.../geometry/euclidean/twod/ConvexArea.java | 4 +-
.../geometry/euclidean/twod/LineSubset.java | 119 +------
.../geometry/euclidean/twod/RegionBSPTree2D.java | 8 +-
.../geometry/euclidean/EuclideanTestUtils.java | 9 +-
.../geometry/euclidean/oned/OrientedPointTest.java | 62 ----
.../euclidean/threed/AbstractPlaneSubsetTest.java | 331 -------------------
.../euclidean/threed/shape/SphereTest.java | 132 ++++++--
.../geometry/euclidean/twod/ConvexAreaTest.java | 69 ++++
.../geometry/euclidean/twod/LineSubsetTest.java | 291 -----------------
.../euclidean/twod/RegionBSPTree2DTest.java | 32 +-
.../jmh/euclidean/RegionBSPTree3DPerformance.java | 8 +-
.../examples/jmh/euclidean/SpherePerformance.java | 28 +-
.../commons/geometry/spherical/oned/CutAngle.java | 69 ----
.../geometry/spherical/twod/GreatCircleSubset.java | 107 -------
.../geometry/spherical/oned/CutAngleTest.java | 62 ----
.../spherical/twod/GreatCircleSubsetTest.java | 289 -----------------
31 files changed, 751 insertions(+), 2008 deletions(-)
diff --git a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegion.java b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegion.java
index 5ff18d8..93ab44d 100644
--- a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegion.java
+++ b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegion.java
@@ -242,14 +242,35 @@ public abstract class AbstractConvexHyperplaneBoundedRegion<P extends Point<P>,
new Split<>(null, thisInstance);
}
- final List<S> minusBoundaries = new ArrayList<>();
- final List<S> plusBoundaries = new ArrayList<>();
+ // the splitter passes through the region; split the other region boundaries
+ // by the splitter
+ final ArrayList<S> minusBoundaries = new ArrayList<>();
+ final ArrayList<S> plusBoundaries = new ArrayList<>();
splitBoundaries(splitter, boundaryType, minusBoundaries, plusBoundaries);
+ // if the splitter was trimmed by the region boundaries, double-check that the split boundaries
+ // actually lie on both sides of the splitter; this is another case where floating point errors
+ // can cause a discrepancy between the results of splitting the splitter by the boundaries and
+ // splitting the boundaries by the splitter
+ if (!trimmedSplitter.isFull()) {
+ if (minusBoundaries.isEmpty()) {
+ if (plusBoundaries.isEmpty()) {
+ return new Split<>(null, null);
+ }
+ return new Split<>(null, thisInstance);
+ } else if (plusBoundaries.isEmpty()) {
+ return new Split<>(thisInstance, null);
+ }
+ }
+
+ // we have a consistent region split; create the new plus and minus regions
minusBoundaries.add(boundaryType.cast(trimmedSplitter));
plusBoundaries.add(boundaryType.cast(trimmedSplitter.reverse()));
+ minusBoundaries.trimToSize();
+ plusBoundaries.trimToSize();
+
return new Split<>(factory.apply(minusBoundaries), factory.apply(plusBoundaries));
}
}
diff --git a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/HyperplaneSubset.java b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/HyperplaneSubset.java
index 43ac97f..dd2b031 100644
--- a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/HyperplaneSubset.java
+++ b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/HyperplaneSubset.java
@@ -114,12 +114,6 @@ public interface HyperplaneSubset<P extends Point<P>> extends Splittable<P, Hype
*/
P closest(P pt);
- /** Return a {@link Builder} instance for joining multiple
- * hyperplane subsets together.
- * @return a new builder instance
- */
- Builder<P> builder();
-
/** Return a new hyperplane subset resulting from the application of the given transform.
* The current instance is not modified.
* @param transform the transform instance to apply
@@ -134,27 +128,4 @@ public interface HyperplaneSubset<P extends Point<P>> extends Splittable<P, Hype
* region as this instance
*/
List<? extends HyperplaneConvexSubset<P>> toConvex();
-
- /** Interface for joining multiple {@link HyperplaneSubset}s into a single
- * instance.
- * @param <P> Point implementation type
- */
- interface Builder<P extends Point<P>> {
-
- /** Add a {@link HyperplaneSubset} instance to the builder.
- * @param sub subset to add to this instance
- */
- void add(HyperplaneSubset<P> sub);
-
- /** Add a {@link HyperplaneConvexSubset} instance to the builder.
- * @param sub convex subset to add to this instance
- */
- void add(HyperplaneConvexSubset<P> sub);
-
- /** Get a {@link HyperplaneSubset} representing the union
- * of all input subsets.
- * @return subset representing the union of all input subsets
- */
- HyperplaneSubset<P> build();
- }
}
diff --git a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTree.java b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTree.java
index 84c1552..05e0dbe 100644
--- a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTree.java
+++ b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTree.java
@@ -26,13 +26,13 @@ import org.apache.commons.geometry.core.Point;
import org.apache.commons.geometry.core.RegionLocation;
import org.apache.commons.geometry.core.internal.IteratorTransform;
import org.apache.commons.geometry.core.partitioning.BoundarySource;
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.Hyperplane;
import org.apache.commons.geometry.core.partitioning.HyperplaneBoundedRegion;
+import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneLocation;
+import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.partitioning.SplitLocation;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.bsp.BSPTreeVisitor.ClosestFirstVisitor;
/** Abstract {@link BSPTree} specialized for representing regions of space. For example,
@@ -135,8 +135,7 @@ public abstract class AbstractRegionBSPTree<
for (final AbstractRegionNode<P, N> node : nodes()) {
boundary = node.getCutBoundary();
if (boundary != null) {
- sum += boundary.getInsideFacing().getSize();
- sum += boundary.getOutsideFacing().getSize();
+ sum += boundary.getSize();
}
}
@@ -699,25 +698,21 @@ public abstract class AbstractRegionBSPTree<
private RegionCutBoundary<P> computeBoundary() {
HyperplaneConvexSubset<P> sub = getCut();
- // find the portions of the node cut sub-hyperplane that touch inside and
+ // find the portions of the node cut hyperplane subset that touch inside and
// outside cells in the minus sub-tree
- HyperplaneSubset.Builder<P> minusInBuilder = sub.builder();
- HyperplaneSubset.Builder<P> minusOutBuilder = sub.builder();
-
- characterizeHyperplaneSubset(sub, getMinus(), minusInBuilder, minusOutBuilder);
+ final List<HyperplaneConvexSubset<P>> minusIn = new ArrayList<>();
+ final List<HyperplaneConvexSubset<P>> minusOut = new ArrayList<>();
- List<? extends HyperplaneConvexSubset<P>> minusIn = minusInBuilder.build().toConvex();
- List<? extends HyperplaneConvexSubset<P>> minusOut = minusOutBuilder.build().toConvex();
+ characterizeHyperplaneSubset(sub, getMinus(), minusIn, minusOut);
- // create the result boundary builders
- HyperplaneSubset.Builder<P> insideFacing = sub.builder();
- HyperplaneSubset.Builder<P> outsideFacing = sub.builder();
+ final ArrayList<HyperplaneConvexSubset<P>> insideFacing = new ArrayList<>();
+ final ArrayList<HyperplaneConvexSubset<P>> outsideFacing = new ArrayList<>();
if (!minusIn.isEmpty()) {
// Add to the boundary anything that touches an inside cell in the minus sub-tree
// and an outside cell in the plus sub-tree. These portions are oriented with their
// plus side pointing to the outside of the region.
- for (HyperplaneConvexSubset<P> minusInFragment : minusIn) {
+ for (final HyperplaneConvexSubset<P> minusInFragment : minusIn) {
characterizeHyperplaneSubset(minusInFragment, getPlus(), null, outsideFacing);
}
}
@@ -726,26 +721,31 @@ public abstract class AbstractRegionBSPTree<
// Add to the boundary anything that touches an outside cell in the minus sub-tree
// and an inside cell in the plus sub-tree. These portions are oriented with their
// plus side pointing to the inside of the region.
- for (HyperplaneConvexSubset<P> minusOutFragment : minusOut) {
+ for (final HyperplaneConvexSubset<P> minusOutFragment : minusOut) {
characterizeHyperplaneSubset(minusOutFragment, getPlus(), insideFacing, null);
}
}
- return new RegionCutBoundary<>(insideFacing.build(), outsideFacing.build());
+ insideFacing.trimToSize();
+ outsideFacing.trimToSize();
+
+ return new RegionCutBoundary<>(
+ insideFacing.isEmpty() ? null : insideFacing,
+ outsideFacing.isEmpty() ? null : outsideFacing);
}
/** Recursive method to characterize a hyperplane convex subset with respect to the region's
* boundaries.
* @param sub the hyperplane convex subset to characterize
* @param node the node to characterize the hyperplane convex subset against
- * @param in the builder that will receive the portions of the subset that lie in the inside
+ * @param in list that will receive the portions of the subset that lie in the inside
* of the region; may be null
- * @param out the builder that will receive the portions of the subset that lie on the outside
+ * @param out list that will receive the portions of the subset that lie on the outside
* of the region; may be null
*/
private void characterizeHyperplaneSubset(final HyperplaneConvexSubset<P> sub,
- final AbstractRegionNode<P, N> node, final HyperplaneSubset.Builder<P> in,
- final HyperplaneSubset.Builder<P> out) {
+ final AbstractRegionNode<P, N> node, final List<HyperplaneConvexSubset<P>> in,
+ final List<HyperplaneConvexSubset<P>> out) {
if (sub != null) {
if (node.isLeaf()) {
@@ -1123,21 +1123,14 @@ public abstract class AbstractRegionBSPTree<
if (input.isInternal()) {
final RegionCutBoundary<P> cutBoundary = input.getCutBoundary();
- final HyperplaneSubset<P> outsideFacing = cutBoundary.getOutsideFacing();
- final HyperplaneSubset<P> insideFacing = cutBoundary.getInsideFacing();
-
- if (outsideFacing != null && !outsideFacing.isEmpty()) {
- for (HyperplaneConvexSubset<P> boundary : outsideFacing.toConvex()) {
-
- addOutput(typeConverter.apply(boundary));
- }
+ for (final HyperplaneConvexSubset<P> boundary : cutBoundary.getOutsideFacing()) {
+ addOutput(typeConverter.apply(boundary));
}
- if (insideFacing != null && !insideFacing.isEmpty()) {
- for (HyperplaneConvexSubset<P> boundary : insideFacing.toConvex()) {
- HyperplaneConvexSubset<P> reversed = boundary.reverse();
- addOutput(typeConverter.apply(reversed));
- }
+ for (final HyperplaneConvexSubset<P> boundary : cutBoundary.getInsideFacing()) {
+ HyperplaneConvexSubset<P> reversed = boundary.reverse();
+
+ addOutput(typeConverter.apply(reversed));
}
}
}
diff --git a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundary.java b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundary.java
index 2a7fb84..e60dc98 100644
--- a/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundary.java
+++ b/commons-geometry-core/src/main/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundary.java
@@ -16,44 +16,55 @@
*/
package org.apache.commons.geometry.core.partitioning.bsp;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
import org.apache.commons.geometry.core.Point;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
+import org.apache.commons.geometry.core.Sized;
+import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
/** Class representing the portion of an
* {@link AbstractRegionBSPTree.AbstractRegionNode AbstractRegionNode}'s cut that
- * lies on the boundary of the region. Portions of this hyperplane subset
- * may be oriented so that the plus side of the hyperplane subset points toward
- * the outside of the region ({@link #getOutsideFacing()}) and other portions
- * of the same hyperplane subset may be oriented so that the plus side points
- * toward the inside of the region ({@link #getInsideFacing()}).
+ * lies on the boundary of the region. Portions of the node cut may be oriented so
+ * that the plus side of the cut points toward the outside of the region
+ * ({@link #getOutsideFacing()}) and other portions toward the inside of the
+ * region ({@link #getInsideFacing()}). The inside-facing and outside-facing portions
+ * of the region boundary are represented as lists of disjoint hyperplane convex subsets,
+ * all originating from the same hyperplane convex subset forming the node cut.
*
* @param <P> Point implementation type
*/
-public final class RegionCutBoundary<P extends Point<P>> {
- /** Portion of the cut with its plus side facing the inside of the region.
- */
- private final HyperplaneSubset<P> insideFacing;
+public final class RegionCutBoundary<P extends Point<P>> implements Sized {
- /** Portion of the cut with its plus side facing the outside of the region.
- */
- private final HyperplaneSubset<P> outsideFacing;
+ /** Portion of the cut oriented such that the plus side of the cut points to the inside of the region. */
+ private final List<HyperplaneConvexSubset<P>> insideFacing;
- /** Simple constructor.
- * @param insideFacing portion of the cut with its plus side facing the
- * inside of the region
- * @param outsideFacing portion of the cut with its plus side facing the
- * outside of the region
+ /** Portion of the cut oriented such that the plus side of the cut points to the outside of the region. */
+ private final List<HyperplaneConvexSubset<P>> outsideFacing;
+
+ /** Construct a new instance from the inside-facing and outside-facing portions of a node cut. The
+ * given lists are expected to be disjoint regions originating from the same hyperplane convex subset.
+ * No validation is performed.
+ * @param insideFacing the inside-facing portion of the node cut
+ * @param outsideFacing the outside-facing portion of the node cut
*/
- public RegionCutBoundary(final HyperplaneSubset<P> insideFacing, final HyperplaneSubset<P> outsideFacing) {
- this.insideFacing = insideFacing;
- this.outsideFacing = outsideFacing;
+ RegionCutBoundary(final List<HyperplaneConvexSubset<P>> insideFacing,
+ final List<HyperplaneConvexSubset<P>> outsideFacing) {
+ this.insideFacing = insideFacing != null ?
+ Collections.unmodifiableList(insideFacing) :
+ Collections.emptyList();
+
+ this.outsideFacing = outsideFacing != null ?
+ Collections.unmodifiableList(outsideFacing) :
+ Collections.emptyList();
}
/** Get the portion of the cut with its plus side facing the inside of the region.
* @return the portion of the cut with its plus side facing the
* inside of the region
*/
- public HyperplaneSubset<P> getInsideFacing() {
+ public List<HyperplaneConvexSubset<P>> getInsideFacing() {
return insideFacing;
}
@@ -61,39 +72,111 @@ public final class RegionCutBoundary<P extends Point<P>> {
* @return the portion of the cut with its plus side facing the
* outside of the region
*/
- public HyperplaneSubset<P> getOutsideFacing() {
+ public List<HyperplaneConvexSubset<P>> getOutsideFacing() {
return outsideFacing;
}
+ /** Get the total size of the cut boundary, including inside and outside facing components.
+ * @return the total size of the cut boundary, including inside and outside facing components
+ */
+ @Override
+ public double getSize() {
+ return getTotalSize(insideFacing) + getTotalSize(outsideFacing);
+ }
+
+ /** Get the total size of all boundaries in the given list.
+ * @param boundaries boundaries to compute the size for
+ * @return the total size of all boundaries in the given list
+ */
+ private double getTotalSize(final List<HyperplaneConvexSubset<P>> boundaries) {
+ double total = 0.0;
+ for (final HyperplaneConvexSubset<P> boundary : boundaries) {
+ total += boundary.getSize();
+
+ if (Double.isInfinite(total)) {
+ return total;
+ }
+ }
+
+ return total;
+ }
+
/** Return the closest point to the argument in the inside and outside facing
* portions of the cut boundary.
* @param pt the reference point
* @return the point in the cut boundary closest to the reference point
- * @see HyperplaneSubset#closest(Point)
+ * @see HyperplaneConvexSubset#closest(Point)
*/
public P closest(final P pt) {
- final P insideFacingPt = (insideFacing != null) ? insideFacing.closest(pt) : null;
- final P outsideFacingPt = (outsideFacing != null) ? outsideFacing.closest(pt) : null;
+ P closest = null;
+ double closestDist = Double.POSITIVE_INFINITY;
+
+ final Iterator<HyperplaneConvexSubset<P>> insideIt = insideFacing.iterator();
+ final Iterator<HyperplaneConvexSubset<P>> outsideIt = outsideFacing.iterator();
+
+ HyperplaneConvexSubset<P> boundary;
+ P testPt;
+ double dist;
- if (insideFacingPt != null && outsideFacingPt != null) {
- if (pt.distance(insideFacingPt) < pt.distance(outsideFacingPt)) {
- return insideFacingPt;
+ while (insideIt.hasNext() || outsideIt.hasNext()) {
+ boundary = insideIt.hasNext() ?
+ insideIt.next() :
+ outsideIt.next();
+
+ testPt = boundary.closest(pt);
+ dist = pt.distance(testPt);
+
+ if (closest == null || dist < closestDist) {
+ closest = testPt;
+ closestDist = dist;
}
- return outsideFacingPt;
- } else if (insideFacingPt != null) {
- return insideFacingPt;
}
- return outsideFacingPt;
+
+ return closest;
}
/** Return true if the given point is contained in the boundary, in either the
* inside facing portion or the outside facing portion.
* @param pt point to test
* @return true if the point is contained in the boundary
- * @see HyperplaneSubset#contains(Point)
+ * @see HyperplaneConvexSubset#contains(Point)
*/
public boolean contains(final P pt) {
- return (insideFacing != null && insideFacing.contains(pt)) ||
- (outsideFacing != null && outsideFacing.contains(pt));
+ return containsInsideFacing(pt) || containsOutsideFacing(pt);
+ }
+
+ /** Return true if the given point is contained in the inside-facing portion of
+ * the region boundary.
+ * @param pt point to test
+ * @return true if the point is contained in the inside-facing portion of the region
+ * boundary
+ */
+ public boolean containsInsideFacing(final P pt) {
+ return anyContains(pt, insideFacing);
+ }
+
+ /** Return true if the given point is contained in the outside-facing portion of the
+ * region boundary.
+ * @param pt point to test
+ * @return true if the point is contained in the outside-facing portion of the region
+ * boundary
+ */
+ public boolean containsOutsideFacing(final P pt) {
+ return anyContains(pt, outsideFacing);
+ }
+
+ /** Return true if the point is contained in any of the given boundaries.
+ * @param pt point to test
+ * @param boundaries
+ * @return true if the point is contained in any of the given boundaries
+ */
+ private boolean anyContains(final P pt, final List<HyperplaneConvexSubset<P>> boundaries) {
+ for (final HyperplaneConvexSubset<P> boundary : boundaries) {
+ if (boundary.contains(pt)) {
+ return true;
+ }
+ }
+
+ return false;
}
}
diff --git a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegionTest.java b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegionTest.java
index 3b67d04..73dff18 100644
--- a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegionTest.java
+++ b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/AbstractConvexHyperplaneBoundedRegionTest.java
@@ -187,7 +187,7 @@ public class AbstractConvexHyperplaneBoundedRegionTest {
}
@Test
- public void testSplit_parallel_plusOnly() {
+ public void testSplit_parallel_splitterIsOutside_plusOnly() {
// arrange
StubRegion region = new StubRegion(
Arrays.asList(new TestLineSegment(new TestPoint2D(0, 1), new TestPoint2D(1, 1))));
@@ -205,7 +205,7 @@ public class AbstractConvexHyperplaneBoundedRegionTest {
}
@Test
- public void testSplit_parallel_minusOnly() {
+ public void testSplit_parallel_splitterIsOutside_minusOnly() {
// arrange
StubRegion region = new StubRegion(
Arrays.asList(new TestLineSegment(new TestPoint2D(0, 1), new TestPoint2D(1, 1))));
@@ -223,6 +223,35 @@ public class AbstractConvexHyperplaneBoundedRegionTest {
}
@Test
+ public void testSplit_parallel_splitterIsInside() {
+ // arrange
+ StubRegion region = new StubRegion(
+ Arrays.asList(new TestLineSegment(new TestPoint2D(1, 1), new TestPoint2D(0, 1))));
+
+ TestLine splitter = TestLine.X_AXIS;
+
+ // act
+ Split<StubRegion> split = region.split(splitter);
+
+ // assert
+ Assert.assertEquals(SplitLocation.BOTH, split.getLocation());
+
+ TestPoint2D p1 = new TestPoint2D(0, 1.5);
+ TestPoint2D p2 = new TestPoint2D(0, 0.5);
+ TestPoint2D p3 = new TestPoint2D(0, -0.5);
+
+ StubRegion minus = split.getMinus();
+ Assert.assertEquals(2, minus.getBoundaries().size());
+ checkClassify(minus, RegionLocation.INSIDE, p2);
+ checkClassify(minus, RegionLocation.OUTSIDE, p1, p3);
+
+ StubRegion plus = split.getPlus();
+ Assert.assertEquals(1, plus.getBoundaries().size());
+ checkClassify(plus, RegionLocation.INSIDE, p3);
+ checkClassify(plus, RegionLocation.OUTSIDE, p1, p2);
+ }
+
+ @Test
public void testSplit_coincident_sameOrientation() {
// arrange
StubRegion region = new StubRegion(Arrays.asList(TestLine.X_AXIS.span()));
@@ -350,6 +379,81 @@ public class AbstractConvexHyperplaneBoundedRegionTest {
}
@Test
+ public void testSplit_inconsistentBoundarySplitLocations_trimmedNotNull_minus() {
+ // arrange
+ TestLine a = new TestLine(new TestPoint2D(1e-8, 0), new TestPoint2D(1, 1));
+ TestLine b = new TestLine(new TestPoint2D(-1, 1), new TestPoint2D(-1e-8, 0));
+
+ StubRegion region = new StubRegion(Arrays.asList(
+ new TestLineSegment(1e-8, Double.POSITIVE_INFINITY, a),
+ new TestLineSegment(Double.NEGATIVE_INFINITY, -1e-8, b)
+ ));
+
+ List<TestLineSegment> segments = region.getBoundaries();
+ PartitionTestUtils.assertPointsEqual(segments.get(0).getStartPoint(), segments.get(1).getEndPoint());
+
+ TestLine splitter = new TestLine(new TestPoint2D(0, 0), new TestPoint2D(1, 0));
+
+ // act
+ Split<StubRegion> split = region.split(splitter);
+
+ // assert
+ Assert.assertEquals(SplitLocation.MINUS, split.getLocation());
+ Assert.assertSame(region, split.getMinus());
+ Assert.assertNull(split.getPlus());
+ }
+
+ @Test
+ public void testSplit_inconsistentBoundarySplitLocations_trimmedNotNull_plus() {
+ // arrange
+ TestLine a = new TestLine(new TestPoint2D(1e-8, 0), new TestPoint2D(1, 1));
+ TestLine b = new TestLine(new TestPoint2D(-1, 1), new TestPoint2D(-1e-8, 0));
+
+ StubRegion region = new StubRegion(Arrays.asList(
+ new TestLineSegment(1e-8, Double.POSITIVE_INFINITY, a),
+ new TestLineSegment(Double.NEGATIVE_INFINITY, -1e-8, b)
+ ));
+
+ List<TestLineSegment> segments = region.getBoundaries();
+ PartitionTestUtils.assertPointsEqual(segments.get(0).getStartPoint(), segments.get(1).getEndPoint());
+
+ TestLine splitter = new TestLine(new TestPoint2D(0, 0), new TestPoint2D(-1, 0));
+
+ // act
+ Split<StubRegion> split = region.split(splitter);
+
+ // assert
+ Assert.assertEquals(SplitLocation.PLUS, split.getLocation());
+ Assert.assertNull(split.getMinus());
+ Assert.assertSame(region, split.getPlus());
+ }
+
+ @Test
+ public void testSplit_inconsistentBoundarySplitLocations_trimmedNotNull_neither() {
+ // arrange
+ TestLine a = new TestLine(new TestPoint2D(1e-8, 0), new TestPoint2D(1, 1));
+ TestLine b = new TestLine(new TestPoint2D(-1, 1), new TestPoint2D(-1e-8, 0));
+
+ StubRegion region = new StubRegion(Arrays.asList(
+ new TestLineSegment(0, 0, a),
+ new TestLineSegment(0, 0, b)
+ ));
+
+ List<TestLineSegment> segments = region.getBoundaries();
+ PartitionTestUtils.assertPointsEqual(segments.get(0).getStartPoint(), segments.get(1).getEndPoint());
+
+ TestLine splitter = new TestLine(new TestPoint2D(0, 0), new TestPoint2D(1, 0));
+
+ // act
+ Split<StubRegion> split = region.split(splitter);
+
+ // assert
+ Assert.assertEquals(SplitLocation.NEITHER, split.getLocation());
+ Assert.assertNull(split.getMinus());
+ Assert.assertNull(split.getPlus());
+ }
+
+ @Test
public void testTransform_full() {
// arrange
StubRegion region = new StubRegion(Collections.emptyList());
diff --git a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTreeTest.java b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTreeTest.java
index 50e946f..68cc682 100644
--- a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTreeTest.java
+++ b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/AbstractRegionBSPTreeTest.java
@@ -29,7 +29,6 @@ import org.apache.commons.geometry.core.partitioning.BoundarySource;
import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.partitioning.SplitLocation;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.bsp.AbstractRegionBSPTree.RegionSizeProperties;
import org.apache.commons.geometry.core.partitioning.test.PartitionTestUtils;
import org.apache.commons.geometry.core.partitioning.test.TestLine;
@@ -37,8 +36,8 @@ import org.apache.commons.geometry.core.partitioning.test.TestLineSegment;
import org.apache.commons.geometry.core.partitioning.test.TestLineSegmentCollection;
import org.apache.commons.geometry.core.partitioning.test.TestPoint2D;
import org.apache.commons.geometry.core.partitioning.test.TestRegionBSPTree;
-import org.apache.commons.geometry.core.partitioning.test.TestTransform2D;
import org.apache.commons.geometry.core.partitioning.test.TestRegionBSPTree.TestRegionNode;
+import org.apache.commons.geometry.core.partitioning.test.TestTransform2D;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -1179,20 +1178,20 @@ public class AbstractRegionBSPTreeTest {
Assert.assertTrue(xAxisBoundary.getOutsideFacing().isEmpty());
Assert.assertFalse(xAxisBoundary.getInsideFacing().isEmpty());
- TestLineSegmentCollection xAxisInsideFacing = (TestLineSegmentCollection) xAxisBoundary.getInsideFacing();
- Assert.assertEquals(1, xAxisInsideFacing.getLineSegments().size());
+ List<HyperplaneConvexSubset<TestPoint2D>> xAxisInsideFacing = xAxisBoundary.getInsideFacing();
+ Assert.assertEquals(1, xAxisInsideFacing.size());
- TestLineSegment xAxisSeg = xAxisInsideFacing.getLineSegments().get(0);
+ TestLineSegment xAxisSeg = (TestLineSegment) xAxisInsideFacing.get(0);
PartitionTestUtils.assertPointsEqual(new TestPoint2D(Double.NEGATIVE_INFINITY, 0), xAxisSeg.getStartPoint());
PartitionTestUtils.assertPointsEqual(TestPoint2D.ZERO, xAxisSeg.getEndPoint());
Assert.assertTrue(yAxisBoundary.getOutsideFacing().isEmpty());
Assert.assertFalse(yAxisBoundary.getInsideFacing().isEmpty());
- TestLineSegmentCollection yAxisInsideFacing = (TestLineSegmentCollection) yAxisBoundary.getInsideFacing();
- Assert.assertEquals(1, yAxisInsideFacing.getLineSegments().size());
+ List<HyperplaneConvexSubset<TestPoint2D>> yAxisInsideFacing = yAxisBoundary.getInsideFacing();
+ Assert.assertEquals(1, yAxisInsideFacing.size());
- TestLineSegment yAxisSeg = yAxisInsideFacing.getLineSegments().get(0);
+ TestLineSegment yAxisSeg = (TestLineSegment) yAxisInsideFacing.get(0);
PartitionTestUtils.assertPointsEqual(TestPoint2D.ZERO, yAxisSeg.getStartPoint());
PartitionTestUtils.assertPointsEqual(new TestPoint2D(0, Double.POSITIVE_INFINITY), yAxisSeg.getEndPoint());
}
@@ -1552,14 +1551,13 @@ public class AbstractRegionBSPTreeTest {
new TestLineSegment(new TestPoint2D(-4, -5), new TestPoint2D(1, 0))));
}
- private static void assertCutBoundarySegment(final HyperplaneSubset<TestPoint2D> boundary, final TestPoint2D start,
- final TestPoint2D end) {
- Assert.assertFalse("Expected boundary to not be empty", boundary.isEmpty());
+ private static void assertCutBoundarySegment(final List<HyperplaneConvexSubset<TestPoint2D>> boundaries,
+ final TestPoint2D start, final TestPoint2D end) {
+ Assert.assertFalse("Expected boundary to not be empty", boundaries.isEmpty());
- TestLineSegmentCollection segmentCollection = (TestLineSegmentCollection) boundary;
- Assert.assertEquals(1, segmentCollection.getLineSegments().size());
+ Assert.assertEquals(1, boundaries.size());
- TestLineSegment segment = segmentCollection.getLineSegments().get(0);
+ TestLineSegment segment = (TestLineSegment) boundaries.get(0);
PartitionTestUtils.assertPointsEqual(start, segment.getStartPoint());
PartitionTestUtils.assertPointsEqual(end, segment.getEndPoint());
}
diff --git a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundaryTest.java b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundaryTest.java
index 9e2bb90..ecd51f1 100644
--- a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundaryTest.java
+++ b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/bsp/RegionCutBoundaryTest.java
@@ -16,7 +16,14 @@
*/
package org.apache.commons.geometry.core.partitioning.bsp;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.geometry.core.GeometryTestUtils;
+import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.test.PartitionTestUtils;
+import org.apache.commons.geometry.core.partitioning.test.TestLine;
import org.apache.commons.geometry.core.partitioning.test.TestLineSegment;
import org.apache.commons.geometry.core.partitioning.test.TestPoint2D;
import org.junit.Assert;
@@ -24,18 +31,68 @@ import org.junit.Test;
public class RegionCutBoundaryTest {
+ private static final double TEST_EPS = 1e-10;
+
@Test
public void testProperties() {
// arrange
- TestLineSegment insideFacing = new TestLineSegment(TestPoint2D.ZERO, new TestPoint2D(1, 0));
- TestLineSegment outsideFacing = new TestLineSegment(new TestPoint2D(-1, 0), TestPoint2D.ZERO);
+ List<HyperplaneConvexSubset<TestPoint2D>> insideFacing =
+ Arrays.asList(new TestLineSegment(TestPoint2D.ZERO, new TestPoint2D(1, 0)));
+ List<HyperplaneConvexSubset<TestPoint2D>> outsideFacing =
+ Arrays.asList(new TestLineSegment(new TestPoint2D(-1, 0), TestPoint2D.ZERO));
// act
RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(insideFacing, outsideFacing);
// assert
- Assert.assertSame(insideFacing, boundary.getInsideFacing());
- Assert.assertSame(outsideFacing, boundary.getOutsideFacing());
+ Assert.assertNotSame(insideFacing, boundary.getInsideFacing());
+ Assert.assertEquals(insideFacing, boundary.getInsideFacing());
+
+ Assert.assertNotSame(outsideFacing, boundary.getOutsideFacing());
+ Assert.assertEquals(outsideFacing, boundary.getOutsideFacing());
+ }
+
+ @Test
+ public void testProperties_nullLists() {
+ // act
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(null, null);
+
+ // assert
+ Assert.assertEquals(0, boundary.getInsideFacing().size());
+ Assert.assertEquals(0, boundary.getOutsideFacing().size());
+ }
+
+ @Test
+ public void testGetSize_noSize() {
+ // act
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(null, null);
+
+ // assert
+ Assert.assertEquals(0, boundary.getSize(), TEST_EPS);
+ }
+
+ @Test
+ public void testGetSize_infinite() {
+ // act
+ TestLine line = new TestLine(new TestPoint2D(0, 0), new TestPoint2D(1, 0));
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(
+ Arrays.asList(new TestLineSegment(1, Double.POSITIVE_INFINITY, line)),
+ Arrays.asList(new TestLineSegment(Double.NEGATIVE_INFINITY, -1, line)));
+
+ // assert
+ GeometryTestUtils.assertPositiveInfinity(boundary.getSize());
+ }
+
+ @Test
+ public void testGetSize_finite() {
+ // act
+ TestLine line = new TestLine(new TestPoint2D(0, 0), new TestPoint2D(1, 0));
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(
+ Arrays.asList(new TestLineSegment(1, 2, line), new TestLineSegment(3, 4, line)),
+ Arrays.asList(new TestLineSegment(-3, -1, line)));
+
+ // assert
+ Assert.assertEquals(4, boundary.getSize(), TEST_EPS);
}
@Test
@@ -48,7 +105,8 @@ public class RegionCutBoundaryTest {
TestLineSegment insideFacing = new TestLineSegment(a, b);
TestLineSegment outsideFacing = new TestLineSegment(b, c);
- RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(insideFacing, outsideFacing);
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(Arrays.asList(insideFacing),
+ Arrays.asList(outsideFacing));
// act/assert
PartitionTestUtils.assertPointsEqual(a, boundary.closest(new TestPoint2D(-2, 1)));
@@ -68,7 +126,7 @@ public class RegionCutBoundaryTest {
TestLineSegment outsideFacing = new TestLineSegment(a, b);
- RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(null, outsideFacing);
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(null, Arrays.asList(outsideFacing));
// act/assert
PartitionTestUtils.assertPointsEqual(a, boundary.closest(new TestPoint2D(-2, 1)));
@@ -85,7 +143,7 @@ public class RegionCutBoundaryTest {
TestLineSegment insideFacing = new TestLineSegment(a, b);
- RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(insideFacing, null);
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(Arrays.asList(insideFacing), null);
// act/assert
PartitionTestUtils.assertPointsEqual(a, boundary.closest(new TestPoint2D(-2, 1)));
@@ -114,7 +172,8 @@ public class RegionCutBoundaryTest {
TestLineSegment insideFacing = new TestLineSegment(a, b);
TestLineSegment outsideFacing = new TestLineSegment(b, c);
- RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(insideFacing, outsideFacing);
+ RegionCutBoundary<TestPoint2D> boundary = new RegionCutBoundary<>(Arrays.asList(insideFacing),
+ Arrays.asList(outsideFacing));
// act/assert
Assert.assertFalse(boundary.contains(new TestPoint2D(-2, 0)));
diff --git a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegment.java b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegment.java
index 7ec2a4e..4514732 100644
--- a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegment.java
+++ b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegment.java
@@ -21,10 +21,9 @@ import java.util.List;
import org.apache.commons.geometry.core.RegionLocation;
import org.apache.commons.geometry.core.Transform;
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.Hyperplane;
+import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.Split;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
/** Class representing a line segment in two dimensional Euclidean space. This
* class should only be used for testing purposes.
@@ -199,12 +198,6 @@ public class TestLineSegment implements HyperplaneConvexSubset<TestPoint2D> {
/** {@inheritDoc} */
@Override
- public HyperplaneSubset.Builder<TestPoint2D> builder() {
- return new TestLineSegmentCollectionBuilder(line);
- }
-
- /** {@inheritDoc} */
- @Override
public HyperplaneConvexSubset<TestPoint2D> transform(Transform<TestPoint2D> transform) {
if (!isInfinite()) {
// simple case; just transform the points directly
diff --git a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegmentCollection.java b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegmentCollection.java
index 5b05916..15cd123 100644
--- a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegmentCollection.java
+++ b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegmentCollection.java
@@ -189,10 +189,4 @@ public class TestLineSegmentCollection implements HyperplaneSubset<TestPoint2D>
public HyperplaneSubset<TestPoint2D> transform(Transform<TestPoint2D> transform) {
throw new UnsupportedOperationException();
}
-
- /** {@inheritDoc} */
- @Override
- public HyperplaneSubset.Builder<TestPoint2D> builder() {
- return new TestLineSegmentCollectionBuilder(segments.get(0).getHyperplane());
- }
}
diff --git a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegmentCollectionBuilder.java b/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegmentCollectionBuilder.java
deleted file mode 100644
index 0e7adf8..0000000
--- a/commons-geometry-core/src/test/java/org/apache/commons/geometry/core/partitioning/test/TestLineSegmentCollectionBuilder.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.geometry.core.partitioning.test;
-
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
-
-public class TestLineSegmentCollectionBuilder implements HyperplaneSubset.Builder<TestPoint2D> {
-
- private final TestLine line;
-
- private final List<SegmentInterval> intervals = new LinkedList<>();
-
- public TestLineSegmentCollectionBuilder(final TestLine line) {
- this.line = line;
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(HyperplaneSubset<TestPoint2D> sub) {
- for (HyperplaneConvexSubset<TestPoint2D> convex : sub.toConvex()) {
- add(convex);
- }
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(HyperplaneConvexSubset<TestPoint2D> convex) {
- TestLineSegment seg = (TestLineSegment) convex;
- addSegment(seg.getStart(), seg.getEnd());
- }
-
- /** {@inheritDoc} */
- @Override
- public HyperplaneSubset<TestPoint2D> build() {
- List<TestLineSegment> segments = new ArrayList<>();
-
- for (SegmentInterval interval : intervals) {
- segments.add(new TestLineSegment(interval.start, interval.end, line));
- }
-
- return new TestLineSegmentCollection(segments);
- }
-
- private void addSegment(final double start, final double end) {
- if (intervals.isEmpty()) {
- intervals.add(new SegmentInterval(start, end));
- } else {
- boolean added = false;
- SegmentInterval current;
- for (int i = 0; i < intervals.size() && !added; ++i) {
- current = intervals.get(i);
-
- if (end < current.start) {
- intervals.add(i, new SegmentInterval(start, end));
-
- added = true;
- } else if (start <= current.end) {
- current.start = Math.min(current.start, start);
- current.end = Math.max(current.end, end);
-
- added = true;
- }
- }
-
- if (!added) {
- intervals.add(new SegmentInterval(start, end));
- }
- }
- }
-
- private static class SegmentInterval {
- private double start;
- private double end;
-
- SegmentInterval(final double start, final double end) {
- this.start = start;
- this.end = end;
- }
- }
-}
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/oned/OrientedPoint.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/oned/OrientedPoint.java
index 8a70fd6..097dc91 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/oned/OrientedPoint.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/oned/OrientedPoint.java
@@ -26,7 +26,6 @@ import org.apache.commons.geometry.core.partitioning.AbstractHyperplane;
import org.apache.commons.geometry.core.partitioning.Hyperplane;
import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneLocation;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
@@ -376,12 +375,6 @@ public final class OrientedPoint extends AbstractHyperplane<Vector1D>
/** {@inheritDoc} */
@Override
- public OrientedPointSubsetBuilder builder() {
- return new OrientedPointSubsetBuilder(this);
- }
-
- /** {@inheritDoc} */
- @Override
public OrientedPointConvexSubset reverse() {
return new OrientedPointConvexSubset(hyperplane.reverse());
}
@@ -398,66 +391,4 @@ public final class OrientedPoint extends AbstractHyperplane<Vector1D>
return sb.toString();
}
}
-
- /** {@link HyperplaneSubset.Builder} implementation for Euclidean 1D space. Similar to
- * {@link OrientedPointConvexSubset}, this is effectively a stub implementation since there are no subspaces
- * of 1D space. Its primary use is to allow for the correct functioning of partitioning code.
- */
- private static final class OrientedPointSubsetBuilder implements HyperplaneSubset.Builder<Vector1D> {
- /** Base hyperplane subset for the builder. */
- private final OrientedPointConvexSubset base;
-
- /** Construct a new instance using the given base hyperplane subset.
- * @param base base hyperplane subset for the instance
- */
- OrientedPointSubsetBuilder(final OrientedPointConvexSubset base) {
- this.base = base;
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneSubset<Vector1D> sub) {
- validateHyperplane(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneConvexSubset<Vector1D> sub) {
- validateHyperplane(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public OrientedPointConvexSubset build() {
- return base;
- }
-
- /** {@inheritDoc} */
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder();
- sb.append(this.getClass().getSimpleName())
- .append("[base= ")
- .append(base)
- .append(']');
-
- return sb.toString();
- }
-
- /** Validate that the given hyperplane subset lies on the same hyperplane as this instance.
- * @param sub hyperplane subset to validate
- * @throws IllegalArgumentException if the argument does not lie on
- * the same hyperplane as this instance
- */
- private void validateHyperplane(final HyperplaneSubset<Vector1D> sub) {
- final OrientedPoint baseHyper = base.getHyperplane();
- final OrientedPoint inputHyper = (OrientedPoint) sub.getHyperplane();
-
- if (!baseHyper.eq(inputHyper, baseHyper.getPrecision())) {
- throw new IllegalArgumentException("Argument is not on the same " +
- "hyperplane. Expected " + baseHyper + " but was " +
- inputHyper);
- }
- }
- }
}
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/AbstractPlaneSubset.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/AbstractPlaneSubset.java
index 6e9d017..474f20a 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/AbstractPlaneSubset.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/AbstractPlaneSubset.java
@@ -16,10 +16,6 @@
*/
package org.apache.commons.geometry.euclidean.threed;
-import java.util.Objects;
-
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.euclidean.threed.line.Line3D;
import org.apache.commons.geometry.euclidean.threed.line.LineConvexSubset3D;
@@ -35,12 +31,6 @@ abstract class AbstractPlaneSubset implements PlaneSubset {
/** {@inheritDoc} */
@Override
- public HyperplaneSubset.Builder<Vector3D> builder() {
- return new Builder(getPlane());
- }
-
- /** {@inheritDoc} */
- @Override
public Vector3D intersection(final Line3D line) {
return Planes.intersection(this, line);
}
@@ -50,103 +40,4 @@ abstract class AbstractPlaneSubset implements PlaneSubset {
public Vector3D intersection(LineConvexSubset3D lineSubset) {
return Planes.intersection(this, lineSubset);
}
-
- /** Internal implementation of the {@link HyperplaneSubset.Builder} interface. In cases where only a single
- * convex subset is given to the builder, this class returns the convex subset instance directly. In all other
- * cases, an {@link EmbeddedTreePlaneSubset} is used to construct the final subset.
- */
- private static final class Builder implements HyperplaneSubset.Builder<Vector3D> {
- /** Plane that a subset is being constructed for. */
- private final Plane plane;
-
- /** Embedded tree subset. */
- private EmbeddedTreePlaneSubset treeSubset;
-
- /** Convex subset added as the first subset to the builder. This is returned directly if
- * no other subsets are added.
- */
- private PlaneConvexSubset convexSubset;
-
- /** Create a new subset builder for the given plane.
- * @param plane plane to build a subset for
- */
- Builder(final Plane plane) {
- this.plane = plane;
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneSubset<Vector3D> sub) {
- addInternal(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneConvexSubset<Vector3D> sub) {
- addInternal(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public PlaneSubset build() {
- // return the convex subset directly if that was all we were given
- if (convexSubset != null) {
- return convexSubset;
- }
- return getTreeSubset();
- }
-
- /** Internal method for adding hyperplane subsets to this builder.
- * @param sub the hyperplane subset to add; may be either convex or non-convex
- */
- private void addInternal(final HyperplaneSubset<Vector3D> sub) {
- Objects.requireNonNull(sub, "Hyperplane subset must not be null");
-
- if (sub instanceof PlaneConvexSubset) {
- addConvexSubset((PlaneConvexSubset) sub);
- } else if (sub instanceof EmbeddedTreePlaneSubset) {
- addTreeSubset((EmbeddedTreePlaneSubset) sub);
- } else {
- throw new IllegalArgumentException("Unsupported hyperplane subset type: " + sub.getClass().getName());
- }
- }
-
- /** Add a convex subset to the builder.
- * @param convex convex subset to add
- */
- private void addConvexSubset(final PlaneConvexSubset convex) {
- Planes.validatePlanesEquivalent(plane, convex.getPlane());
-
- if (treeSubset == null && convexSubset == null) {
- convexSubset = convex;
- } else {
- getTreeSubset().add(convex);
- }
- }
-
- /** Add an embedded tree subset to the builder.
- * @param tree embedded tree subset to add
- */
- private void addTreeSubset(final EmbeddedTreePlaneSubset tree) {
- // no need to validate the line here since the add() method does that for us
- getTreeSubset().add(tree);
- }
-
- /** Get the tree subset for the builder, creating it if needed.
- * @return the tree subset for the builder
- */
- private EmbeddedTreePlaneSubset getTreeSubset() {
- if (treeSubset == null) {
- treeSubset = new EmbeddedTreePlaneSubset(plane.getEmbedding());
-
- if (convexSubset != null) {
- treeSubset.add(convexSubset);
-
- convexSubset = null;
- }
- }
-
- return treeSubset;
- }
- }
}
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/Planes.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/Planes.java
index 9da6697..349259f 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/Planes.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/Planes.java
@@ -131,7 +131,6 @@ public final class Planes {
if (area.isFinite()) {
// prefer a vertex-based representation for finite areas
final List<Vector3D> vertices = plane.toSpace(area.getVertices());
-
return fromConvexPlanarVertices(plane, vertices);
}
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/RegionBSPTree3D.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/RegionBSPTree3D.java
index b4c1781..141bdaf 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/RegionBSPTree3D.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/RegionBSPTree3D.java
@@ -22,6 +22,7 @@ import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.commons.geometry.core.partitioning.Hyperplane;
+import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.partitioning.bsp.AbstractBSPTree;
@@ -312,8 +313,14 @@ public final class RegionBSPTree3D extends AbstractRegionBSPTree<Vector3D, Regio
public Result visit(final RegionNode3D node) {
if (node.isInternal()) {
final RegionCutBoundary<Vector3D> boundary = node.getCutBoundary();
- addBoundaryContribution(boundary.getOutsideFacing(), false);
- addBoundaryContribution(boundary.getInsideFacing(), true);
+
+ for (final HyperplaneConvexSubset<Vector3D> outsideFacing : boundary.getOutsideFacing()) {
+ addBoundaryContribution(outsideFacing, false);
+ }
+
+ for (final HyperplaneConvexSubset<Vector3D> insideFacing : boundary.getInsideFacing()) {
+ addBoundaryContribution(insideFacing, true);
+ }
}
return Result.CONTINUE;
@@ -483,11 +490,11 @@ public final class RegionBSPTree3D extends AbstractRegionBSPTree<Vector3D, Regio
boolean onBoundary = false;
boolean negateNormal = false;
- if (boundary.getInsideFacing() != null && boundary.getInsideFacing().contains(pt)) {
+ if (boundary.containsInsideFacing(pt)) {
// on inside-facing boundary
onBoundary = true;
negateNormal = true;
- } else if (boundary.getOutsideFacing() != null && boundary.getOutsideFacing().contains(pt)) {
+ } else if (boundary.containsOutsideFacing(pt)) {
// on outside-facing boundary
onBoundary = true;
}
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/shape/Sphere.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/shape/Sphere.java
index 8c0d789..b3309c8 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/shape/Sphere.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/shape/Sphere.java
@@ -16,7 +16,6 @@
*/
package org.apache.commons.geometry.euclidean.threed.shape;
-import java.text.MessageFormat;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -24,15 +23,15 @@ import java.util.stream.Stream;
import org.apache.commons.geometry.core.partitioning.bsp.RegionCutRule;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
import org.apache.commons.geometry.euclidean.AbstractNSphere;
+import org.apache.commons.geometry.euclidean.threed.Plane;
import org.apache.commons.geometry.euclidean.threed.Planes;
import org.apache.commons.geometry.euclidean.threed.RegionBSPTree3D;
-import org.apache.commons.geometry.euclidean.threed.SphericalCoordinates;
+import org.apache.commons.geometry.euclidean.threed.RegionBSPTree3D.RegionNode3D;
import org.apache.commons.geometry.euclidean.threed.Vector3D;
import org.apache.commons.geometry.euclidean.threed.line.Line3D;
import org.apache.commons.geometry.euclidean.threed.line.LineConvexSubset3D;
import org.apache.commons.geometry.euclidean.threed.line.LinecastPoint3D;
import org.apache.commons.geometry.euclidean.threed.line.Linecastable3D;
-import org.apache.commons.numbers.angle.PlaneAngleRadians;
/** Class representing a 3 dimensional sphere in Euclidean space.
*/
@@ -75,33 +74,53 @@ public final class Sphere extends AbstractNSphere<Vector3D> implements Linecasta
return project(pt, Vector3D.Unit.PLUS_X);
}
- /** Return a {@link RegionBSPTree3D} representing an approximation of the sphere. All points
- * in the approximation are contained in the sphere (ie, they lie inside or on the boundary).
- * No guarantees are made regarding the internal structure of the returned tree. Non-boundary
- * split nodes may be used in order to balance the tree and improve performance.
+ /** Build an approximation of this sphere using a {@link RegionBSPTree3D}. The approximation is constructed by
+ * taking an octahedron (8-sided polyhedron with triangular faces) inscribed in the sphere and subdividing each
+ * triangular face {@code subdivisions} number of times, each time projecting the newly created vertices onto the
+ * sphere surface. Each triangle subdivision produces 4 triangles, meaning that the total number of triangles
+ * inserted into tree is equal to \(8 \times 4^s\), where \(s\) is the number of subdivisions. For
+ * example, calling this method with {@code subdivisions} equal to {@code 3} will produce a tree having
+ * \(8 \times 4^3 = 512\) triangular facets inserted. See the table below for other examples. The returned BSP
+ * tree also contains structural cuts to reduce the overall height of the tree.
*
- * <p>The sphere approximation is created by logically dividing up the sphere into
- * {@code stacks} number of sections by planes perpendicular to the z-axis. For each such "stack",
- * {@code slices} number of boundary planes are then created around the z-pole of the sphere
- * from points lying on the sphere boundary. The total number of logical boundaries in the approximation
- * is therefore equal to {@code stacks * slices}. (Note that this may not match the number of
- * boundaries returned by {@link RegionBSPTree3D#getBoundaries()}, depending on the internal
- * structure of the returned tree.)
+ * <table>
+ * <caption>Subdivisions to Triangle Counts</caption>
+ * <thead>
+ * <tr>
+ * <th>Subdivisions</th>
+ * <th>Triangles</th>
+ * </tr>
+ * </thead>
+ * <tbody>
+ * <tr><td>0</td><td>8</td></tr>
+ * <tr><td>1</td><td>32</td></tr>
+ * <tr><td>2</td><td>128</td></tr>
+ * <tr><td>3</td><td>512</td></tr>
+ * <tr><td>4</td><td>2048</td></tr>
+ * <tr><td>5</td><td>8192</td></tr>
+ * </tbody>
+ * </table>
*
- * <p>Choosing appropriate values for {@code stacks} and {@code slices} is a trade-off
- * between size and accuracy: approximations with large numbers of boundaries more closely
- * match the geometric properties of the sphere but at the cost of using larger tree structures.
- * In general, the smallest number of boundaries that produce an acceptable result should be used.
- *
- * @param stacks number of stacks to use when creating the approximation; each stacks
- * contains {@code slices} number of boundary planes surrounding the
- * z-axis of the sphere
- * @param slices number of boundary planes to create for each "stack" of the approximation
- * @return a BSP tree approximation of the sphere
- * @throws IllegalArgumentException if {@code stacks} is less than 2 or {@code slices} is less than 3
+ * <p>Care must be taken when using this method with large subdivision numbers so that floating point errors
+ * do not interfere with the creation of the planes and triangles in the tree. For example, if the number of
+ * subdivisions is too high, the subdivided triangle points may become equivalent according to the sphere's
+ * {@link #getPrecision() precision context} and plane creation may fail. Or plane creation may succeed but
+ * insertion of the plane into the tree may fail for similar reasons. In general, it is best to use the lowest
+ * subdivision number practical for the intended purpose.</p>
+ * @param subdivisions the number of triangle subdivisions to use when creating the tree; the total number of
+ * triangular facets inserted into the returned tree is equal to \(8 \times 4^s\), where \(s\) is the number
+ * of subdivisions
+ * @return a BSP tree containing an approximation of the sphere
+ * @throws IllegalArgumentException if {@code subdivisions} is less than zero
+ * @throws IllegalStateException if tree creation fails for the given subdivision count
*/
- public RegionBSPTree3D toTree(final int stacks, final int slices) {
- return new SphereApproximationBuilder(this, stacks, slices).build();
+ public RegionBSPTree3D toTree(final int subdivisions) {
+ if (subdivisions < 0) {
+ throw new IllegalArgumentException(
+ "Number of sphere approximation subdivisions must be greater than or equal to zero; was " +
+ subdivisions);
+ }
+ return new SphereApproximationBuilder(this, subdivisions).build();
}
/** Get the intersections of the given line with this sphere. The returned list will
@@ -173,200 +192,181 @@ public final class Sphere extends AbstractNSphere<Vector3D> implements Linecasta
return new Sphere(center, radius, precision);
}
- /** Class used to construct BSP tree approximations of spheres. Structural BSP tree cuts are
- * used to help balance the tree and improve performance.
+ /** Internal class used to construct hyperplane-bounded approximations of spheres. The class begins with an
+ * octahedron inscribed in the sphere and then subdivides each triangular face a specified number of times.
*/
- private static class SphereApproximationBuilder {
-
- /** Minimum number of stacks. */
- private static final int MIN_STACKS = 2;
-
- /** Minimum number of slices. */
- private static final int MIN_SLICES = 3;
+ private static final class SphereApproximationBuilder {
- /** Minimum number of slices in a portion of a stack to allow a structural BSP split. */
- private static final int SLICE_SPLIT_THRESHOLD = 4;
+ /** Threshold used to determine when to stop inserting structural cuts and begin adding facets. */
+ private static final int PARTITION_THRESHOLD = 2;
- /** The sphere being approximated. */
+ /** The sphere that an approximation is being created for. */
private final Sphere sphere;
- /** Number of stacks in the approximation. */
- private final int stacks;
+ /** The number of triangular subdivisions to use. */
+ private final int subdivisions;
- /** Number of slices in the approximation. */
- private final int slices;
-
- /** Polar delta value between vertices. */
- private final double polarDelta;
-
- /** Azimuth delta value between vertices. */
- private final double azimuthDelta;
-
- /** Create a new instance for approximating the given sphere.
- * @param sphere sphere to approximate
- * @param stacks number of "stacks" (sections parallel to the x-y plane) in the approximation
- * @param slices number of "slices" (boundary plane subsets per stack) in the approximation
- * @throws IllegalArgumentException if {@code stacks} is less than 2 or {@code slices} is less than 3
+ /** Construct a new builder for creating a BSP tree approximation of the given sphere.
+ * @param sphere the sphere to create an approximation of
+ * @param subdivisions the number of triangle subdivisions to use in tree creation
*/
- SphereApproximationBuilder(final Sphere sphere, final int stacks, final int slices) {
- if (stacks < MIN_STACKS) {
- throw new IllegalArgumentException(MessageFormat.format(
- "Sphere approximation stack number must be greater than or equal to {0}; was {1}",
- MIN_STACKS, stacks));
- }
- if (slices < MIN_SLICES) {
- throw new IllegalArgumentException(MessageFormat.format(
- "Sphere approximation slice number must be greater than or equal to {0}; was {1}",
- MIN_SLICES, slices));
- }
-
+ SphereApproximationBuilder(final Sphere sphere, final int subdivisions) {
this.sphere = sphere;
- this.stacks = stacks;
- this.slices = slices;
-
- this.polarDelta = PlaneAngleRadians.PI / stacks;
- this.azimuthDelta = PlaneAngleRadians.TWO_PI / slices;
+ this.subdivisions = subdivisions;
}
- /** Build the BSP tree sphere approximation.
- * @return the BSP tree sphere approximation
+ /** Build the sphere approximation BSP tree.
+ * @return the sphere approximation BSP tree
+ * @throws IllegalStateException if tree creation fails for the configured subdivision count
*/
- public RegionBSPTree3D build() {
+ RegionBSPTree3D build() {
final RegionBSPTree3D tree = RegionBSPTree3D.empty();
- splitAndInsertStacks(tree.getRoot(), 0, stacks);
+ final Vector3D center = sphere.getCenter();
+ final double radius = sphere.getRadius();
+ final DoublePrecisionContext precision = sphere.getPrecision();
- return tree;
- }
+ // insert the primary split planes
+ Plane plusXPlane = Planes.fromPointAndNormal(center, Vector3D.Unit.PLUS_X, precision);
+ Plane plusYPlane = Planes.fromPointAndNormal(center, Vector3D.Unit.PLUS_Y, precision);
+ Plane plusZPlane = Planes.fromPointAndNormal(center, Vector3D.Unit.PLUS_Z, precision);
- /** Recursively split the given node and insert stacks. The node is split until only a single stack
- * remains, at which point slices are inserted.
- * @param node node to insert into
- * @param polarTopIdx the polar index for vertices at the top of the stack
- * @param polarBottomIdx the polar index for vertices at the bottom of the stack
- */
- private void splitAndInsertStacks(final RegionBSPTree3D.RegionNode3D node, final int polarTopIdx,
- final int polarBottomIdx) {
-
- final int indexDiff = polarBottomIdx - polarTopIdx;
- if (indexDiff < 2) {
- // we have a single stack, separated by vertices on two stack rows; we can now insert
- // boundary planes using the polar bottom index
- insertStack(node, polarBottomIdx);
- } else {
- // split the group of stacks in two
- final int splitIdx = (indexDiff / 2) + polarTopIdx;
- final Vector3D splitPt = pointAt(splitIdx, 0);
+ tree.insert(plusXPlane.span(), RegionCutRule.INHERIT);
+ tree.insert(plusYPlane.span(), RegionCutRule.INHERIT);
+ tree.insert(plusZPlane.span(), RegionCutRule.INHERIT);
- node.cut(Planes.fromPointAndNormal(splitPt, Vector3D.Unit.PLUS_Z, sphere.getPrecision()),
- RegionCutRule.INHERIT);
+ // create the vertices for the octahedron
+ final double cx = center.getX();
+ final double cy = center.getY();
+ final double cz = center.getZ();
- splitAndInsertStacks(node.getPlus(), polarTopIdx, splitIdx);
- splitAndInsertStacks(node.getMinus(), splitIdx, polarBottomIdx);
- }
- }
+ Vector3D maxX = Vector3D.of(cx + radius, cy, cz);
+ Vector3D minX = Vector3D.of(cx - radius, cy, cz);
- /** Insert the boundaries ("slices") for the stack with the given polar bottom index.
- * @param node node to insert into
- * @param polarBottomIdx the polar index for vertices at the bottom of the stack
- */
- private void insertStack(final RegionBSPTree3D.RegionNode3D node, final int polarBottomIdx) {
- if (slices >= SLICE_SPLIT_THRESHOLD) {
- final int splitIdx = slices / 2;
+ Vector3D maxY = Vector3D.of(cx, cy + radius, cz);
+ Vector3D minY = Vector3D.of(cx, cy - radius, cz);
- RegionBSPTree3D.RegionNode3D splitNode = node;
- int sliceEndIdx = slices;
+ Vector3D maxZ = Vector3D.of(cx, cy, cz + radius);
+ Vector3D minZ = Vector3D.of(cx, cy, cz - radius);
- if (slices % 2 != 0) {
- // odd number of slices; we'll need to add the side directly opposite
- // split index before splitting
- splitNode = insertSlices(node, polarBottomIdx, slices - 1, slices);
- --sliceEndIdx;
- }
+ // partition and subdivide the face triangles and insert them into the tree
+ RegionNode3D root = tree.getRoot();
- final Vector3D p0 = sphere.getCenter();
- final Vector3D p1 = pointAt(polarBottomIdx, splitIdx);
- final Vector3D p2 = pointAt(polarBottomIdx - 1, splitIdx);
+ try {
+ partitionAndInsert(root.getMinus().getMinus().getMinus(), minX, minZ, minY, 0);
+ partitionAndInsert(root.getMinus().getMinus().getPlus(), minX, minY, maxZ, 0);
- splitNode.cut(Planes.fromPoints(p0, p1, p2, sphere.getPrecision()), RegionCutRule.INHERIT);
+ partitionAndInsert(root.getMinus().getPlus().getMinus(), minX, maxY, minZ, 0);
+ partitionAndInsert(root.getMinus().getPlus().getPlus(), minX, maxZ, maxY, 0);
- splitAndInsertSlices(splitNode.getPlus(), polarBottomIdx, 0, splitIdx);
- splitAndInsertSlices(splitNode.getMinus(), polarBottomIdx, splitIdx, sliceEndIdx);
- } else {
- insertSlices(node, polarBottomIdx, 0, slices);
+ partitionAndInsert(root.getPlus().getMinus().getMinus(), maxX, minY, minZ, 0);
+ partitionAndInsert(root.getPlus().getMinus().getPlus(), maxX, maxZ, minY, 0);
+
+ partitionAndInsert(root.getPlus().getPlus().getMinus(), maxX, minZ, maxY, 0);
+ partitionAndInsert(root.getPlus().getPlus().getPlus(), maxX, maxY, maxZ, 0);
+ } catch (final IllegalStateException | IllegalArgumentException exc) {
+ // standardize any tree construction failure as an IllegalStateException
+ throw new IllegalStateException("Failed to construct sphere approximation with subdivision count " +
+ subdivisions + ": " + exc.getMessage(), exc);
}
+
+ return tree;
}
- /** Recursively split a stack and insert slice boundaries.
- * @param node node to insert into
- * @param polarBottomIdx the polar index for vertices at the bottom of the stack
- * @param azimuthStartIdx the azimuth start index for vertices in the inserted slices
- * @param azimuthStopIdx the azimuth start index for vertices in the inserted slices
+ /** Recursively insert structural BSP tree cuts into the given node and then insert subdivided triangles
+ * when a target subdivision level is reached. The structural BSP tree cuts are used to help reduce the
+ * overall depth of the BSP tree.
+ * @param node the node to insert into
+ * @param p1 first triangle point
+ * @param p2 second triangle point
+ * @param p3 third triangle point
+ * @param level current subdivision level
*/
- private void splitAndInsertSlices(final RegionBSPTree3D.RegionNode3D node, final int polarBottomIdx,
- final int azimuthStartIdx, final int azimuthStopIdx) {
+ private void partitionAndInsert(final RegionNode3D node,
+ final Vector3D p1, final Vector3D p2, final Vector3D p3, int level) {
+
+ if (subdivisions - level > PARTITION_THRESHOLD) {
+ final int nextLevel = level + 1;
+
+ final Vector3D center = sphere.getCenter();
- final int indexDiff = azimuthStopIdx - azimuthStartIdx;
- if (indexDiff >= SLICE_SPLIT_THRESHOLD) {
- final int splitIdx = ((indexDiff + 1) / 2) + azimuthStartIdx;
+ final Vector3D m1 = sphere.project(p1.lerp(p2, 0.5));
+ final Vector3D m2 = sphere.project(p2.lerp(p3, 0.5));
+ final Vector3D m3 = sphere.project(p3.lerp(p1, 0.5));
- final Vector3D p0 = sphere.getCenter();
- final Vector3D p1 = pointAt(polarBottomIdx, splitIdx);
- final Vector3D p2 = pointAt(polarBottomIdx - 1, splitIdx);
+ RegionNode3D curNode = node;
- node.cut(Planes.fromPoints(p0, p1, p2, sphere.getPrecision()), RegionCutRule.INHERIT);
+ checkedCut(curNode, createPlane(m3, m2, center), RegionCutRule.INHERIT);
+ partitionAndInsert(curNode.getPlus(), m3, m2, p3, nextLevel);
- splitAndInsertSlices(node.getPlus(), polarBottomIdx, azimuthStartIdx, splitIdx);
- splitAndInsertSlices(node.getMinus(), polarBottomIdx, splitIdx, azimuthStopIdx);
+ curNode = curNode.getMinus();
+ checkedCut(curNode, createPlane(m2, m1, center), RegionCutRule.INHERIT);
+ partitionAndInsert(curNode.getPlus(), m1, p2, m2, nextLevel);
+
+ curNode = curNode.getMinus();
+ checkedCut(curNode, createPlane(m1, m3, center), RegionCutRule.INHERIT);
+ partitionAndInsert(curNode.getPlus(), p1, m1, m3, nextLevel);
+
+ partitionAndInsert(curNode.getMinus(), m1, m2, m3, nextLevel);
} else {
- insertSlices(node, polarBottomIdx, azimuthStartIdx, azimuthStopIdx);
+ insertSubdividedTriangles(node, p1, p2, p3, level);
}
}
- /** Insert slice boundaries. Each boundary is inserted on the minus side of the previously
- * inserted boundary.
- * @param node node to insert into
- * @param polarBottomIdx the polar index for vertices at the bottom of the stack
- * @param azimuthStartIdx the azimuth start index for vertices in the inserted slices
- * @param azimuthStopIdx the azimuth start index for vertices in the inserted slices
- * @return the node representing the interior of the inserted boundaries
- * (the minus child of the last split BSP tree node)
+ /** Recursively insert subdivided triangles into the given node. Each triangle is inserted into the minus
+ * side of the previous triangle.
+ * @param node the node to insert into
+ * @param p1 first triangle point
+ * @param p2 second triangle point
+ * @param p3 third triangle point
+ * @param level the current subdivision level
+ * @return the node representing the inside of the region after insertion of all triangles
*/
- private RegionBSPTree3D.RegionNode3D insertSlices(final RegionBSPTree3D.RegionNode3D node,
- final int polarBottomIdx, final int azimuthStartIdx, final int azimuthStopIdx) {
+ private RegionNode3D insertSubdividedTriangles(final RegionNode3D node,
+ final Vector3D p1, final Vector3D p2, final Vector3D p3, int level) {
- final boolean lastStack = polarBottomIdx == stacks;
+ if (level >= subdivisions) {
+ // base case
+ checkedCut(node, createPlane(p1, p2, p3), RegionCutRule.MINUS_INSIDE);
+ return node.getMinus();
+ } else {
+ final int nextLevel = level + 1;
- RegionBSPTree3D.RegionNode3D currNode = node;
- Vector3D p0;
- Vector3D p1;
- Vector3D p2;
+ final Vector3D m1 = sphere.project(p1.lerp(p2, 0.5));
+ final Vector3D m2 = sphere.project(p2.lerp(p3, 0.5));
+ final Vector3D m3 = sphere.project(p3.lerp(p1, 0.5));
- for (int i = azimuthStartIdx + 1; i <= azimuthStopIdx; ++i) {
- p0 = pointAt(polarBottomIdx, i);
- p1 = pointAt(polarBottomIdx - 1, i);
- p2 = lastStack ?
- pointAt(polarBottomIdx - 1, i - 1) :
- pointAt(polarBottomIdx, i - 1);
+ RegionNode3D curNode = node;
+ curNode = insertSubdividedTriangles(curNode, p1, m1, m3, nextLevel);
+ curNode = insertSubdividedTriangles(curNode, m1, p2, m2, nextLevel);
+ curNode = insertSubdividedTriangles(curNode, m3, m2, p3, nextLevel);
+ curNode = insertSubdividedTriangles(curNode, m1, m2, m3, nextLevel);
- currNode = currNode.cut(Planes.fromPoints(p0, p1, p2, sphere.getPrecision()))
- .getMinus();
+ return curNode;
}
-
- return currNode;
}
- /** Get the vertex at the given polar and azimuth indices.
- * @param polarIdx vertex polar index
- * @param azimuthIdx vertex azimuth index
- * @return the vertex at the given indices
+ /** Create a plane from the given points, using the precision context of the sphere.
+ * @param p1 first point
+ * @param p2 second point
+ * @param p3 third point
+ * @return a plane defined by the given points
*/
- private Vector3D pointAt(final int polarIdx, final int azimuthIdx) {
- final double polar = polarDelta * polarIdx;
- final double az = azimuthDelta * azimuthIdx;
+ private Plane createPlane(final Vector3D p1, final Vector3D p2, final Vector3D p3) {
+ return Planes.fromPoints(p1, p2, p3, sphere.getPrecision());
+ }
- return SphericalCoordinates.toCartesian(sphere.getRadius(), az, polar)
- .add(sphere.getCenter());
+ /** Insert the cut into the given node, throwing an exception if no portion of the cutter intersects
+ * the node.
+ * @param node node to cut
+ * @param cutter plane to use to cut the node
+ * @param cutRule cut rule to apply
+ * @throws IllegalStateException if no portion of the cutter plane intersects the node
+ */
+ private void checkedCut(final RegionNode3D node, final Plane cutter, final RegionCutRule cutRule) {
+ if (!node.insertCut(cutter)) {
+ throw new IllegalStateException("Failed to cut BSP tree node with plane: " + cutter);
+ }
}
}
}
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/ConvexArea.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/ConvexArea.java
index 0a1a4cc..8f4d47c 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/ConvexArea.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/ConvexArea.java
@@ -72,7 +72,9 @@ public class ConvexArea extends AbstractConvexHyperplaneBoundedRegion<Vector2D,
* @return the line subset paths comprising the boundary of the area.
*/
public List<LinePath> getBoundaryPaths() {
- return InteriorAngleLinePathConnector.connectMinimized(getBoundaries());
+ // use connectMaximized() here since that will prevent us from skipping vertices
+ // when there are multiple equivalent vertices to choose from for a given endpoint
+ return InteriorAngleLinePathConnector.connectMaximized(getBoundaries());
}
/** Get the vertices for the area in a counter-clockwise order. Each vertex in the
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/LineSubset.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/LineSubset.java
index 2e8a2c3..e441483 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/LineSubset.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/LineSubset.java
@@ -17,12 +17,10 @@
package org.apache.commons.geometry.euclidean.twod;
import java.util.List;
-import java.util.Objects;
import org.apache.commons.geometry.core.RegionEmbedding;
import org.apache.commons.geometry.core.RegionLocation;
import org.apache.commons.geometry.core.partitioning.HyperplaneBoundedRegion;
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
@@ -63,16 +61,6 @@ public abstract class LineSubset implements HyperplaneSubset<Vector2D>, RegionEm
return line.toSubspace(pt);
}
- /** {@inheritDoc} */
- @Override
- public Vector2D toSpace(final Vector1D pt) {
- return line.toSpace(pt);
- }
-
- /** {@inheritDoc} */
- @Override
- public abstract List<LineConvexSubset> toConvex();
-
/** Get a {@link Bounds2D} object defining an axis-aligned bounding box containing all
* vertices for this subset. Null is returned if the subset is infinite or does not
* contain any vertices.
@@ -86,12 +74,16 @@ public abstract class LineSubset implements HyperplaneSubset<Vector2D>, RegionEm
/** {@inheritDoc} */
@Override
- public HyperplaneSubset.Builder<Vector2D> builder() {
- return new Builder(line);
+ public Vector2D toSpace(final Vector1D pt) {
+ return line.toSpace(pt);
}
/** {@inheritDoc} */
@Override
+ public abstract List<LineConvexSubset> toConvex();
+
+ /** {@inheritDoc} */
+ @Override
public RegionLocation classify(final Vector2D pt) {
if (line.contains(pt)) {
return classifyAbscissa(line.abscissa(pt));
@@ -186,103 +178,4 @@ public abstract class LineSubset implements HyperplaneSubset<Vector2D>, RegionEm
new Split<>(low, high) :
new Split<>(high, low);
}
-
- /** Internal implementation of the {@link HyperplaneSubset.Builder} interface. In cases where only a single
- * convex subset is given to the builder, this class returns the convex subset instance directly. In all other
- * cases, an {@link EmbeddedTreeLineSubset} is used to construct the final subset.
- */
- private static final class Builder implements HyperplaneSubset.Builder<Vector2D> {
- /** Line that a subset is being constructed for. */
- private final Line line;
-
- /** Embedded tree subset. */
- private EmbeddedTreeLineSubset treeSubset;
-
- /** Convex subset added as the first subset to the builder. This is returned directly if
- * no other subsets are added.
- */
- private LineConvexSubset convexSubset;
-
- /** Create a new subset builder for the given line.
- * @param line line to build a subset for
- */
- Builder(final Line line) {
- this.line = line;
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneSubset<Vector2D> sub) {
- addInternal(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneConvexSubset<Vector2D> sub) {
- addInternal(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public LineSubset build() {
- // return the convex subset directly if that was all we were given
- if (convexSubset != null) {
- return convexSubset;
- }
- return getTreeSubset();
- }
-
- /** Internal method for adding hyperplane subsets to this builder.
- * @param sub the hyperplane subset to add; may be either convex or non-convex
- */
- private void addInternal(final HyperplaneSubset<Vector2D> sub) {
- Objects.requireNonNull(sub, "Hyperplane subset must not be null");
-
- if (sub instanceof LineConvexSubset) {
- addConvexSubset((LineConvexSubset) sub);
- } else if (sub instanceof EmbeddedTreeLineSubset) {
- addTreeSubset((EmbeddedTreeLineSubset) sub);
- } else {
- throw new IllegalArgumentException("Unsupported hyperplane subset type: " + sub.getClass().getName());
- }
- }
-
- /** Add a convex subset to the builder.
- * @param convex convex subset to add
- */
- private void addConvexSubset(final LineConvexSubset convex) {
- Lines.validateLinesEquivalent(line, convex.getLine());
-
- if (treeSubset == null && convexSubset == null) {
- convexSubset = convex;
- } else {
- getTreeSubset().add(convex);
- }
- }
-
- /** Add an embedded tree subset to the builder.
- * @param tree embedded tree subset to add
- */
- private void addTreeSubset(final EmbeddedTreeLineSubset tree) {
- // no need to validate the line here since the add() method does that for us
- getTreeSubset().add(tree);
- }
-
- /** Get the tree subset for the builder, creating it if needed.
- * @return the tree subset for the builder
- */
- private EmbeddedTreeLineSubset getTreeSubset() {
- if (treeSubset == null) {
- treeSubset = new EmbeddedTreeLineSubset(line);
-
- if (convexSubset != null) {
- treeSubset.add(convexSubset);
-
- convexSubset = null;
- }
- }
-
- return treeSubset;
- }
- }
}
diff --git a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2D.java b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2D.java
index fc44228..afa9347 100644
--- a/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2D.java
+++ b/commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2D.java
@@ -288,7 +288,7 @@ public final class RegionBSPTree2D extends AbstractRegionBSPTree<Vector2D, Regio
* @return a new tree instance constructed from the given boundaries
* @see #from(Iterable, boolean)
*/
- public static RegionBSPTree2D from(final Iterable<LineConvexSubset> boundaries) {
+ public static RegionBSPTree2D from(final Iterable<? extends LineConvexSubset> boundaries) {
return from(boundaries, false);
}
@@ -299,7 +299,7 @@ public final class RegionBSPTree2D extends AbstractRegionBSPTree<Vector2D, Regio
* @param full if true, the initial tree will contain the entire space
* @return a new tree instance constructed from the given boundaries
*/
- public static RegionBSPTree2D from(final Iterable<LineConvexSubset> boundaries, final boolean full) {
+ public static RegionBSPTree2D from(final Iterable<? extends LineConvexSubset> boundaries, final boolean full) {
final RegionBSPTree2D tree = new RegionBSPTree2D(full);
tree.insert(boundaries);
@@ -471,11 +471,11 @@ public final class RegionBSPTree2D extends AbstractRegionBSPTree<Vector2D, Regio
boolean onBoundary = false;
boolean negateNormal = false;
- if (boundary.getInsideFacing() != null && boundary.getInsideFacing().contains(pt)) {
+ if (boundary.containsInsideFacing(pt)) {
// on inside-facing boundary
onBoundary = true;
negateNormal = true;
- } else if (boundary.getOutsideFacing() != null && boundary.getOutsideFacing().contains(pt)) {
+ } else if (boundary.containsOutsideFacing(pt)) {
// on outside-facing boundary
onBoundary = true;
}
diff --git a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/EuclideanTestUtils.java b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/EuclideanTestUtils.java
index 33fa04c..8309937 100644
--- a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/EuclideanTestUtils.java
+++ b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/EuclideanTestUtils.java
@@ -191,18 +191,19 @@ public final class EuclideanTestUtils {
/**
* Assert that the given lists represent equivalent vertex loops. The loops must contain the same sequence
* of vertices but do not need to start at the same point.
+ * @param <V> Vector implementation type
* @param expected
* @param actual
* @param precision
*/
- public static void assertVertexLoopSequence(List<Vector3D> expected, List<Vector3D> actual,
+ public static <V extends EuclideanVector<V>> void assertVertexLoopSequence(List<V> expected, List<V> actual,
DoublePrecisionContext precision) {
Assert.assertEquals("Vertex sequences have different sizes", expected.size(), actual.size());
if (expected.size() > 0) {
int offset = -1;
- Vector3D start = expected.get(0);
+ V start = expected.get(0);
for (int i = 0; i < actual.size(); ++i) {
if (actual.get(i).eq(start, precision)) {
offset = i;
@@ -214,8 +215,8 @@ public final class EuclideanTestUtils {
Assert.fail("Vertex loops do not share any points: expected " + expected + " but was " + actual);
}
- Vector3D expectedVertex;
- Vector3D actualVertex;
+ V expectedVertex;
+ V actualVertex;
for (int i = 0; i < expected.size(); ++i) {
expectedVertex = expected.get(i);
actualVertex = actual.get((i + offset) % actual.size());
diff --git a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/oned/OrientedPointTest.java b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/oned/OrientedPointTest.java
index 1e97c50..718596e 100644
--- a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/oned/OrientedPointTest.java
+++ b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/oned/OrientedPointTest.java
@@ -23,8 +23,6 @@ import org.apache.commons.geometry.core.RegionLocation;
import org.apache.commons.geometry.core.Transform;
import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneLocation;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset.Builder;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
import org.apache.commons.geometry.core.precision.EpsilonDoublePrecisionContext;
@@ -555,66 +553,6 @@ public class OrientedPointTest {
Assert.assertTrue(str.contains("direction= (1.0)"));
}
- @Test
- public void testBuilder() {
- // arrange
- DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-3);
-
- OrientedPoint pt = OrientedPoints.createPositiveFacing(0, precision);
- HyperplaneConvexSubset<Vector1D> sub = pt.span();
-
- // act
- Builder<Vector1D> builder = sub.builder();
-
- builder.add(sub);
- builder.add(OrientedPoints.createPositiveFacing(1e-4, precision).span());
- builder.add((HyperplaneSubset<Vector1D>) sub);
-
- HyperplaneSubset<Vector1D> result = builder.build();
-
- // assert
- Assert.assertSame(sub, result);
- }
-
- @Test
- public void testBuilder_invalidArgs() {
- // arrange
- DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-3);
-
- OrientedPoint pt = OrientedPoints.createPositiveFacing(0, precision);
- HyperplaneConvexSubset<Vector1D> sub = pt.span();
-
- Builder<Vector1D> builder = sub.builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(
- () -> builder.add(OrientedPoints.createPositiveFacing(2e-3, precision).span()),
- IllegalArgumentException.class);
- GeometryTestUtils.assertThrows(
- () -> builder.add(OrientedPoints.createNegativeFacing(2e-3, precision).span()),
- IllegalArgumentException.class);
-
- GeometryTestUtils.assertThrows(
- () -> builder.add((HyperplaneSubset<Vector1D>) OrientedPoints.createPositiveFacing(2e-3, precision).span()),
- IllegalArgumentException.class);
- }
-
- @Test
- public void testBuilder_toString() {
- // arrange
- OrientedPoint pt = OrientedPoints.createPositiveFacing(2, TEST_PRECISION);
- HyperplaneSubset.Builder<Vector1D> builder = pt.span().builder();
-
- // act
- String str = builder.toString();
-
- //assert
- Assert.assertTrue(str.contains("OrientedPointSubsetBuilder"));
- Assert.assertTrue(str.contains("base= OrientedPointConvexSubset"));
- Assert.assertTrue(str.contains("point= (2.0)"));
- Assert.assertTrue(str.contains("direction= (1.0)"));
- }
-
private static void assertOrientedPoint(OrientedPoint pt, double location, boolean positiveFacing,
DoublePrecisionContext precision) {
Assert.assertEquals(location, pt.getPoint().getX(), TEST_EPS);
diff --git a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/threed/AbstractPlaneSubsetTest.java b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/threed/AbstractPlaneSubsetTest.java
deleted file mode 100644
index 4527771..0000000
--- a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/threed/AbstractPlaneSubsetTest.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.geometry.euclidean.threed;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.commons.geometry.core.GeometryTestUtils;
-import org.apache.commons.geometry.core.RegionLocation;
-import org.apache.commons.geometry.core.Transform;
-import org.apache.commons.geometry.core.partitioning.Hyperplane;
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
-import org.apache.commons.geometry.core.partitioning.Split;
-import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
-import org.apache.commons.geometry.core.precision.EpsilonDoublePrecisionContext;
-import org.apache.commons.geometry.euclidean.twod.ConvexArea;
-import org.apache.commons.geometry.euclidean.twod.RegionBSPTree2D;
-import org.apache.commons.geometry.euclidean.twod.Vector2D;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class AbstractPlaneSubsetTest {
-
- private static final double TEST_EPS = 1e-10;
-
- private static final DoublePrecisionContext TEST_PRECISION =
- new EpsilonDoublePrecisionContext(TEST_EPS);
-
- private static final EmbeddingPlane XY_PLANE = Planes.fromPointAndPlaneVectors(Vector3D.ZERO,
- Vector3D.Unit.PLUS_X, Vector3D.Unit.PLUS_Y, TEST_PRECISION);
-
- @Test
- public void testBuilder_empty() {
- // act
- HyperplaneSubset.Builder<Vector3D> builder = XY_PLANE.span().builder();
-
- PlaneSubset result = (PlaneSubset) builder.build();
-
- // assert
- Assert.assertSame(XY_PLANE, result.getPlane());
-
- Assert.assertFalse(result.isFull());
- Assert.assertTrue(result.isEmpty());
- Assert.assertTrue(result.isFinite());
- Assert.assertFalse(result.isInfinite());
-
- Assert.assertEquals(0, result.getSize(), TEST_EPS);
-
- checkPoints(result, RegionLocation.OUTSIDE, Vector3D.ZERO);
- }
-
- @Test
- public void testBuilder_addSingleConvex_returnsSameInstance() {
- // arrange
- PlaneConvexSubset convex = Planes.convexPolygonFromVertices(Arrays.asList(
- Vector3D.ZERO,
- Vector3D.of(1, 0, 0),
- Vector3D.of(0, 1, 0)
- ), TEST_PRECISION);
-
- // act
- HyperplaneSubset.Builder<Vector3D> builder = XY_PLANE.span().builder();
-
- builder.add(convex);
-
- PlaneSubset result = (PlaneSubset) builder.build();
-
- // assert
- Assert.assertSame(convex, result);
- }
-
- @Test
- public void testBuilder_addSingleTreeSubset() {
- // arrange
- ConvexArea area = ConvexArea.convexPolygonFromVertices(Arrays.asList(
- Vector2D.ZERO,
- Vector2D.of(1, 0),
- Vector2D.of(0, 1)
- ), TEST_PRECISION);
- EmbeddedTreePlaneSubset treeSubset = new EmbeddedTreePlaneSubset(XY_PLANE, area.toTree());
-
- // act
- HyperplaneSubset.Builder<Vector3D> builder = XY_PLANE.span().builder();
-
- builder.add(treeSubset);
-
- PlaneSubset result = (PlaneSubset) builder.build();
-
- // assert
- Assert.assertNotSame(treeSubset, result);
-
- Assert.assertFalse(result.isFull());
- Assert.assertFalse(result.isEmpty());
- Assert.assertTrue(result.isFinite());
- Assert.assertFalse(result.isInfinite());
-
- Assert.assertEquals(0.5, result.getSize(), TEST_EPS);
-
- checkPoints(result, RegionLocation.INSIDE, Vector3D.of(0.25, 0.25, 0));
- checkPoints(result, RegionLocation.OUTSIDE,
- Vector3D.of(0.25, 0.25, 1), Vector3D.of(0.25, 0.25, -1),
- Vector3D.of(1, 0.25, 0), Vector3D.of(-1, 0.25, 0),
- Vector3D.of(0.25, 1, 0), Vector3D.of(0.25, -1, 0));
- checkPoints(result, RegionLocation.BOUNDARY, Vector3D.of(0, 0, 0));
- }
-
- @Test
- public void testBuilder_addMixed_convexFirst() {
- // arrange
- EmbeddingPlane mainPlane = Planes.fromPointAndPlaneVectors(
- Vector3D.of(0, 0, 1), Vector3D.Unit.PLUS_X, Vector3D.Unit.PLUS_Y, TEST_PRECISION);
-
- ConvexArea a = ConvexArea.convexPolygonFromVertices(
- Arrays.asList(Vector2D.ZERO, Vector2D.of(1, 0), Vector2D.of(1, 1).normalize()), TEST_PRECISION);
- ConvexArea b = ConvexArea.convexPolygonFromVertices(
- Arrays.asList(Vector2D.ZERO, Vector2D.of(1, 1).normalize(), Vector2D.of(0, 1)), TEST_PRECISION);
- ConvexArea c = ConvexArea.convexPolygonFromVertices(
- Arrays.asList(Vector2D.Unit.PLUS_X, Vector2D.of(1, 1), Vector2D.Unit.PLUS_Y), TEST_PRECISION);
-
- EmbeddingPlane closePlane = Planes.fromPointAndPlaneVectors(
- Vector3D.of(1e-16, 0, 1), Vector3D.of(1, 1e-16, 0), Vector3D.Unit.PLUS_Y, TEST_PRECISION);
-
- // act
- HyperplaneSubset.Builder<Vector3D> builder = mainPlane.span().builder();
-
- builder.add(Planes.subsetFromConvexArea(closePlane, a));
- builder.add(Planes.subsetFromConvexArea(closePlane, b));
- builder.add(new EmbeddedTreePlaneSubset(closePlane, c.toTree()));
-
- PlaneSubset result = (PlaneSubset) builder.build();
-
- // assert
- Assert.assertFalse(result.isFull());
- Assert.assertFalse(result.isEmpty());
- Assert.assertTrue(result.isFinite());
- Assert.assertFalse(result.isInfinite());
-
- checkPoints(result, RegionLocation.INSIDE, Vector3D.of(0.5, 0.5, 1));
- checkPoints(result, RegionLocation.OUTSIDE,
- Vector3D.of(-1, 0.5, 1), Vector3D.of(2, 0.5, 1),
- Vector3D.of(0.5, -1, 1), Vector3D.of(0.5, 2, 1));
- checkPoints(result, RegionLocation.BOUNDARY,
- Vector3D.of(0, 0, 1), Vector3D.of(1, 0, 1),
- Vector3D.of(1, 1, 1), Vector3D.of(0, 1, 1));
- }
-
- @Test
- public void testBuilder_addMixed_treeSubsetFirst() {
- // arrange
- EmbeddingPlane mainPlane = Planes.fromPointAndPlaneVectors(
- Vector3D.of(0, 0, 1), Vector3D.Unit.PLUS_X, Vector3D.Unit.PLUS_Y, TEST_PRECISION);
-
- ConvexArea a = ConvexArea.convexPolygonFromVertices(
- Arrays.asList(Vector2D.ZERO, Vector2D.of(1, 0), Vector2D.of(1, 1).normalize()), TEST_PRECISION);
- ConvexArea b = ConvexArea.convexPolygonFromVertices(
- Arrays.asList(Vector2D.ZERO, Vector2D.of(1, 1).normalize(), Vector2D.of(0, 1)), TEST_PRECISION);
- ConvexArea c = ConvexArea.convexPolygonFromVertices(
- Arrays.asList(Vector2D.Unit.PLUS_X, Vector2D.of(1, 1), Vector2D.Unit.PLUS_Y), TEST_PRECISION);
-
- EmbeddingPlane closePlane = Planes.fromPointAndPlaneVectors(
- Vector3D.of(1e-16, 0, 1), Vector3D.of(1, 1e-16, 0), Vector3D.Unit.PLUS_Y, TEST_PRECISION);
-
- // act
- HyperplaneSubset.Builder<Vector3D> builder = mainPlane.span().builder();
-
- builder.add(new EmbeddedTreePlaneSubset(closePlane, c.toTree()));
- builder.add(Planes.subsetFromConvexArea(closePlane, a));
- builder.add(Planes.subsetFromConvexArea(closePlane, b));
-
- PlaneSubset result = (PlaneSubset) builder.build();
-
- // assert
- Assert.assertFalse(result.isFull());
- Assert.assertFalse(result.isEmpty());
- Assert.assertTrue(result.isFinite());
- Assert.assertFalse(result.isInfinite());
-
- checkPoints(result, RegionLocation.INSIDE, Vector3D.of(0.5, 0.5, 1));
- checkPoints(result, RegionLocation.OUTSIDE,
- Vector3D.of(-1, 0.5, 1), Vector3D.of(2, 0.5, 1),
- Vector3D.of(0.5, -1, 1), Vector3D.of(0.5, 2, 1));
- checkPoints(result, RegionLocation.BOUNDARY,
- Vector3D.of(0, 0, 1), Vector3D.of(1, 0, 1),
- Vector3D.of(1, 1, 1), Vector3D.of(0, 1, 1));
- }
-
- @Test
- public void testBuilder_add_nullArguments() {
- // arrange
- HyperplaneSubset.Builder<Vector3D> builder = XY_PLANE.span().builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add((HyperplaneSubset<Vector3D>) null);
- }, NullPointerException.class, "Hyperplane subset must not be null");
-
- GeometryTestUtils.assertThrows(() -> {
- builder.add((HyperplaneConvexSubset<Vector3D>) null);
- }, NullPointerException.class, "Hyperplane subset must not be null");
- }
-
- @Test
- public void testBuilder_add_argumentsFromDifferentPlanes() {
- // arrange
- ConvexPolygon3D convex = Planes.convexPolygonFromVertices(Arrays.asList(
- Vector3D.ZERO,
- Vector3D.of(1, 0, 1),
- Vector3D.of(0, 1, 1)
- ), TEST_PRECISION);
-
- HyperplaneSubset.Builder<Vector3D> builder = XY_PLANE.span().builder();
-
- RegionBSPTree2D tree = RegionBSPTree2D.empty();
- tree.add(convex.getEmbedded().getSubspaceRegion());
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add(convex);
- }, IllegalArgumentException.class);
-
- GeometryTestUtils.assertThrows(() -> {
- builder.add(new EmbeddedTreePlaneSubset(convex.getPlane().getEmbedding(), tree));
- }, IllegalArgumentException.class);
- }
-
- @Test
- public void testBuilder_add_addUnknownType() {
- // arrange
- HyperplaneSubset.Builder<Vector3D> builder = XY_PLANE.span().builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add(new StubPlaneSubset(XY_PLANE));
- }, IllegalArgumentException.class);
- }
-
- private static void checkPoints(PlaneSubset ps, RegionLocation loc, Vector3D... pts) {
- for (Vector3D pt : pts) {
- Assert.assertEquals("Unexpected location for point " + pt, loc, ps.classify(pt));
- }
- }
-
- private static class StubPlaneSubset extends AbstractPlaneSubset {
-
- private final Plane plane;
-
- StubPlaneSubset(final Plane plane) {
- this.plane = plane;
- }
-
- @Override
- public Plane getPlane() {
- return plane;
- }
-
- @Override
- public List<PlaneConvexSubset> toConvex() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public List<Triangle3D> toTriangles() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isFull() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isEmpty() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public RegionLocation classify(Vector3D pt) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Vector3D closest(Vector3D pt) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public HyperplaneSubset<Vector3D> transform(Transform<Vector3D> transform) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Split<? extends HyperplaneSubset<Vector3D>> split(Hyperplane<Vector3D> splitter) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public double getSize() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Vector3D getCentroid() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public PlaneSubset.Embedded getEmbedded() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Bounds3D getBounds() {
- throw new UnsupportedOperationException();
- }
- }
-}
diff --git a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/threed/shape/SphereTest.java b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/threed/shape/SphereTest.java
index 6d810e1..466dcd6 100644
--- a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/threed/shape/SphereTest.java
+++ b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/threed/shape/SphereTest.java
@@ -18,6 +18,9 @@ package org.apache.commons.geometry.euclidean.threed.shape;
import java.io.IOException;
import java.util.List;
+import java.util.function.DoubleSupplier;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.apache.commons.geometry.core.GeometryTestUtils;
import org.apache.commons.geometry.core.RegionLocation;
@@ -27,12 +30,15 @@ import org.apache.commons.geometry.euclidean.EuclideanTestUtils;
import org.apache.commons.geometry.euclidean.threed.PlaneConvexSubset;
import org.apache.commons.geometry.euclidean.threed.RegionBSPTree3D;
import org.apache.commons.geometry.euclidean.threed.SphericalCoordinates;
+import org.apache.commons.geometry.euclidean.threed.Triangle3D;
import org.apache.commons.geometry.euclidean.threed.Vector3D;
import org.apache.commons.geometry.euclidean.threed.line.Line3D;
import org.apache.commons.geometry.euclidean.threed.line.LineConvexSubset3D;
import org.apache.commons.geometry.euclidean.threed.line.LinecastPoint3D;
import org.apache.commons.geometry.euclidean.threed.line.Lines3D;
import org.apache.commons.numbers.angle.PlaneAngleRadians;
+import org.apache.commons.rng.UniformRandomProvider;
+import org.apache.commons.rng.simple.RandomSource;
import org.junit.Assert;
import org.junit.Test;
@@ -284,31 +290,55 @@ public class SphereTest {
}
@Test
- public void testToTree_smallestNumberOfPlanes() throws IOException {
+ public void testToTree_zeroSubdivisions() throws IOException {
// arrange
double r = 2;
Sphere s = Sphere.from(Vector3D.of(2, 1, 3), r, TEST_PRECISION);
// act
- RegionBSPTree3D tree = s.toTree(2, 3);
+ RegionBSPTree3D tree = s.toTree(0);
// assert
checkBasicApproximationProperties(s, tree);
List<PlaneConvexSubset> boundaries = tree.getBoundaries();
- Assert.assertEquals(6, boundaries.size());
+ Assert.assertEquals(8, boundaries.size());
- double expectedSize = 0.5 * Math.sqrt(3) * (r * r * r);
+ List<Triangle3D> triangles = tree.triangleStream().collect(Collectors.toList());
+ Assert.assertEquals(8, triangles.size());
+
+ double expectedSize = (4.0 / 3.0) * r * r * r;
Assert.assertEquals(expectedSize, tree.getSize(), TEST_EPS);
}
@Test
- public void testToTree_multipleApproximationSizes() throws Exception {
+ public void testToTree_oneSubdivision() throws IOException {
+ // arrange
+ double r = 2;
+ Sphere s = Sphere.from(Vector3D.of(2, 1, 3), r, TEST_PRECISION);
+
+ // act
+ RegionBSPTree3D tree = s.toTree(1);
+
+ // assert
+ checkBasicApproximationProperties(s, tree);
+
+ List<PlaneConvexSubset> boundaries = tree.getBoundaries();
+ Assert.assertEquals(32, boundaries.size());
+
+ List<Triangle3D> triangles = tree.triangleStream().collect(Collectors.toList());
+ Assert.assertEquals(32, triangles.size());
+
+ Assert.assertTrue(tree.getSize() <= s.getSize());
+ }
+
+ @Test
+ public void testToTree_multipleSubdivisionCounts() throws Exception {
// -- arrange
Sphere s = Sphere.from(Vector3D.of(-3, 5, 1), 10, TEST_PRECISION);
- int min = 4;
- int max = 50;
+ int min = 0;
+ int max = 5;
RegionBSPTree3D tree;
@@ -317,11 +347,18 @@ public class SphereTest {
for (int n = min; n <= max; ++n) {
// -- act
- tree = s.toTree(n, n);
+ tree = s.toTree(n);
// -- assert
checkBasicApproximationProperties(s, tree);
+ int expectedTriangles = (int) (8 * Math.pow(4, n));
+ List<PlaneConvexSubset> boundaries = tree.getBoundaries();
+ Assert.assertEquals(expectedTriangles, boundaries.size());
+
+ List<Triangle3D> triangles = tree.triangleStream().collect(Collectors.toList());
+ Assert.assertEquals(expectedTriangles, triangles.size());
+
// check that we get closer and closer to the correct size as we add more segments
sizeDiff = s.getSize() - tree.getSize();
Assert.assertTrue("Expected size difference to decrease: n= " +
@@ -332,57 +369,90 @@ public class SphereTest {
}
@Test
+ public void testToTree_randomSpheres() {
+ // arrange
+ UniformRandomProvider rand = RandomSource.create(RandomSource.XO_RO_SHI_RO_128_PP, 1L);
+ DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-10);
+ double min = 1e-1;
+ double max = 1e2;
+
+ DoubleSupplier randDouble = () -> (rand.nextDouble() * (max - min)) + min;
+
+ int count = 10;
+ for (int i = 0; i < count; ++i) {
+ Vector3D center = Vector3D.of(
+ randDouble.getAsDouble(),
+ randDouble.getAsDouble(),
+ randDouble.getAsDouble());
+
+ double radius = randDouble.getAsDouble();
+ Sphere sphere = Sphere.from(center, radius, precision);
+
+ for (int s = 0; s < 7; ++s) {
+ // act
+ RegionBSPTree3D tree = sphere.toTree(s);
+
+ // assert
+ Assert.assertEquals((int)(8 * Math.pow(4, s)), tree.getBoundaries().size());
+ Assert.assertTrue(tree.isFinite());
+ Assert.assertFalse(tree.isEmpty());
+ Assert.assertTrue(tree.getSize() < sphere.getSize());
+ }
+ }
+ }
+
+ @Test
public void testToTree_closeApproximation() throws IOException {
// arrange
- Sphere s = Sphere.from(Vector3D.of(0, -1, 2), 1, TEST_PRECISION);
+ Sphere s = Sphere.from(Vector3D.ZERO, 1, TEST_PRECISION);
// act
- RegionBSPTree3D tree = s.toTree(25, 40);
+ RegionBSPTree3D tree = s.toTree(8);
// assert
checkBasicApproximationProperties(s, tree);
- double eps = 0.1;
+ double eps = 1e-3;
+ Assert.assertTrue(tree.isFinite());
Assert.assertEquals(s.getSize(), tree.getSize(), eps);
Assert.assertEquals(s.getBoundarySize(), tree.getBoundarySize(), eps);
EuclideanTestUtils.assertCoordinatesEqual(s.getCentroid(), tree.getCentroid(), eps);
}
@Test
- public void testToTree_invalidArgs() {
+ public void testToTree_subdivideFails() {
// arrange
- Sphere s = Sphere.from(Vector3D.of(2, 1, 3), 2, TEST_PRECISION);
- String baseStackMsg = "Sphere approximation stack number must be greater than or equal to 2; was ";
- String baseSliceMsg = "Sphere approximation slice number must be greater than or equal to 3; was ";
+ DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-5);
+ Sphere s = Sphere.from(Vector3D.ZERO, 1, precision);
// act/assert
GeometryTestUtils.assertThrows(() -> {
- s.toTree(1, 10);
- }, IllegalArgumentException.class, baseStackMsg + "1");
- GeometryTestUtils.assertThrows(() -> {
- s.toTree(-1, 10);
- }, IllegalArgumentException.class, baseStackMsg + "-1");
- GeometryTestUtils.assertThrows(() -> {
- s.toTree(0, -1);
- }, IllegalArgumentException.class, baseStackMsg + "0");
+ s.toTree(6);
+ }, IllegalStateException.class,
+ Pattern.compile("^Failed to construct sphere approximation with subdivision count 6:.*"));
+ }
+ @Test
+ public void testToTree_invalidArgs() {
+ // arrange
+ Sphere s = Sphere.from(Vector3D.of(2, 1, 3), 2, TEST_PRECISION);
+
+ // act/assert
GeometryTestUtils.assertThrows(() -> {
- s.toTree(2, 2);
- }, IllegalArgumentException.class, baseSliceMsg + "2");
- GeometryTestUtils.assertThrows(() -> {
- s.toTree(4, -1);
- }, IllegalArgumentException.class, baseSliceMsg + "-1");
+ s.toTree(-1);
+ }, IllegalArgumentException.class,
+ "Number of sphere approximation subdivisions must be greater than or equal to zero; was -1");
}
@Test
public void testHashCode() {
// arrange
- DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-2);
+ DoublePrecisionContext otherPrecision = new EpsilonDoublePrecisionContext(1e-2);
Sphere a = Sphere.from(Vector3D.of(1, 2, 3), 3, TEST_PRECISION);
Sphere b = Sphere.from(Vector3D.of(1, 1, 3), 3, TEST_PRECISION);
Sphere c = Sphere.from(Vector3D.of(1, 2, 3), 4, TEST_PRECISION);
- Sphere d = Sphere.from(Vector3D.of(1, 2, 3), 3, precision);
+ Sphere d = Sphere.from(Vector3D.of(1, 2, 3), 3, otherPrecision);
Sphere e = Sphere.from(Vector3D.of(1, 2, 3), 3, TEST_PRECISION);
// act
@@ -509,6 +579,8 @@ public class SphereTest {
private static void checkBasicApproximationProperties(Sphere s, RegionBSPTree3D tree) {
Assert.assertFalse(tree.isFull());
Assert.assertFalse(tree.isEmpty());
+ Assert.assertTrue(tree.isFinite());
+ Assert.assertFalse(tree.isInfinite());
// volume must be less than the sphere
Assert.assertTrue("Expected approximation volume to be less than circle", tree.getSize() < s.getSize());
diff --git a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/ConvexAreaTest.java b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/ConvexAreaTest.java
index dc68d0d..5f7973b 100644
--- a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/ConvexAreaTest.java
+++ b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/ConvexAreaTest.java
@@ -312,6 +312,35 @@ public class ConvexAreaTest {
}
@Test
+ public void testGetVertices_mismatchedEndpoints() {
+ // This test checks the case where we have a valid set of boundary segments but
+ // with a small mismatch in the endpoints of some of the segments (possibly due
+ // to floating point errors).
+
+ // arrange
+ DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-2);
+
+ Vector2D p1 = Vector2D.ZERO;
+ Vector2D p2 = Vector2D.of(0.99, 0);
+ Vector2D p3 = Vector2D.of(1, 0.002);
+ Vector2D p4 = Vector2D.of(0.995, -0.001);
+ Vector2D p5 = Vector2D.of(1, 1);
+
+ ConvexArea area = new ConvexArea(Arrays.asList(
+ Lines.segmentFromPoints(p1, p2, precision),
+ Lines.segmentFromPoints(p2, p3, precision),
+ Lines.segmentFromPoints(p4, p5, precision),
+ Lines.segmentFromPoints(p5, p1, precision)
+ ));
+
+ // act
+ List<Vector2D> vertices = area.getVertices();
+
+ // assert
+ Assert.assertEquals(Arrays.asList(p1, p2, p3, p5), vertices);
+ }
+
+ @Test
public void testGetBounds_infinite() {
// act/assert
Assert.assertNull(ConvexArea.full().getBounds());
@@ -728,6 +757,46 @@ public class ConvexAreaTest {
}
@Test
+ public void testSplit_trimmedSplitterDiscrepancy() {
+ // The following example came from a failed invocation of the Sphere.toTree() method.
+ // This test checks the case where the splitter trimmed to the area is non-empty but
+ // the boundaries split by the splitter all lies on a single side.
+
+ // arrange
+ DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-10);
+
+ Vector2D p1 = Vector2D.of(-100.27622744776312, -39.236143934478704);
+ Vector2D p2 = Vector2D.of(-100.23149336840831, -39.28090397981739);
+ Vector2D p3 = Vector2D.of(-96.28607710958399, -39.25486984391497);
+ ConvexArea area = ConvexArea.fromBounds(
+ Lines.fromPointAndDirection(p1, Vector2D.of(-0.00601644753700725, -0.9999819010157307), precision),
+ Lines.fromPoints(p1, p2, precision),
+ Lines.fromPoints(p2, p3, precision),
+ Lines.fromPointAndDirection(p3, Vector2D.of(0.9999648811047153, 0.008380725340508379), precision)
+ );
+
+ Line splitter = Lines.fromPointAndDirection(
+ Vector2D.of(-68.9981806624852, -70.04669274578112),
+ Vector2D.of(0.7124186895479748, -0.7017546656651072),
+ precision);
+
+ // act
+ Split<ConvexArea> minusSplit = area.split(splitter);
+ Split<ConvexArea> plusSplit = area.split(splitter.reverse());
+
+ // assert
+ Assert.assertEquals(SplitLocation.MINUS, minusSplit.getLocation());
+
+ Assert.assertSame(area, minusSplit.getMinus());
+ Assert.assertNull(minusSplit.getPlus());
+
+ Assert.assertEquals(SplitLocation.PLUS, plusSplit.getLocation());
+
+ Assert.assertNull(plusSplit.getMinus());
+ Assert.assertSame(area, plusSplit.getPlus());
+ }
+
+ @Test
public void testLinecast_full() {
// arrange
ConvexArea area = ConvexArea.full();
diff --git a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/LineSubsetTest.java b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/LineSubsetTest.java
index 94157ab..292ac7c 100644
--- a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/LineSubsetTest.java
+++ b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/LineSubsetTest.java
@@ -16,23 +16,10 @@
*/
package org.apache.commons.geometry.euclidean.twod;
-import java.util.List;
-
-import org.apache.commons.geometry.core.GeometryTestUtils;
-import org.apache.commons.geometry.core.RegionLocation;
-import org.apache.commons.geometry.core.Transform;
-import org.apache.commons.geometry.core.partitioning.Hyperplane;
-import org.apache.commons.geometry.core.partitioning.HyperplaneBoundedRegion;
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
-import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
import org.apache.commons.geometry.core.precision.EpsilonDoublePrecisionContext;
import org.apache.commons.geometry.euclidean.EuclideanTestUtils;
-import org.apache.commons.geometry.euclidean.oned.Interval;
-import org.apache.commons.geometry.euclidean.oned.RegionBSPTree1D;
import org.apache.commons.geometry.euclidean.oned.Vector1D;
-import org.junit.Assert;
import org.junit.Test;
public class LineSubsetTest {
@@ -52,282 +39,4 @@ public class LineSubsetTest {
EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(2, 1), subset.toSpace(Vector1D.of(2)), TEST_EPS);
EuclideanTestUtils.assertCoordinatesEqual(Vector1D.of(2), subset.toSubspace(Vector2D.of(2, 1)), TEST_EPS);
}
-
- @Test
- public void testBuilder_empty() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- // act
- LineSubset subset = (LineSubset) builder.build();
-
- // assert
- Assert.assertFalse(subset.isFull());
- Assert.assertTrue(subset.isEmpty());
-
- List<LineConvexSubset> segments = subset.toConvex();
- Assert.assertEquals(0, segments.size());
- }
-
- @Test
- public void testBuilder_addSingleConvex_usesSameInstance() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
- LineConvexSubset convex = Lines.subsetFromInterval(line, 2, 4);
-
- // act
- builder.add(convex);
-
- LineSubset subset = (LineSubset) builder.build();
-
- // assert
- Assert.assertSame(convex, subset);
- }
-
- @Test
- public void testBuilder_addConvex() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
- Line otherLine = Lines.fromPointAndAngle(Vector2D.of(0, 1), 1e-11, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- // act
- builder.add(Lines.subsetFromInterval(line, 2, 4));
- builder.add(Lines.subsetFromInterval(otherLine, 1, 3));
- builder.add(Lines.segmentFromPoints(Vector2D.of(-4, 1), Vector2D.of(-1, 1), TEST_PRECISION));
-
- LineSubset subset = (LineSubset) builder.build();
-
- // assert
- Assert.assertFalse(subset.isFull());
- Assert.assertFalse(subset.isEmpty());
-
- List<LineConvexSubset> segments = subset.toConvex();
- Assert.assertEquals(2, segments.size());
-
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(-4, 1), segments.get(0).getStartPoint(), TEST_EPS);
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(-1, 1), segments.get(0).getEndPoint(), TEST_EPS);
-
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(1, 1), segments.get(1).getStartPoint(), TEST_EPS);
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(4, 1), segments.get(1).getEndPoint(), TEST_EPS);
- }
-
- @Test
- public void testBuilder_addTreeSubset() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
-
- EmbeddedTreeLineSubset a = new EmbeddedTreeLineSubset(line);
- RegionBSPTree1D aTree = a.getSubspaceRegion();
- aTree.add(Interval.max(-3, TEST_PRECISION));
- aTree.add(Interval.of(1, 2, TEST_PRECISION));
-
- EmbeddedTreeLineSubset b = new EmbeddedTreeLineSubset(line);
- RegionBSPTree1D bTree = b.getSubspaceRegion();
- bTree.add(Interval.of(2, 4, TEST_PRECISION));
- bTree.add(Interval.of(-4, -2, TEST_PRECISION));
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- int aTreeCount = aTree.count();
- int bTreeCount = bTree.count();
-
- // act
- builder.add(a);
- builder.add(b);
-
- LineSubset subset = (LineSubset) builder.build();
-
- // assert
- Assert.assertFalse(subset.isFull());
- Assert.assertFalse(subset.isEmpty());
-
- List<LineConvexSubset> segments = subset.toConvex();
-
- Assert.assertEquals(2, segments.size());
-
- Assert.assertNull(segments.get(0).getStartPoint());
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(-2, 1), segments.get(0).getEndPoint(), TEST_EPS);
-
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(1, 1), segments.get(1).getStartPoint(), TEST_EPS);
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(4, 1), segments.get(1).getEndPoint(), TEST_EPS);
-
- Assert.assertEquals(aTreeCount, aTree.count());
- Assert.assertEquals(bTreeCount, bTree.count());
- }
-
- @Test
- public void testBuilder_addMixed_convexFirst() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
- Line otherLine = Lines.fromPointAndAngle(Vector2D.of(0, 1), 1e-11, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- // act
- builder.add(Lines.subsetFromInterval(line, 2, 4));
-
- EmbeddedTreeLineSubset treeSubset = new EmbeddedTreeLineSubset(otherLine);
- treeSubset.add(Lines.subsetFromInterval(otherLine, 1, 3));
- builder.add(treeSubset);
-
- LineSubset subset = (LineSubset) builder.build();
-
- // assert
- Assert.assertFalse(subset.isFull());
- Assert.assertFalse(subset.isEmpty());
-
- List<LineConvexSubset> segments = subset.toConvex();
- Assert.assertEquals(1, segments.size());
-
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(1, 1), segments.get(0).getStartPoint(), TEST_EPS);
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(4, 1), segments.get(0).getEndPoint(), TEST_EPS);
- }
-
- @Test
- public void testBuilder_addMixed_treeSubsetFirst() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
- Line otherLine = Lines.fromPointAndAngle(Vector2D.of(0, 1), 1e-11, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- // act
- EmbeddedTreeLineSubset treeSubset = new EmbeddedTreeLineSubset(otherLine);
- treeSubset.add(Lines.subsetFromInterval(otherLine, 1, 3));
- builder.add(treeSubset);
-
- builder.add(Lines.subsetFromInterval(line, 2, 4));
-
- LineSubset subset = (LineSubset) builder.build();
-
- // assert
- Assert.assertFalse(subset.isFull());
- Assert.assertFalse(subset.isEmpty());
-
- List<LineConvexSubset> segments = subset.toConvex();
- Assert.assertEquals(1, segments.size());
-
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(1, 1), segments.get(0).getStartPoint(), TEST_EPS);
- EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(4, 1), segments.get(0).getEndPoint(), TEST_EPS);
- }
-
- @Test
- public void testBuilder_nullArgs() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add((HyperplaneSubset<Vector2D>) null);
- }, NullPointerException.class, "Hyperplane subset must not be null");
-
- GeometryTestUtils.assertThrows(() -> {
- builder.add((HyperplaneConvexSubset<Vector2D>) null);
- }, NullPointerException.class, "Hyperplane subset must not be null");
- }
-
- @Test
- public void testBuilder_argumentsFromDifferentLine() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
- Line otherLine = Lines.fromPointAndAngle(Vector2D.of(0, 1), 1e-2, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add(Lines.subsetFromInterval(otherLine, 0, 1));
- }, IllegalArgumentException.class);
-
- GeometryTestUtils.assertThrows(() -> {
- builder.add(new EmbeddedTreeLineSubset(otherLine));
- }, IllegalArgumentException.class);
- }
-
- @Test
- public void testBuilder_unknownSubsetType() {
- // arrange
- Line line = Lines.fromPointAndAngle(Vector2D.of(0, 1), 0.0, TEST_PRECISION);
-
- LineSubset unknownType = new LineSubset(line) {
- @Override
- public boolean isInfinite() {
- return false;
- }
-
- @Override
- public boolean isFinite() {
- return true;
- }
-
- @Override
- public List<LineConvexSubset> toConvex() {
- return null;
- }
-
- @Override
- public HyperplaneBoundedRegion<Vector1D> getSubspaceRegion() {
- return null;
- }
-
- @Override
- public Split<? extends HyperplaneSubset<Vector2D>> split(Hyperplane<Vector2D> splitter) {
- return null;
- }
-
- @Override
- public HyperplaneSubset<Vector2D> transform(Transform<Vector2D> transform) {
- return null;
- }
-
- @Override
- public Vector2D closest(Vector2D point) {
- return null;
- }
-
- @Override
- public boolean isFull() {
- return false;
- }
-
- @Override
- public boolean isEmpty() {
- return false;
- }
-
- @Override
- public double getSize() {
- return 0;
- }
-
- @Override
- public Vector2D getCentroid() {
- return null;
- }
-
- @Override
- public Bounds2D getBounds() {
- return null;
- }
-
- @Override
- RegionLocation classifyAbscissa(double abscissa) {
- return null;
- }
- };
-
- HyperplaneSubset.Builder<Vector2D> builder = line.span().builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add(unknownType);
- }, IllegalArgumentException.class);
- }
}
diff --git a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2DTest.java b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2DTest.java
index 4db2834..f621a48 100644
--- a/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2DTest.java
+++ b/commons-geometry-euclidean/src/test/java/org/apache/commons/geometry/euclidean/twod/RegionBSPTree2DTest.java
@@ -845,25 +845,11 @@ public class RegionBSPTree2DTest {
Assert.assertEquals(16, tree.getBoundarySize(), TEST_EPS);
- List<LineConvexSubset> segments = new ArrayList<>(tree.getBoundaries());
- Collections.sort(segments, SEGMENT_COMPARATOR);
-
- Assert.assertEquals(8, segments.size());
-
- checkFiniteSegment(segments.get(0), Vector2D.ZERO, Vector2D.of(3, 0));
- checkFiniteSegment(segments.get(1), Vector2D.of(0, 3), Vector2D.ZERO);
- checkFiniteSegment(segments.get(2), Vector2D.of(1, 1), Vector2D.of(1, 2));
- checkFiniteSegment(segments.get(3), Vector2D.of(1, 2), Vector2D.of(2, 2));
- checkFiniteSegment(segments.get(4), Vector2D.of(2, 1), Vector2D.of(1, 1));
- checkFiniteSegment(segments.get(5), Vector2D.of(2, 2), Vector2D.of(2, 1));
- checkFiniteSegment(segments.get(6), Vector2D.of(3, 0), Vector2D.of(3, 3));
- checkFiniteSegment(segments.get(7), Vector2D.of(3, 3), Vector2D.of(0, 3));
-
List<LinePath> paths = tree.getBoundaryPaths();
Assert.assertEquals(2, paths.size());
- checkVertices(paths.get(0), Vector2D.ZERO, Vector2D.of(3, 0), Vector2D.of(3, 3),
- Vector2D.of(0, 3), Vector2D.ZERO);
+ checkVertices(paths.get(0), Vector2D.of(0, 3), Vector2D.ZERO, Vector2D.of(3, 0),
+ Vector2D.of(3, 3), Vector2D.of(0, 3));
checkVertices(paths.get(1), Vector2D.of(1, 1), Vector2D.of(1, 2), Vector2D.of(2, 2),
Vector2D.of(2, 1), Vector2D.of(1, 1));
}
@@ -886,20 +872,6 @@ public class RegionBSPTree2DTest {
Assert.assertEquals(16, tree.getBoundarySize(), TEST_EPS);
- List<LineConvexSubset> segments = new ArrayList<>(tree.getBoundaries());
- Collections.sort(segments, SEGMENT_COMPARATOR);
-
- Assert.assertEquals(8, segments.size());
-
- checkFiniteSegment(segments.get(0), Vector2D.ZERO, Vector2D.of(0, 3));
- checkFiniteSegment(segments.get(1), Vector2D.of(0, 3), Vector2D.of(3, 3));
- checkFiniteSegment(segments.get(2), Vector2D.of(1, 1), Vector2D.of(2, 1));
- checkFiniteSegment(segments.get(3), Vector2D.of(1, 2), Vector2D.of(1, 1));
- checkFiniteSegment(segments.get(4), Vector2D.of(2, 1), Vector2D.of(2, 2));
- checkFiniteSegment(segments.get(5), Vector2D.of(2, 2), Vector2D.of(1, 2));
- checkFiniteSegment(segments.get(6), Vector2D.of(3, 0), Vector2D.ZERO);
- checkFiniteSegment(segments.get(7), Vector2D.of(3, 3), Vector2D.of(3, 0));
-
List<LinePath> paths = tree.getBoundaryPaths();
Assert.assertEquals(2, paths.size());
diff --git a/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/RegionBSPTree3DPerformance.java b/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/RegionBSPTree3DPerformance.java
index 6bd9dc3..c0ddafa 100644
--- a/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/RegionBSPTree3DPerformance.java
+++ b/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/RegionBSPTree3DPerformance.java
@@ -51,18 +51,18 @@ public class RegionBSPTree3DPerformance {
@State(Scope.Thread)
public static class SphericalBoundaryInputBase {
- /** The input to use for the stacks and slices parameters when generating the
+ /** The input to use for the subdivisions parameter when generating the
* sphere boundaries.
*/
- @Param({"5", "10", "15"})
- private int stacksSlices;
+ @Param({"2", "3", "4"})
+ private int subdivisions;
/** Compute the boundaries for the instance.
* @return the boundaries for the instance.
*/
protected List<PlaneConvexSubset> computeBoundaries() {
final Sphere sphere = Sphere.from(Vector3D.ZERO, 1, new EpsilonDoublePrecisionContext(1e-10));
- return sphere.toTree(stacksSlices, stacksSlices).getBoundaries();
+ return sphere.toTree(subdivisions).getBoundaries();
}
}
diff --git a/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/SpherePerformance.java b/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/SpherePerformance.java
index 059aac3..ff0ac31 100644
--- a/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/SpherePerformance.java
+++ b/commons-geometry-examples/examples-jmh/src/main/java/org/apache/commons/geometry/examples/jmh/euclidean/SpherePerformance.java
@@ -53,7 +53,7 @@ public class SpherePerformance {
private static final double MIN_VALUE = 1e-1;
/** Maximum value for random doubles. */
- private static final double MAX_VALUE = 1e-100;
+ private static final double MAX_VALUE = 1e2;
/** Benchmark input providing a source of random {@link Sphere} instances.
*/
@@ -77,20 +77,20 @@ public class SpherePerformance {
}
}
- /** Class defining input values to the {@link Sphere#toTree(int, int)} method.
+ /** Class defining input values to the {@link Sphere#toTree(int)} method.
*/
@State(Scope.Thread)
public static class ToTreeInput {
- /** The number of "stacks" and "slices" in the sphere approximation. */
- @Param({"10", "25", "50"})
- private int size;
+ /** The number of subdivisions in the sphere approximation. */
+ @Param({"3", "4", "5"})
+ private int subdivisions;
- /** Get the number of stacks and slices to use for the sphere approximation.
- * @return the number of stacks and slices to use for the sphere approximation
+ /** Get the number of subdivisions to use for the sphere approximation.
+ * @return the number of subdivisions to use for the sphere approximation
*/
- public int getSize() {
- return size;
+ public int getSubdivisions() {
+ return subdivisions;
}
}
@@ -107,7 +107,7 @@ public class SpherePerformance {
public void setup() {
final Sphere sphere = randomSphere(RandomSource.create(RandomSource.XO_RO_SHI_RO_128_PP));
- tree = sphere.toTree(getSize(), getSize());
+ tree = sphere.toTree(getSubdivisions());
}
/** Get the computed bsp tree sphere approximation.
@@ -138,7 +138,7 @@ public class SpherePerformance {
return (rand.nextDouble() * (MAX_VALUE - MIN_VALUE)) + MIN_VALUE;
}
- /** Benchmark testing the performance of the {@link Sphere#toTree(int, int)} method.
+ /** Benchmark testing the performance of the {@link Sphere#toTree(int)} method.
* @param randomSphere sphere input
* @param toTreeInput toTree input parameters
* @return created bsp tree
@@ -146,13 +146,13 @@ public class SpherePerformance {
@Benchmark
public RegionBSPTree3D toTreeCreation(final RandomSphere randomSphere, final ToTreeInput toTreeInput) {
final Sphere sphere = randomSphere.getSphere();
- final int size = toTreeInput.getSize();
+ final int subdivisions = toTreeInput.getSubdivisions();
- return sphere.toTree(size, size);
+ return sphere.toTree(subdivisions);
}
/** Benchmark testing the performance of the computation of the size of the bsp trees
- * created by the {@link Sphere#toTree(int, int)} method.
+ * created by the {@link Sphere#toTree(int)} method.
* @param toTreeInstance bsp tree sphere approximation instance
* @return the size (volume) of the region represented by the tree
*/
diff --git a/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/oned/CutAngle.java b/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/oned/CutAngle.java
index f771e01..39079fb 100644
--- a/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/oned/CutAngle.java
+++ b/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/oned/CutAngle.java
@@ -26,7 +26,6 @@ import org.apache.commons.geometry.core.partitioning.AbstractHyperplane;
import org.apache.commons.geometry.core.partitioning.Hyperplane;
import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneLocation;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
@@ -362,12 +361,6 @@ public final class CutAngle extends AbstractHyperplane<Point1S> {
/** {@inheritDoc} */
@Override
- public CutAngleSubsetBuilder builder() {
- return new CutAngleSubsetBuilder(this);
- }
-
- /** {@inheritDoc} */
- @Override
public CutAngleConvexSubset reverse() {
return new CutAngleConvexSubset(hyperplane.reverse());
}
@@ -384,66 +377,4 @@ public final class CutAngle extends AbstractHyperplane<Point1S> {
return sb.toString();
}
}
-
- /** {@link HyperplaneSubset.Builder} implementation for spherical 1D space. This is effectively
- * a stub implementation since there are no subspaces of 1D space. Its primary use is to allow
- * for the correct functioning of partitioning code.
- */
- private static final class CutAngleSubsetBuilder implements HyperplaneSubset.Builder<Point1S> {
- /** Base hyperplane subset for the builder. */
- private final CutAngleConvexSubset base;
-
- /** Construct a new instance using the given base hyperplane subset.
- * @param base base hyperplane subset for the instance
- */
- CutAngleSubsetBuilder(final CutAngleConvexSubset base) {
- this.base = base;
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneSubset<Point1S> sub) {
- validateHyperplane(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneConvexSubset<Point1S> sub) {
- validateHyperplane(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public CutAngleConvexSubset build() {
- return base;
- }
-
- /** {@inheritDoc} */
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder();
- sb.append(this.getClass().getSimpleName())
- .append("[base= ")
- .append(base)
- .append(']');
-
- return sb.toString();
- }
-
- /** Validate that the given hyperplane subset lies on the same hyperplane subset as this instance.
- * @param sub hyperplane subset to validate
- * @throws IllegalArgumentException if the argument is not on the same hyperplane
- * as the instance
- */
- private void validateHyperplane(final HyperplaneSubset<Point1S> sub) {
- final CutAngle baseHyper = base.getHyperplane();
- final CutAngle inputHyper = (CutAngle) sub.getHyperplane();
-
- if (!baseHyper.eq(inputHyper, baseHyper.getPrecision())) {
- throw new IllegalArgumentException("Argument is not on the same " +
- "hyperplane. Expected " + baseHyper + " but was " +
- inputHyper);
- }
- }
- }
}
diff --git a/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/twod/GreatCircleSubset.java b/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/twod/GreatCircleSubset.java
index 1c5800f..b4d74eb 100644
--- a/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/twod/GreatCircleSubset.java
+++ b/commons-geometry-spherical/src/main/java/org/apache/commons/geometry/spherical/twod/GreatCircleSubset.java
@@ -17,13 +17,11 @@
package org.apache.commons.geometry.spherical.twod;
import java.util.List;
-import java.util.Objects;
import org.apache.commons.geometry.core.RegionEmbedding;
import org.apache.commons.geometry.core.RegionLocation;
import org.apache.commons.geometry.core.internal.HyperplaneSubsets;
import org.apache.commons.geometry.core.partitioning.HyperplaneBoundedRegion;
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
import org.apache.commons.geometry.spherical.oned.Point1S;
@@ -116,12 +114,6 @@ public abstract class GreatCircleSubset implements HyperplaneSubset<Point2S>, Re
@Override
public abstract HyperplaneBoundedRegion<Point1S> getSubspaceRegion();
- /** {@inheritDoc} */
- @Override
- public HyperplaneSubset.Builder<Point2S> builder() {
- return new Builder(circle);
- }
-
/** Return the object used to perform floating point comparisons, which is the
* same object used by the underlying {@link GreatCircle}.
* @return precision object used to perform floating point comparisons.
@@ -129,103 +121,4 @@ public abstract class GreatCircleSubset implements HyperplaneSubset<Point2S>, Re
public DoublePrecisionContext getPrecision() {
return circle.getPrecision();
}
-
- /** Internal implementation of the {@link HyperplaneSubset.Builder} interface. In cases where only a single
- * convex subset is given to the builder, this class returns the convex subset instance directly. In all other
- * cases, an {@link EmbeddedTreeGreatCircleSubset} is used to construct the final subset.
- */
- private static final class Builder implements HyperplaneSubset.Builder<Point2S> {
- /** Great circle that a subset is being constructed for. */
- private final GreatCircle circle;
-
- /** Embedded tree subset. */
- private EmbeddedTreeGreatCircleSubset treeSubset;
-
- /** Convex subset added as the first subset to the builder. This is returned directly if
- * no other subsets are added.
- */
- private GreatArc convexSubset;
-
- /** Create a new subset builder for the given great circle.
- * @param circle great circle to build a subset for
- */
- Builder(final GreatCircle circle) {
- this.circle = circle;
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneSubset<Point2S> sub) {
- addInternal(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public void add(final HyperplaneConvexSubset<Point2S> sub) {
- addInternal(sub);
- }
-
- /** {@inheritDoc} */
- @Override
- public GreatCircleSubset build() {
- // return the convex subset directly if that was all we were given
- if (convexSubset != null) {
- return convexSubset;
- }
- return getTreeSubset();
- }
-
- /** Internal method for adding hyperplane subsets to this builder.
- * @param sub the hyperplane subset to add; may be either convex or non-convex
- */
- private void addInternal(final HyperplaneSubset<Point2S> sub) {
- Objects.requireNonNull(sub, "Hyperplane subset must not be null");
-
- if (sub instanceof GreatArc) {
- addConvexSubset((GreatArc) sub);
- } else if (sub instanceof EmbeddedTreeGreatCircleSubset) {
- addTreeSubset((EmbeddedTreeGreatCircleSubset) sub);
- } else {
- throw new IllegalArgumentException("Unsupported hyperplane subset type: " + sub.getClass().getName());
- }
- }
-
- /** Add a convex subset to the builder.
- * @param convex convex subset to add
- */
- private void addConvexSubset(final GreatArc convex) {
- GreatCircles.validateGreatCirclesEquivalent(circle, convex.getCircle());
-
- if (treeSubset == null && convexSubset == null) {
- convexSubset = convex;
- } else {
- getTreeSubset().add(convex);
- }
- }
-
- /** Add an embedded tree subset to the builder.
- * @param tree embedded tree subset to add
- */
- private void addTreeSubset(final EmbeddedTreeGreatCircleSubset tree) {
- // no need to validate the line here since the add() method does that for us
- getTreeSubset().add(tree);
- }
-
- /** Get the tree subset for the builder, creating it if needed.
- * @return the tree subset for the builder
- */
- private EmbeddedTreeGreatCircleSubset getTreeSubset() {
- if (treeSubset == null) {
- treeSubset = new EmbeddedTreeGreatCircleSubset(circle);
-
- if (convexSubset != null) {
- treeSubset.add(convexSubset);
-
- convexSubset = null;
- }
- }
-
- return treeSubset;
- }
- }
}
diff --git a/commons-geometry-spherical/src/test/java/org/apache/commons/geometry/spherical/oned/CutAngleTest.java b/commons-geometry-spherical/src/test/java/org/apache/commons/geometry/spherical/oned/CutAngleTest.java
index 901fc87..cd0dcb0 100644
--- a/commons-geometry-spherical/src/test/java/org/apache/commons/geometry/spherical/oned/CutAngleTest.java
+++ b/commons-geometry-spherical/src/test/java/org/apache/commons/geometry/spherical/oned/CutAngleTest.java
@@ -18,11 +18,9 @@ package org.apache.commons.geometry.spherical.oned;
import java.util.List;
-import org.apache.commons.geometry.core.GeometryTestUtils;
import org.apache.commons.geometry.core.RegionLocation;
import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
import org.apache.commons.geometry.core.partitioning.HyperplaneLocation;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
import org.apache.commons.geometry.core.partitioning.Split;
import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
import org.apache.commons.geometry.core.precision.EpsilonDoublePrecisionContext;
@@ -509,66 +507,6 @@ public class CutAngleTest {
Assert.assertTrue(str.contains("positiveFacing= "));
}
- @Test
- public void testBuilder() {
- // arrange
- DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-3);
-
- CutAngle pt = CutAngles.createPositiveFacing(0, precision);
- HyperplaneConvexSubset<Point1S> sub = pt.span();
-
- // act
- HyperplaneSubset.Builder<Point1S> builder = sub.builder();
-
- builder.add(sub);
- builder.add(CutAngles.createPositiveFacing(1e-4, precision).span());
- builder.add((HyperplaneSubset<Point1S>) sub);
-
- HyperplaneSubset<Point1S> result = builder.build();
-
- // assert
- Assert.assertSame(sub, result);
- }
-
- @Test
- public void testBuilder_invalidArgs() {
- // arrange
- DoublePrecisionContext precision = new EpsilonDoublePrecisionContext(1e-3);
-
- CutAngle pt = CutAngles.createPositiveFacing(0, precision);
- HyperplaneConvexSubset<Point1S> sub = pt.span();
-
- HyperplaneSubset.Builder<Point1S> builder = sub.builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(
- () -> builder.add(CutAngles.createPositiveFacing(2e-3, precision).span()),
- IllegalArgumentException.class);
- GeometryTestUtils.assertThrows(
- () -> builder.add(CutAngles.createNegativeFacing(2e-3, precision).span()),
- IllegalArgumentException.class);
-
- GeometryTestUtils.assertThrows(
- () -> builder.add((HyperplaneSubset<Point1S>) CutAngles.createPositiveFacing(2e-3, precision).span()),
- IllegalArgumentException.class);
- }
-
- @Test
- public void testBuilder_toString() {
- // arrange
- CutAngle pt = CutAngles.createPositiveFacing(2, TEST_PRECISION);
- HyperplaneSubset.Builder<Point1S> builder = pt.span().builder();
-
- // act
- String str = builder.toString();
-
- //assert
- Assert.assertTrue(str.contains("CutAngleSubsetBuilder["));
- Assert.assertTrue(str.contains("base= CutAngleConvexSubset["));
- Assert.assertTrue(str.contains("point= "));
- Assert.assertTrue(str.contains("positiveFacing= "));
- }
-
private static void checkCutAngle(CutAngle angle, double az, boolean positiveFacing) {
checkCutAngle(angle, az, positiveFacing, TEST_PRECISION);
}
diff --git a/commons-geometry-spherical/src/test/java/org/apache/commons/geometry/spherical/twod/GreatCircleSubsetTest.java b/commons-geometry-spherical/src/test/java/org/apache/commons/geometry/spherical/twod/GreatCircleSubsetTest.java
deleted file mode 100644
index 43de49f..0000000
--- a/commons-geometry-spherical/src/test/java/org/apache/commons/geometry/spherical/twod/GreatCircleSubsetTest.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.geometry.spherical.twod;
-
-import java.util.List;
-
-import org.apache.commons.geometry.core.GeometryTestUtils;
-import org.apache.commons.geometry.core.RegionLocation;
-import org.apache.commons.geometry.core.Transform;
-import org.apache.commons.geometry.core.partitioning.Hyperplane;
-import org.apache.commons.geometry.core.partitioning.HyperplaneConvexSubset;
-import org.apache.commons.geometry.core.partitioning.HyperplaneSubset;
-import org.apache.commons.geometry.core.partitioning.Split;
-import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
-import org.apache.commons.geometry.core.precision.EpsilonDoublePrecisionContext;
-import org.apache.commons.geometry.euclidean.threed.Vector3D;
-import org.apache.commons.geometry.spherical.SphericalTestUtils;
-import org.apache.commons.geometry.spherical.oned.AngularInterval;
-import org.apache.commons.geometry.spherical.oned.RegionBSPTree1S;
-import org.apache.commons.numbers.angle.PlaneAngleRadians;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class GreatCircleSubsetTest {
-
- private static final double TEST_EPS = 1e-10;
-
- private static final DoublePrecisionContext TEST_PRECISION =
- new EpsilonDoublePrecisionContext(TEST_EPS);
-
- private static final GreatCircle XY_CIRCLE = GreatCircles.fromPoleAndU(
- Vector3D.Unit.PLUS_Z, Vector3D.Unit.PLUS_X, TEST_PRECISION);
-
- @Test
- public void testBuilder_empty() {
- // act
- HyperplaneSubset.Builder<Point2S> builder = XY_CIRCLE.span().builder();
-
- GreatCircleSubset result = (GreatCircleSubset) builder.build();
-
- // assert
- Assert.assertFalse(result.isFull());
- Assert.assertTrue(result.isEmpty());
- Assert.assertFalse(result.isInfinite());
- Assert.assertTrue(result.isFinite());
-
- Assert.assertEquals(0, result.getSize(), TEST_EPS);
- }
-
- @Test
- public void testBuilder_addSingleConvex_returnsSameInstance() {
- // arrange
- GreatArc convex = XY_CIRCLE.arc(0, 1);
-
- // act
- HyperplaneSubset.Builder<Point2S> builder = XY_CIRCLE.span().builder();
-
- builder.add(convex);
-
- GreatCircleSubset result = (GreatCircleSubset) builder.build();
-
- // assert
- Assert.assertSame(convex, result);
- }
-
- @Test
- public void testBuilder_addSingleTreeSubset() {
- // arrange
- GreatCircle circle = GreatCircles.fromPoints(Point2S.MINUS_K, Point2S.PLUS_J, TEST_PRECISION);
-
- RegionBSPTree1S region = RegionBSPTree1S.empty();
- region.add(AngularInterval.of(PlaneAngleRadians.PI, 1.5 * PlaneAngleRadians.PI, TEST_PRECISION));
- region.add(AngularInterval.of(0, PlaneAngleRadians.PI_OVER_TWO, TEST_PRECISION));
-
- EmbeddedTreeGreatCircleSubset sub = new EmbeddedTreeGreatCircleSubset(circle, region);
-
- // act
- HyperplaneSubset.Builder<Point2S> builder = circle.span().builder();
-
- builder.add(sub);
-
- GreatCircleSubset result = (GreatCircleSubset) builder.build();
-
- // assert
- Assert.assertNotSame(sub, result);
-
- List<GreatArc> arcs = result.toConvex();
-
- Assert.assertEquals(2, arcs.size());
- checkArc(arcs.get(0), Point2S.MINUS_K, Point2S.PLUS_J);
- checkArc(arcs.get(1), Point2S.PLUS_K, Point2S.MINUS_J);
- }
-
- @Test
- public void testBuilder_addMixed_convexFirst() {
- // arrange
- GreatCircle circle = GreatCircles.fromPoints(Point2S.MINUS_K, Point2S.MINUS_J, TEST_PRECISION);
-
- RegionBSPTree1S region = RegionBSPTree1S.empty();
- region.add(AngularInterval.of(PlaneAngleRadians.PI, 1.25 * PlaneAngleRadians.PI, TEST_PRECISION));
- region.add(AngularInterval.of(0.25 * PlaneAngleRadians.PI, PlaneAngleRadians.PI_OVER_TWO, TEST_PRECISION));
-
- EmbeddedTreeGreatCircleSubset sub = new EmbeddedTreeGreatCircleSubset(circle, region);
-
- // act
- HyperplaneSubset.Builder<Point2S> builder = circle.span().builder();
-
- builder.add(circle.arc(1.5 * PlaneAngleRadians.PI, 0.25 * PlaneAngleRadians.PI));
- builder.add(circle.arc(1.6 * PlaneAngleRadians.PI, 0.2 * PlaneAngleRadians.PI));
- builder.add(sub);
-
- GreatCircleSubset result = (GreatCircleSubset) builder.build();
-
- // assert
- List<GreatArc> arcs = result.toConvex();
-
- Assert.assertEquals(2, arcs.size());
- checkArc(arcs.get(0), Point2S.of(PlaneAngleRadians.PI_OVER_TWO, 0), Point2S.of(PlaneAngleRadians.PI_OVER_TWO, 0.25 * PlaneAngleRadians.PI));
- checkArc(arcs.get(1), Point2S.PLUS_J, Point2S.MINUS_J);
- }
-
- @Test
- public void testBuilder_addMixed_treeSubsetFirst() {
- // arrange
- GreatCircle circle = GreatCircles.fromPoints(Point2S.MINUS_K, Point2S.MINUS_J, TEST_PRECISION);
-
- RegionBSPTree1S region = RegionBSPTree1S.empty();
- region.add(AngularInterval.of(PlaneAngleRadians.PI, 1.25 * PlaneAngleRadians.PI, TEST_PRECISION));
- region.add(AngularInterval.of(0.25 * PlaneAngleRadians.PI, PlaneAngleRadians.PI_OVER_TWO, TEST_PRECISION));
-
- EmbeddedTreeGreatCircleSubset sub = new EmbeddedTreeGreatCircleSubset(circle, region);
-
- // act
- HyperplaneSubset.Builder<Point2S> builder = circle.span().builder();
-
- builder.add(sub);
- builder.add(circle.arc(1.5 * PlaneAngleRadians.PI, 0.25 * PlaneAngleRadians.PI));
-
- GreatCircleSubset result = (GreatCircleSubset) builder.build();
-
- // assert
- List<GreatArc> arcs = result.toConvex();
-
- Assert.assertEquals(2, arcs.size());
- checkArc(arcs.get(0), Point2S.of(PlaneAngleRadians.PI_OVER_TWO, 0), Point2S.of(PlaneAngleRadians.PI_OVER_TWO, 0.25 * PlaneAngleRadians.PI));
- checkArc(arcs.get(1), Point2S.PLUS_J, Point2S.MINUS_J);
- }
-
- @Test
- public void testBuilder_nullArguments() {
- // arrange
- GreatCircle circle = GreatCircles.fromPoints(Point2S.MINUS_K, Point2S.MINUS_J, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Point2S> builder = circle.span().builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add((HyperplaneSubset<Point2S>) null);
- }, NullPointerException.class);
-
- GeometryTestUtils.assertThrows(() -> {
- builder.add((HyperplaneConvexSubset<Point2S>) null);
- }, NullPointerException.class, "Hyperplane subset must not be null");
- }
-
- @Test
- public void testBuilder_argumentsFromDifferentGreatCircle() {
- // arrange
- GreatCircle circle = GreatCircles.fromPoints(Point2S.MINUS_K, Point2S.MINUS_J, TEST_PRECISION);
- GreatCircle otherCircle = GreatCircles.fromPoints(Point2S.PLUS_I, Point2S.PLUS_J, TEST_PRECISION);
-
- EmbeddedTreeGreatCircleSubset sub = new EmbeddedTreeGreatCircleSubset(circle);
-
- HyperplaneSubset.Builder<Point2S> builder = sub.builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add(otherCircle.span());
- }, IllegalArgumentException.class);
-
- GeometryTestUtils.assertThrows(() -> {
- builder.add(new EmbeddedTreeGreatCircleSubset(otherCircle));
- }, IllegalArgumentException.class);
-
- GeometryTestUtils.assertThrows(() -> {
- builder.add(new UnknownHyperplaneSubset());
- }, IllegalArgumentException.class);
- }
-
- @Test
- public void testBuilder_unknownSubsetType() {
- // arrange
- GreatCircle circle = GreatCircles.fromPoints(Point2S.MINUS_K, Point2S.MINUS_J, TEST_PRECISION);
-
- HyperplaneSubset.Builder<Point2S> builder = circle.span().builder();
-
- // act/assert
- GeometryTestUtils.assertThrows(() -> {
- builder.add(new UnknownHyperplaneSubset());
- }, IllegalArgumentException.class);
- }
-
- private static void checkArc(GreatArc arc, Point2S start, Point2S end) {
- SphericalTestUtils.assertPointsEq(start, arc.getStartPoint(), TEST_EPS);
- SphericalTestUtils.assertPointsEq(end, arc.getEndPoint(), TEST_EPS);
- }
-
- private static class UnknownHyperplaneSubset implements HyperplaneSubset<Point2S> {
-
- @Override
- public Split<? extends HyperplaneSubset<Point2S>> split(Hyperplane<Point2S> splitter) {
- return null;
- }
-
- @Override
- public Hyperplane<Point2S> getHyperplane() {
- return null;
- }
-
- @Override
- public boolean isFull() {
- return false;
- }
-
- @Override
- public boolean isEmpty() {
- return false;
- }
-
- @Override
- public boolean isInfinite() {
- return false;
- }
-
- @Override
- public boolean isFinite() {
- return false;
- }
-
- @Override
- public double getSize() {
- return 0;
- }
-
- @Override
- public Point2S getCentroid() {
- return null;
- }
-
- @Override
- public RegionLocation classify(Point2S point) {
- return null;
- }
-
- @Override
- public Point2S closest(Point2S point) {
- return null;
- }
-
- @Override
- public Builder<Point2S> builder() {
- return null;
- }
-
- @Override
- public HyperplaneSubset<Point2S> transform(Transform<Point2S> transform) {
- return null;
- }
-
- @Override
- public List<? extends HyperplaneConvexSubset<Point2S>> toConvex() {
- return null;
- }
- }
-}