Commit 8d9e9bef authored by Benedikt Zoennchen's avatar Benedikt Zoennchen

much faster implementation of the BowyerWatson algorithm and a splitting...

much faster implementation of the BowyerWatson algorithm and a splitting algorithm for obscuse triangles
parent a2a75c7c
package org.vadere.util.data;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
public class DAG<E> {
private final E root;
private final List<DAG<E>> children;
public DAG(@NotNull final E element) {
root = element;
children = new ArrayList<>();
}
public List<DAG<E>> getChildren() {
return children;
}
public void addChild(E child) {
this.children.add(new DAG<E>(child));
}
public void addChild(DAG<E> child) {
this.children.add(child);
}
public E getRoot() {
return root;
}
public Collection<E> collectLeafs() {
Collection<E> leafs = new ArrayList<E>();
LinkedList<DAG<E>> nodesToVisit = new LinkedList<>();
nodesToVisit.add(this);
while (!nodesToVisit.isEmpty()) {
DAG<E> currentNode = nodesToVisit.removeFirst();
nodesToVisit.addAll(currentNode.children);
if(currentNode.isLeaf())
leafs.add(currentNode.getRoot());
}
return leafs;
}
public boolean isLeaf(){
return children.isEmpty();
}
/**
* Finds the first DAG-node element in a dept first fashion.
* @param test the predicate the element of the DAG-node has to fullfill.
* @return
*/
public Optional<E> findFirstElement(final Predicate<E> test){
Optional<DAG<E>> optDag = findFirst(test);
if(optDag.isPresent()) {
return Optional.of(optDag.get().getRoot());
}
else {
return Optional.empty();
}
}
/**
* Finds the first DAG-node in a dept first fashion.
* @param test the predicate the element of the DAG-node has to fullfill.
* @return
*/
public Optional<DAG<E>> findFirst(final Predicate<E> test){
if(test.test(root)) {
return Optional.of(this);
}
else {
return children.stream().map(child -> child.findFirst(test)).filter(opt -> opt.isPresent()).map(opt -> opt.get()).findFirst();
}
}
public Optional<DAG<E>> matchAll(final Predicate<E> test) {
if(test.test(root)) {
if(isLeaf()) {
return Optional.of(this);
}
else {
return children.stream().map(child -> child.matchAll(test)).filter(opt -> opt.isPresent()).map(opt -> opt.get()).findFirst();
}
}
return Optional.empty();
}
}
package org.vadere.util.delaunay;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.vadere.util.geometry.shapes.VCircle;
import org.vadere.util.geometry.shapes.VLine;
import org.vadere.util.geometry.shapes.VPoint;
import org.vadere.util.geometry.shapes.VRectangle;
import org.vadere.util.geometry.shapes.VTriangle;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* @author Benedikt Zoennchen
*
* This class is for computing the DelaunayTriangulation using the BowyerWatson-Algorithm. In average the algorithm should perfom in O(n log(n)) but
* in degenerated cases its runtime can be in O(n^2) where n is the number of points.
*/
public class BowyerWatsonSlow<P extends VPoint> {
private List<Triple<P, P, P>> triangles;
private Collection<P> points;
private List<P> initPoints;
private final BiFunction<Double, Double, P> pointConstructor;
public BowyerWatsonSlow(final Collection<P> points, final BiFunction<Double, Double, P> pointConstructor) {
this.points = points;
this.pointConstructor = pointConstructor;
}
public void execute() {
P max = points.parallelStream().reduce(pointConstructor.apply(Double.MIN_VALUE, Double.MIN_VALUE), (a, b) -> pointConstructor.apply(Math.max(a.getX(), b.getX()), Math.max(a.getY(), b.getY())));
P min = points.parallelStream().reduce(pointConstructor.apply(Double.MIN_VALUE, Double.MIN_VALUE), (a, b) -> pointConstructor.apply(Math.min(a.getX(), b.getX()), Math.min(a.getY(), b.getY())));
VRectangle bound = new VRectangle(min.getX(), min.getY(), max.getX()-min.getX(), max.getY()- min.getY());
init(bound);
points.stream().forEach(point -> handle(point));
cleanUp();
}
public List<Triple<P, P, P>> getTriangles() {
return triangles;
}
public List<VTriangle> getVTriangles() {
return triangles.stream().map(this::pointsToTriangle).collect(Collectors.toList());
}
public Set<VLine> getEdges() {
return triangles.parallelStream().flatMap(triangle -> Stream.of(new VTriangle(triangle.getLeft(), triangle.getMiddle(), triangle.getRight()).getLines())).collect(Collectors.toSet());
}
private void init(final VRectangle bound) {
triangles = new ArrayList<>();
initPoints = new ArrayList<>();
Triple<P, P, P> superTriangle = getSuperTriangle(bound);
triangles.add(superTriangle);
initPoints.add(superTriangle.getLeft());
initPoints.add(superTriangle.getMiddle());
initPoints.add(superTriangle.getRight());
}
private Triple<P, P, P> getSuperTriangle(final VRectangle bound) {
double gap = 1.0;
double max = Math.max(bound.getWidth(), bound.getHeight());
P p1 = pointConstructor.apply(bound.getX() - max - gap, bound.getY() - gap);
P p2 = pointConstructor.apply(bound.getX() + 2 * max + gap, bound.getY() - gap);
P p3 = pointConstructor.apply(bound.getX() + (max+2*gap)/2, bound.getY() + 2 * max+ gap);
return ImmutableTriple.of(p1, p2, p3);
}
private void handle(final P point) {
HashSet<Line> edges = new HashSet<>();
// This is way to expensive O(n) instead of O(log(n))
Map<Boolean, List<Triple<P, P, P>>> partition = triangles.parallelStream().collect(Collectors.partitioningBy(t -> pointsToTriangle(t).isInCircumscribedCycle(point)));
List<Triple<P, P, P>> badTriangles = partition.get(true);
triangles = partition.get(false);
IntStream s;
HashSet<Line> toRemove = new HashSet<>();
// duplicated edges
badTriangles.stream().flatMap(t -> getEdges(t).stream()).forEach(line -> {
if(!edges.add(line)) {
toRemove.add(line);
}
});
toRemove.stream().forEach(removeEdge -> edges.remove(removeEdge));
// identifier ?
edges.stream().forEach(edge -> triangles.add(Triple.of(edge.p1, edge.p2, point)));
}
private List<Line> getEdges(Triple<P, P, P> triangle) {
List<Line> list = new ArrayList<>();
list.add(new Line(triangle.getLeft(), triangle.getMiddle()));
list.add(new Line(triangle.getMiddle(), triangle.getRight()));
list.add(new Line(triangle.getRight(), triangle.getLeft()));
return list;
}
private void cleanUp() {
triangles = triangles.stream().filter(triangle -> !isTriangleConnectedToInitialPoints(triangle)).collect(Collectors.toList());
}
private boolean isTriangleConnectedToInitialPoints(final Triple<P, P, P> trianglePoints) {
return Stream.of(pointsToTriangle(trianglePoints).getLines()).anyMatch(edge -> {
VPoint p1 = new VPoint(edge.getP1().getX(), edge.getP1().getY());
VPoint p2 = new VPoint(edge.getP2().getX(), edge.getP2().getY());
return initPoints.stream().anyMatch(initPoint -> p1.equals(initPoint) || p2.equals(initPoint));
});
}
private VTriangle pointsToTriangle(Triple<P, P, P> points) {
return new VTriangle(points.getLeft(), points.getMiddle(), points.getRight());
}
private class Line {
final P p1;
final P p2;
private Line(P p1, P p2) {
this.p1 = p1;
this.p2 = p2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Line line = (Line) o;
return (p1.equals(line.p1) && p2.equals(line.p2)) || (p2.equals(line.p1) && p1.equals(line.p2));
}
@Override
public int hashCode() {
return p1.hashCode() * p2.hashCode();
}
}
// TODO: the following code can be deleted, this is only for visual checks
public static void main(String[] args) {
// TODO Auto-generated method stub
int height = 1000;
int width = 1000;
int max = Math.max(height, width);
Set<VPoint> points = new HashSet<>();
/*points.add(new VPoint(20,20));
points.add(new VPoint(20,40));
points.add(new VPoint(75,53));
points.add(new VPoint(80,70));*/
Random r = new Random();
for(int i=0; i<100; i++) {
VPoint point = new VPoint(width*r.nextDouble(), height*r.nextDouble());
points.add(point);
}
BowyerWatsonSlow<VPoint> bw = new BowyerWatsonSlow<VPoint>(points, (x, y) -> new VPoint(x, y));
bw.execute();
Set<VLine> edges = bw.getEdges();
JFrame window = new JFrame();
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setBounds(0, 0, max, max);
window.getContentPane().add(new Lines(edges, points, max));
window.setVisible(true);
}
private static class Lines extends JComponent{
private Set<VLine> edges;
private Set<VPoint> points;
private final int max;
public Lines(final Set<VLine> edges, final Set<VPoint> points, final int max){
this.edges = edges;
this.points = points;
this.max = max;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setBackground(Color.white);
g2.setStroke(new BasicStroke(1.0f));
g2.setColor(Color.gray);
edges.stream().forEach(edge -> {
Shape k = new VLine(edge.getP1().getX(), edge.getP1().getY(), edge.getP2().getX(), edge.getP2().getY());
g2.draw(k);
});
points.stream().forEach(point -> {
VCircle k = new VCircle(point.getX(), point.getY(), 1.0);
g2.draw(k);
});
}
}
public void removeTriangleIf(final Predicate<Triple<P, P, P>> predicate) {
triangles.removeIf(predicate);
}
}
package org.vadere.util.delaunay;
import org.apache.commons.lang3.tuple.Triple;
import org.vadere.util.geometry.shapes.VPoint;
import org.vadere.util.geometry.shapes.VTriangle;
public class DAGElement<P extends VPoint, T extends VTriangle> {
private Face<P> face;
private Triple<P, P, P> vertices;
private T triangle;
public DAGElement(final Face<P> face, final Triple<P, P, P> vertices, final TriangleConstructor<P, T> triangleConstructor) {
this.face = face;
this.vertices = vertices;
this.triangle = triangleConstructor.create(vertices.getLeft(), vertices.getMiddle(), vertices.getRight());
}
public Face<P> getFace() {
return face;
}
public T getTriangle() {
return triangle;
}
public Triple<P, P, P> getVertices() {
return vertices;
}
}
package org.vadere.util.delaunay;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.NotNull;
import org.vadere.util.data.DAG;
import org.vadere.util.geometry.shapes.VPoint;
import org.vadere.util.geometry.shapes.VPolygon;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class Face implements Iterable<HalfEdge> {
public class Face<P extends VPoint> implements Iterable<HalfEdge<P>> {
/**
* one of the half-edges bordering this face.
*/
private HalfEdge edge;
private HalfEdge<P> edge;
public Face(final HalfEdge edge) {
public Face(final HalfEdge<P> edge) {
this.edge = edge;
}
public Face() {}
public void setEdge(@NotNull HalfEdge edge) {
public static <P extends VPoint> Face<P> of(P p1, P p2, P p3) {
Face superTriangle = new Face();
HalfEdge edge1 = new HalfEdge(p1, superTriangle);
HalfEdge edge2 = new HalfEdge(p2, superTriangle);
HalfEdge edge3 = new HalfEdge(p3, superTriangle);
edge1.setNext(edge2);
edge2.setNext(edge3);
edge3.setNext(edge1);
superTriangle.setEdge(edge1);
return superTriangle;
}
public void setEdge(@NotNull HalfEdge<P> edge) {
this.edge = edge;
}
public double getArea() {
List<VPoint> pointList = getPoints();
List<P> pointList = getPoints();
double result = 0;
for (int i = 0; i < pointList.size() - 1; i++) {
......@@ -39,15 +53,11 @@ public class Face implements Iterable<HalfEdge> {
return Math.abs(result) / 2.0;
}
public List<VPoint> getPoints() {
List<VPoint> list = new ArrayList<>();
for(HalfEdge edge : this) {
list.add(edge.getEnd());
}
return list;
public List<P> getPoints() {
return streamPoints().collect(Collectors.toList());
}
public boolean contains(final VPoint point) {
public boolean contains(final P point) {
return toPolygon().contains(point);
}
......@@ -61,17 +71,25 @@ public class Face implements Iterable<HalfEdge> {
}
@Override
public Iterator<HalfEdge> iterator() {
public Iterator<HalfEdge<P>> iterator() {
return new HalfEdgeIterator();
}
public Stream<HalfEdge> stream () {
Iterable<HalfEdge> iterable = () -> iterator();
public Stream<HalfEdge<P>> stream () {
Iterable<HalfEdge<P>> iterable = () -> iterator();
return StreamSupport.stream(iterable.spliterator(), false);
}
private class HalfEdgeIterator implements Iterator<HalfEdge> {
private HalfEdge currentHalfEdge;
public List<HalfEdge<P>> getEdges() {
return stream().collect(Collectors.toList());
}
public Stream<P> streamPoints() {
return stream().map(edge -> edge.getEnd());
}
private class HalfEdgeIterator implements Iterator<HalfEdge<P>> {
private HalfEdge<P> currentHalfEdge;
private boolean started = false;
private HalfEdgeIterator(){
......@@ -84,7 +102,7 @@ public class Face implements Iterable<HalfEdge> {
}
@Override
public HalfEdge next() {
public HalfEdge<P> next() {
started = true;
HalfEdge result = currentHalfEdge;
currentHalfEdge = currentHalfEdge.getNext();
......
package org.vadere.util.delaunay;
import org.vadere.util.geometry.shapes.VPoint;
@FunctionalInterface
public interface PointConstructor<P extends VPoint> {
P create(double x, double y);
}
......@@ -12,48 +12,50 @@ import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PointLocation {
public class PointLocation<P extends VPoint> {
private final Collection<Face> faces;
private final List<VPoint> orderedPointList;
private final List<List<HalfEdge>> halfeEdgesSegments;
private final List<List<VPoint>> intersectionPointsInSegment;
private final Collection<Face<P>> faces;
private final List<P> orderedPointList;
private final List<List<HalfEdge<P>>> halfeEdgesSegments;
private final List<List<P>> intersectionPointsInSegment;
private final BiFunction<Double, Double, P> pointConstructor;
private Comparator<VPoint> pointComparatorX = (p1, p2) -> {
private Comparator<P> pointComparatorX = (p1, p2) -> {
double dx = p1.getX() - p2.getX();
if(dx < 0) return -1;
else if(dx > 0) return 1;
else return 0;
};
private Comparator<VPoint> pointComparatorY = (p1, p2) -> {
private Comparator<P> pointComparatorY = (p1, p2) -> {
double dy = p1.getY() - p2.getY();
if(dy < 0) return -1;
else if(dy > 0) return 1;
else return 0;
};
private class BetweenTwoPoints implements Predicate<HalfEdge> {
private class BetweenTwoPoints implements Predicate<HalfEdge<P>> {
private VPoint p1;
private VPoint p2;
private P p1;
private P p2;
private BetweenTwoPoints(final VPoint p1, final VPoint p2) {
private BetweenTwoPoints(final P p1, final P p2) {
this.p1 = p1;
this.p2 = p2;
}
@Override
public boolean test(final HalfEdge halfEdge) {
public boolean test(final HalfEdge<P> halfEdge) {
return (halfEdge.getEnd().getX() > p1.getX() && halfEdge.getPrevious().getEnd().getX() < p2.getX()) ||
(halfEdge.getEnd().getX() > p2.getX() && halfEdge.getPrevious().getEnd().getX() < p1.getX());
}
}
private class HalfEdgeComparator implements Comparator<HalfEdge> {
private class HalfEdgeComparator implements Comparator<HalfEdge<P>> {
private double x1;
private double x2;
......@@ -64,7 +66,7 @@ public class PointLocation {
}
@Override
public int compare(final HalfEdge edge1, final HalfEdge edge2) {
public int compare(final HalfEdge<P> edge1, final HalfEdge<P> edge2) {
VLine line1 = edge1.toLine();
VLine line2 = edge2.toLine();
double slope1 = line1.slope();
......@@ -79,10 +81,12 @@ public class PointLocation {
}
}
public PointLocation(final Collection<Face> faces) {
public PointLocation(final Collection<Face<P>> faces, final BiFunction<Double, Double, P> pointConstructor) {
this.faces = faces;
this.pointConstructor = pointConstructor;
//TODO distinct is maybe slow here
Set<VPoint> pointSet = faces.stream()
Set<P> pointSet = faces.stream()
.flatMap(face -> face.stream()).map(edge -> edge.getEnd())
.sorted(pointComparatorX).collect(Collectors.toSet());
......@@ -91,11 +95,11 @@ public class PointLocation {
intersectionPointsInSegment = new ArrayList<>(orderedPointList.size()-1);
for(int i = 0; i < orderedPointList.size() - 1; i++) {
VPoint p1 = orderedPointList.get(i);
VPoint p2 = orderedPointList.get(i+1);
List<HalfEdge> halfEdges = faces.stream().flatMap(face -> face.stream()).filter(new BetweenTwoPoints(p1, p2))
P p1 = orderedPointList.get(i);
P p2 = orderedPointList.get(i+1);
List<HalfEdge<P>> halfEdges = faces.stream().flatMap(face -> face.stream()).filter(new BetweenTwoPoints(p1, p2))
.sorted(new HalfEdgeComparator(p1.getX(), p2.getX())).collect(Collectors.toList());
List<VPoint> intersectionPoints = halfEdges.stream()
List<P> intersectionPoints = halfEdges.stream()
.map(hf -> hf.toLine())
.map(line -> intersectionWithX(p1.getX(), line)).collect(Collectors.toList());