forked from apache/lucene
/
Tessellator.java
1605 lines (1482 loc) · 54 KB
/
Tessellator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.lucene.geo;
import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;
import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;
import static org.apache.lucene.geo.GeoUtils.lineCrossesLine;
import static org.apache.lucene.geo.GeoUtils.lineOverlapLine;
import static org.apache.lucene.geo.GeoUtils.orient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.geo.GeoUtils.WindingOrder;
import org.apache.lucene.util.BitUtil;
/**
* Computes a triangular mesh tessellation for a given polygon.
*
* <p>This is inspired by mapbox's earcut algorithm (https://github.com/mapbox/earcut) which is a
* modification to FIST (https://www.cosy.sbg.ac.at/~held/projects/triang/triang.html) written by
* Martin Held, and ear clipping
* (https://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf) written by David
* Eberly.
*
* <p>Notes:
*
* <ul>
* <li>Requires valid polygons:
* <ul>
* <li>No self intersections
* <li>Holes may only touch at one vertex
* <li>Polygon must have an area (e.g., no "line" boxes)
* <li>sensitive to overflow (e.g, subatomic values such as E-200 can cause unexpected
* behavior)
* </ul>
* </ul>
*
* <p>The code is a modified version of the javascript implementation provided by MapBox under the
* following license:
*
* <p>ISC License
*
* <p>Copyright (c) 2016, Mapbox
*
* <p>Permission to use, copy, modify, and/or distribute this software for any purpose with or
* without fee is hereby granted, provided that the above copyright notice and this permission
* notice appear in all copies.
*
* <p>THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH' REGARD TO THIS
* SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*
* @lucene.internal
*/
public final class Tessellator {
// this is a dumb heuristic to control whether we cut over to sorted morton values
private static final int VERTEX_THRESHOLD = 80;
/** state of the tessellated split - avoids recursion */
private enum State {
INIT,
CURE,
SPLIT
}
// No Instance:
private Tessellator() {}
public static List<Triangle> tessellate(final Polygon polygon, boolean checkSelfIntersections) {
// Attempt to establish a doubly-linked list of the provided shell points (should be CCW, but
// this will correct);
// then filter instances of intersections.
Node outerNode =
createDoublyLinkedList(
polygon.getPolyLons(),
polygon.getPolyLats(),
polygon.getWindingOrder(),
true,
0,
WindingOrder.CW);
// If an outer node hasn't been detected, the shape is malformed. (must comply with OGC SFA
// specification)
if (outerNode == null) {
throw new IllegalArgumentException("Malformed shape detected in Tessellator!");
}
if (outerNode == outerNode.next || outerNode == outerNode.next.next) {
throw new IllegalArgumentException("at least three non-collinear points required");
}
// Determine if the specified list of points contains holes
if (polygon.numHoles() > 0) {
// Eliminate the hole triangulation.
outerNode = eliminateHoles(polygon, outerNode);
}
// If the shape crosses VERTEX_THRESHOLD, use z-order curve hashing:
final boolean mortonOptimized;
{
int threshold = VERTEX_THRESHOLD - polygon.numPoints();
for (int i = 0; threshold >= 0 && i < polygon.numHoles(); ++i) {
threshold -= polygon.getHole(i).numPoints();
}
// Link polygon nodes in Z-Order
mortonOptimized = threshold < 0;
if (mortonOptimized == true) {
sortByMorton(outerNode);
}
}
if (checkSelfIntersections) {
checkIntersection(outerNode, mortonOptimized);
}
// Calculate the tessellation using the doubly LinkedList.
List<Triangle> result =
earcutLinkedList(polygon, outerNode, new ArrayList<>(), State.INIT, mortonOptimized);
if (result.size() == 0) {
throw new IllegalArgumentException(
"Unable to Tessellate shape. Possible malformed shape detected.");
}
return result;
}
public static List<Triangle> tessellate(final XYPolygon polygon, boolean checkSelfIntersections) {
// Attempt to establish a doubly-linked list of the provided shell points (should be CCW, but
// this will correct);
// then filter instances of intersections.0
Node outerNode =
createDoublyLinkedList(
XYEncodingUtils.floatArrayToDoubleArray(polygon.getPolyX()),
XYEncodingUtils.floatArrayToDoubleArray(polygon.getPolyY()),
polygon.getWindingOrder(),
false,
0,
WindingOrder.CW);
// If an outer node hasn't been detected, the shape is malformed. (must comply with OGC SFA
// specification)
if (outerNode == null) {
throw new IllegalArgumentException("Malformed shape detected in Tessellator!");
}
if (outerNode == outerNode.next || outerNode == outerNode.next.next) {
throw new IllegalArgumentException("at least three non-collinear points required");
}
// Determine if the specified list of points contains holes
if (polygon.numHoles() > 0) {
// Eliminate the hole triangulation.
outerNode = eliminateHoles(polygon, outerNode);
}
// If the shape crosses VERTEX_THRESHOLD, use z-order curve hashing:
final boolean mortonOptimized;
{
int threshold = VERTEX_THRESHOLD - polygon.numPoints();
for (int i = 0; threshold >= 0 && i < polygon.numHoles(); ++i) {
threshold -= polygon.getHole(i).numPoints();
}
// Link polygon nodes in Z-Order
mortonOptimized = threshold < 0;
if (mortonOptimized == true) {
sortByMorton(outerNode);
}
}
if (checkSelfIntersections) {
checkIntersection(outerNode, mortonOptimized);
}
// Calculate the tessellation using the doubly LinkedList.
List<Triangle> result =
earcutLinkedList(polygon, outerNode, new ArrayList<>(), State.INIT, mortonOptimized);
if (result.size() == 0) {
throw new IllegalArgumentException(
"Unable to Tessellate shape. Possible malformed shape detected.");
}
return result;
}
/**
* Creates a circular doubly linked list using polygon points. The order is governed by the
* specified winding order
*/
private static final Node createDoublyLinkedList(
final double[] x,
final double[] y,
final WindingOrder polyWindingOrder,
boolean isGeo,
int startIndex,
final WindingOrder windingOrder) {
Node lastNode = null;
// Link points into the circular doubly-linked list in the specified winding order
if (windingOrder == polyWindingOrder) {
for (int i = 0; i < x.length; ++i) {
lastNode = insertNode(x, y, startIndex++, i, lastNode, isGeo);
}
} else {
for (int i = x.length - 1; i >= 0; --i) {
lastNode = insertNode(x, y, startIndex++, i, lastNode, isGeo);
}
}
// if first and last node are the same then remove the end node and set lastNode to the start
if (lastNode != null && isVertexEquals(lastNode, lastNode.next)) {
removeNode(lastNode, true);
lastNode = lastNode.next;
}
// Return the last node in the Doubly-Linked List
return filterPoints(lastNode, null);
}
private static final Node eliminateHoles(final XYPolygon polygon, Node outerNode) {
// Define a list to hole a reference to each filtered hole list.
final List<Node> holeList = new ArrayList<>();
// keep a reference to the hole
final Map<Node, XYPolygon> holeListPolygons = new HashMap<>();
// Iterate through each array of hole vertices.
XYPolygon[] holes = polygon.getHoles();
int nodeIndex = polygon.numPoints();
for (int i = 0; i < polygon.numHoles(); ++i) {
// create the doubly-linked hole list
Node list =
createDoublyLinkedList(
XYEncodingUtils.floatArrayToDoubleArray(holes[i].getPolyX()),
XYEncodingUtils.floatArrayToDoubleArray(holes[i].getPolyY()),
holes[i].getWindingOrder(),
false,
nodeIndex,
WindingOrder.CCW);
// Determine if the resulting hole polygon was successful.
if (list != null) {
// Add the leftmost vertex of the hole.
Node leftMost = fetchLeftmost(list);
holeList.add(leftMost);
holeListPolygons.put(leftMost, holes[i]);
}
nodeIndex += holes[i].numPoints();
}
return eliminateHoles(holeList, holeListPolygons, outerNode);
}
/** Links every hole into the outer loop, producing a single-ring polygon without holes. * */
private static final Node eliminateHoles(final Polygon polygon, Node outerNode) {
// Define a list to hole a reference to each filtered hole list.
final List<Node> holeList = new ArrayList<>();
// keep a reference to the hole
final Map<Node, Polygon> holeListPolygons = new HashMap<>();
// Iterate through each array of hole vertices.
Polygon[] holes = polygon.getHoles();
int nodeIndex = polygon.numPoints();
for (int i = 0; i < polygon.numHoles(); ++i) {
// create the doubly-linked hole list
Node list =
createDoublyLinkedList(
holes[i].getPolyLons(),
holes[i].getPolyLats(),
holes[i].getWindingOrder(),
true,
nodeIndex,
WindingOrder.CCW);
if (list == list.next) {
throw new IllegalArgumentException("Points are all coplanar in hole: " + holes[i]);
}
// Add the leftmost vertex of the hole.
Node leftMost = fetchLeftmost(list);
holeList.add(leftMost);
holeListPolygons.put(leftMost, holes[i]);
nodeIndex += holes[i].numPoints();
}
return eliminateHoles(holeList, holeListPolygons, outerNode);
}
private static final Node eliminateHoles(
List<Node> holeList, final Map<Node, ?> holeListPolygons, Node outerNode) {
// Sort the hole vertices by x coordinate
holeList.sort(
(Node pNodeA, Node pNodeB) -> {
double diff = pNodeA.getX() - pNodeB.getX();
if (diff == 0) {
diff = pNodeA.getY() - pNodeB.getY();
if (diff == 0) {
// same hole node
double a = Math.min(pNodeA.previous.getY(), pNodeA.next.getY());
double b = Math.min(pNodeB.previous.getY(), pNodeB.next.getY());
diff = a - b;
}
}
return diff < 0 ? -1 : diff > 0 ? 1 : 0;
});
// Process holes from left to right.
for (int i = 0; i < holeList.size(); ++i) {
// Eliminate hole triangles from the result set
final Node holeNode = holeList.get(i);
double holeMinX, holeMaxX, holeMinY, holeMaxY;
Object h = holeListPolygons.get(holeNode);
if (h instanceof Polygon) {
Polygon holePoly = (Polygon) h;
holeMinX = holePoly.minLon;
holeMaxX = holePoly.maxLon;
holeMinY = holePoly.minLat;
holeMaxY = holePoly.maxLat;
} else {
XYPolygon holePoly = (XYPolygon) h;
holeMinX = holePoly.minX;
holeMaxX = holePoly.maxX;
holeMinY = holePoly.minY;
holeMaxY = holePoly.maxY;
}
eliminateHole(holeNode, outerNode, holeMinX, holeMaxX, holeMinY, holeMaxY);
// Filter the new polygon.
outerNode = filterPoints(outerNode, outerNode.next);
}
// Return a pointer to the list.
return outerNode;
}
/** Finds a bridge between vertices that connects a hole with an outer ring, and links it */
private static final void eliminateHole(
final Node holeNode,
Node outerNode,
double holeMinX,
double holeMaxX,
double holeMinY,
double holeMaxY) {
// Attempt to find a common point between the HoleNode and OuterNode.
Node next = outerNode;
do {
if (Rectangle.containsPoint(
next.getY(), next.getX(), holeMinY, holeMaxY, holeMinX, holeMaxX)) {
Node sharedVertex = getSharedVertex(holeNode, next);
if (sharedVertex != null) {
// Split the resulting polygon.
Node node = splitPolygon(next, sharedVertex, true);
// Filter the split nodes.
filterPoints(node, node.next);
return;
}
}
next = next.next;
} while (next != outerNode);
// Attempt to find a logical bridge between the HoleNode and OuterNode.
outerNode = fetchHoleBridge(holeNode, outerNode);
// Determine whether a hole bridge could be fetched.
if (outerNode != null) {
// compute if the bridge overlaps with a polygon edge.
boolean fromPolygon =
isPointInLine(outerNode, outerNode.next, holeNode)
|| isPointInLine(holeNode, holeNode.next, outerNode);
// Split the resulting polygon.
Node node = splitPolygon(outerNode, holeNode, fromPolygon);
// Filter the split nodes.
filterPoints(node, node.next);
}
}
/**
* David Eberly's algorithm for finding a bridge between a hole and outer polygon
*
* <p>see: http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
*/
private static final Node fetchHoleBridge(final Node holeNode, final Node outerNode) {
Node p = outerNode;
double qx = Double.NEGATIVE_INFINITY;
final double hx = holeNode.getX();
final double hy = holeNode.getY();
Node connection = null;
// 1. find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
{
do {
if (hy <= p.getY() && hy >= p.next.getY() && p.next.getY() != p.getY()) {
final double x =
p.getX() + (hy - p.getY()) * (p.next.getX() - p.getX()) / (p.next.getY() - p.getY());
if (x <= hx && x > qx) {
qx = x;
if (x == hx) {
if (hy == p.getY()) return p;
if (hy == p.next.getY()) return p.next;
}
connection = p.getX() < p.next.getX() ? p : p.next;
}
}
p = p.next;
} while (p != outerNode);
}
if (connection == null) {
return null;
} else if (hx == qx) {
return connection.previous;
}
// 2. look for points inside the triangle of hole point, segment intersection, and endpoint
// its a valid connection iff there are no points found;
// otherwise choose the point of the minimum angle with the ray as the connection point
Node stop = connection;
final double mx = connection.getX();
final double my = connection.getY();
double tanMin = Double.POSITIVE_INFINITY;
double tan;
p = connection.next;
{
while (p != stop) {
if (hx >= p.getX()
&& p.getX() >= mx
&& hx != p.getX()
&& pointInEar(
p.getX(), p.getY(), hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy)) {
tan = Math.abs(hy - p.getY()) / (hx - p.getX()); // tangential
if (isVertexEquals(p, connection) && isLocallyInside(p, holeNode)) {
// make sure we are not crossing the polygon. This might happen when several holes have
// a bridge to the same polygon vertex
// and this vertex has different vertex.
boolean crosses =
GeoUtils.lineCrossesLine(
p.getX(),
p.getY(),
holeNode.getX(),
holeNode.getY(),
connection.next.getX(),
connection.next.getY(),
connection.previous.getX(),
connection.previous.getY());
if (crosses == false) {
connection = p;
tanMin = tan;
}
} else if ((tan < tanMin || (tan == tanMin && p.getX() > connection.getX()))
&& isLocallyInside(p, holeNode)) {
connection = p;
tanMin = tan;
}
}
p = p.next;
}
}
return connection;
}
/** Check if the provided vertex is in the polygon and return it * */
private static Node getSharedVertex(final Node polygon, final Node vertex) {
Node next = polygon;
do {
if (isVertexEquals(next, vertex)) {
// make sure we are not crossing the polygon. This might happen when several holes share the
// same polygon vertex.
boolean crosses =
GeoUtils.lineCrossesLine(
next.previous.getX(),
next.previous.getY(),
vertex.next.getX(),
vertex.next.getY(),
next.next.getX(),
next.next.getY(),
vertex.previous.getX(),
vertex.previous.getY());
if (crosses == false) {
return next;
}
}
next = next.next;
} while (next != polygon);
return null;
}
/** Finds the left-most hole of a polygon ring. * */
private static final Node fetchLeftmost(final Node start) {
Node node = start;
Node leftMost = start;
do {
// Determine if the current node possesses a lesser X position.
if (node.getX() < leftMost.getX()
|| (node.getX() == leftMost.getX() && node.getY() < leftMost.getY())) {
// Maintain a reference to this Node.
leftMost = node;
}
// Progress the search to the next node in the doubly-linked list.
node = node.next;
} while (node != start);
// Return the node with the smallest X value.
return leftMost;
}
/**
* Main ear slicing loop which triangulates the vertices of a polygon, provided as a doubly-linked
* list. *
*/
private static final List<Triangle> earcutLinkedList(
Object polygon,
Node currEar,
final List<Triangle> tessellation,
State state,
final boolean mortonOptimized) {
earcut:
do {
if (currEar == null || currEar.previous == currEar.next) {
return tessellation;
}
Node stop = currEar;
Node prevNode;
Node nextNode;
// Iteratively slice ears
do {
prevNode = currEar.previous;
nextNode = currEar.next;
// Determine whether the current triangle must be cut off.
final boolean isReflex =
area(
prevNode.getX(),
prevNode.getY(),
currEar.getX(),
currEar.getY(),
nextNode.getX(),
nextNode.getY())
>= 0;
if (isReflex == false && isEar(currEar, mortonOptimized) == true) {
// Compute if edges belong to the polygon
boolean abFromPolygon = prevNode.isNextEdgeFromPolygon;
boolean bcFromPolygon = currEar.isNextEdgeFromPolygon;
boolean caFromPolygon = isEdgeFromPolygon(prevNode, nextNode, mortonOptimized);
// Return the triangulated data
tessellation.add(
new Triangle(
prevNode, abFromPolygon, currEar, bcFromPolygon, nextNode, caFromPolygon));
// Remove the ear node.
removeNode(currEar, caFromPolygon);
// Skipping to the next node leaves fewer slither triangles.
currEar = nextNode.next;
stop = nextNode.next;
continue;
}
currEar = nextNode;
// If the whole polygon has been iterated over and no more ears can be found.
if (currEar == stop) {
switch (state) {
case INIT:
// try filtering points and slicing again
currEar = filterPoints(currEar, null);
state = State.CURE;
continue earcut;
case CURE:
// if this didn't work, try curing all small self-intersections locally
currEar = cureLocalIntersections(currEar, tessellation, mortonOptimized);
state = State.SPLIT;
continue earcut;
case SPLIT:
// as a last resort, try splitting the remaining polygon into two
if (splitEarcut(polygon, currEar, tessellation, mortonOptimized) == false) {
// we could not process all points. Tessellation failed
throw new IllegalArgumentException(
"Unable to Tessellate shape. Possible malformed shape detected.");
}
break;
}
break;
}
} while (currEar.previous != currEar.next);
break;
} while (true);
// Return the calculated tessellation
return tessellation;
}
/** Determines whether a polygon node forms a valid ear with adjacent nodes. * */
private static final boolean isEar(final Node ear, final boolean mortonOptimized) {
if (mortonOptimized == true) {
return mortonIsEar(ear);
}
// make sure there aren't other points inside the potential ear
Node node = ear.next.next;
while (node != ear.previous) {
if (pointInEar(
node.getX(),
node.getY(),
ear.previous.getX(),
ear.previous.getY(),
ear.getX(),
ear.getY(),
ear.next.getX(),
ear.next.getY())
&& area(
node.previous.getX(),
node.previous.getY(),
node.getX(),
node.getY(),
node.next.getX(),
node.next.getY())
>= 0) {
return false;
}
node = node.next;
}
return true;
}
/**
* Uses morton code for speed to determine whether or a polygon node forms a valid ear w/ adjacent
* nodes
*/
private static final boolean mortonIsEar(final Node ear) {
// triangle bbox (flip the bits so negative encoded values are < positive encoded values)
int minTX = StrictMath.min(StrictMath.min(ear.previous.x, ear.x), ear.next.x) ^ 0x80000000;
int minTY = StrictMath.min(StrictMath.min(ear.previous.y, ear.y), ear.next.y) ^ 0x80000000;
int maxTX = StrictMath.max(StrictMath.max(ear.previous.x, ear.x), ear.next.x) ^ 0x80000000;
int maxTY = StrictMath.max(StrictMath.max(ear.previous.y, ear.y), ear.next.y) ^ 0x80000000;
// z-order range for the current triangle bbox;
long minZ = BitUtil.interleave(minTX, minTY);
long maxZ = BitUtil.interleave(maxTX, maxTY);
// now make sure we don't have other points inside the potential ear;
// look for points inside the triangle in both directions
Node p = ear.previousZ;
Node n = ear.nextZ;
while (p != null
&& Long.compareUnsigned(p.morton, minZ) >= 0
&& n != null
&& Long.compareUnsigned(n.morton, maxZ) <= 0) {
if (p.idx != ear.previous.idx
&& p.idx != ear.next.idx
&& pointInEar(
p.getX(),
p.getY(),
ear.previous.getX(),
ear.previous.getY(),
ear.getX(),
ear.getY(),
ear.next.getX(),
ear.next.getY())
&& area(
p.previous.getX(),
p.previous.getY(),
p.getX(),
p.getY(),
p.next.getX(),
p.next.getY())
>= 0) return false;
p = p.previousZ;
if (n.idx != ear.previous.idx
&& n.idx != ear.next.idx
&& pointInEar(
n.getX(),
n.getY(),
ear.previous.getX(),
ear.previous.getY(),
ear.getX(),
ear.getY(),
ear.next.getX(),
ear.next.getY())
&& area(
n.previous.getX(),
n.previous.getY(),
n.getX(),
n.getY(),
n.next.getX(),
n.next.getY())
>= 0) return false;
n = n.nextZ;
}
// first look for points inside the triangle in decreasing z-order
while (p != null && Long.compareUnsigned(p.morton, minZ) >= 0) {
if (p.idx != ear.previous.idx
&& p.idx != ear.next.idx
&& pointInEar(
p.getX(),
p.getY(),
ear.previous.getX(),
ear.previous.getY(),
ear.getX(),
ear.getY(),
ear.next.getX(),
ear.next.getY())
&& area(
p.previous.getX(),
p.previous.getY(),
p.getX(),
p.getY(),
p.next.getX(),
p.next.getY())
>= 0) {
return false;
}
p = p.previousZ;
}
// then look for points in increasing z-order
while (n != null && Long.compareUnsigned(n.morton, maxZ) <= 0) {
if (n.idx != ear.previous.idx
&& n.idx != ear.next.idx
&& pointInEar(
n.getX(),
n.getY(),
ear.previous.getX(),
ear.previous.getY(),
ear.getX(),
ear.getY(),
ear.next.getX(),
ear.next.getY())
&& area(
n.previous.getX(),
n.previous.getY(),
n.getX(),
n.getY(),
n.next.getX(),
n.next.getY())
>= 0) {
return false;
}
n = n.nextZ;
}
return true;
}
/** Iterate through all polygon nodes and remove small local self-intersections * */
private static final Node cureLocalIntersections(
Node startNode, final List<Triangle> tessellation, final boolean mortonOptimized) {
Node node = startNode;
Node nextNode;
do {
nextNode = node.next;
Node a = node.previous;
Node b = nextNode.next;
// a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2])
if (isVertexEquals(a, b) == false
&& isIntersectingPolygon(a, a.getX(), a.getY(), b.getX(), b.getY()) == false
&& linesIntersect(
a.getX(),
a.getY(),
node.getX(),
node.getY(),
nextNode.getX(),
nextNode.getY(),
b.getX(),
b.getY())
&& isLocallyInside(a, b)
&& isLocallyInside(b, a)) {
// compute edges from polygon
boolean abFromPolygon =
(a.next == node)
? a.isNextEdgeFromPolygon
: isEdgeFromPolygon(a, node, mortonOptimized);
boolean bcFromPolygon =
(node.next == b)
? node.isNextEdgeFromPolygon
: isEdgeFromPolygon(node, b, mortonOptimized);
boolean caFromPolygon =
(b.next == a) ? b.isNextEdgeFromPolygon : isEdgeFromPolygon(a, b, mortonOptimized);
tessellation.add(new Triangle(a, abFromPolygon, node, bcFromPolygon, b, caFromPolygon));
// Return the triangulated vertices to the tessellation
tessellation.add(new Triangle(a, abFromPolygon, node, bcFromPolygon, b, caFromPolygon));
// remove two nodes involved
removeNode(node, caFromPolygon);
removeNode(node.next, caFromPolygon);
node = startNode = b;
}
node = node.next;
} while (node != startNode);
return node;
}
/**
* Attempt to split a polygon and independently triangulate each side. Return true if the polygon
* was splitted *
*/
private static final boolean splitEarcut(
final Object polygon,
final Node start,
final List<Triangle> tessellation,
final boolean mortonOptimized) {
// Search for a valid diagonal that divides the polygon into two.
Node searchNode = start;
Node nextNode;
do {
nextNode = searchNode.next;
Node diagonal = nextNode.next;
while (diagonal != searchNode.previous) {
if (searchNode.idx != diagonal.idx && isValidDiagonal(searchNode, diagonal)) {
// Split the polygon into two at the point of the diagonal
Node splitNode =
splitPolygon(
searchNode, diagonal, isEdgeFromPolygon(searchNode, diagonal, mortonOptimized));
// Filter the resulting polygon.
searchNode = filterPoints(searchNode, searchNode.next);
splitNode = filterPoints(splitNode, splitNode.next);
// Attempt to earcut both of the resulting polygons
if (mortonOptimized) {
sortByMortonWithReset(searchNode);
sortByMortonWithReset(splitNode);
}
earcutLinkedList(polygon, searchNode, tessellation, State.INIT, mortonOptimized);
earcutLinkedList(polygon, splitNode, tessellation, State.INIT, mortonOptimized);
// Finish the iterative search
return true;
}
diagonal = diagonal.next;
}
searchNode = searchNode.next;
} while (searchNode != start);
return false;
}
/** Computes if edge defined by a and b overlaps with a polygon edge * */
private static void checkIntersection(Node a, boolean isMorton) {
Node next = a.next;
do {
Node innerNext = next.next;
if (isMorton) {
mortonCheckIntersection(next, innerNext);
} else {
do {
checkIntersectionPoint(next, innerNext);
innerNext = innerNext.next;
} while (innerNext != next.previous);
}
next = next.next;
} while (next != a.previous);
}
/**
* Uses morton code for speed to determine whether or not and edge defined by a and b overlaps
* with a polygon edge
*/
private static final void mortonCheckIntersection(final Node a, final Node b) {
// edge bbox (flip the bits so negative encoded values are < positive encoded values)
int minTX = StrictMath.min(a.x, a.next.x) ^ 0x80000000;
int minTY = StrictMath.min(a.y, a.next.y) ^ 0x80000000;
int maxTX = StrictMath.max(a.x, a.next.x) ^ 0x80000000;
int maxTY = StrictMath.max(a.y, a.next.y) ^ 0x80000000;
// z-order range for the current edge;
long minZ = BitUtil.interleave(minTX, minTY);
long maxZ = BitUtil.interleave(maxTX, maxTY);
// now make sure we don't have other points inside the potential ear;
// look for points inside edge in both directions
Node p = b.previousZ;
Node n = b.nextZ;
while (p != null
&& Long.compareUnsigned(p.morton, minZ) >= 0
&& n != null
&& Long.compareUnsigned(n.morton, maxZ) <= 0) {
checkIntersectionPoint(p, a);
p = p.previousZ;
checkIntersectionPoint(n, a);
n = n.nextZ;
}
// first look for points inside the edge in decreasing z-order
while (p != null && Long.compareUnsigned(p.morton, minZ) >= 0) {
checkIntersectionPoint(p, a);
p = p.previousZ;
}
// then look for points in increasing z-order
while (n != null && Long.compareUnsigned(n.morton, maxZ) <= 0) {
checkIntersectionPoint(n, a);
n = n.nextZ;
}
}
private static void checkIntersectionPoint(final Node a, final Node b) {
if (a == b) {
return;
}
if (Math.max(a.getY(), a.next.getY()) <= Math.min(b.getY(), b.next.getY())
|| Math.min(a.getY(), a.next.getY()) >= Math.max(b.getY(), b.next.getY())
|| Math.max(a.getX(), a.next.getX()) <= Math.min(b.getX(), b.next.getX())
|| Math.min(a.getX(), a.next.getX()) >= Math.max(b.getX(), b.next.getX())) {
return;
}
if (lineCrossesLine(
a.getX(),
a.getY(),
a.next.getX(),
a.next.getY(),
b.getX(),
b.getY(),
b.next.getX(),
b.next.getY())) {
// Line AB represented as a1x + b1y = c1
double a1 = a.next.getY() - a.getY();
double b1 = a.getX() - a.next.getX();
double c1 = a1 * (a.getX()) + b1 * (a.getY());
// Line CD represented as a2x + b2y = c2
double a2 = b.next.getY() - b.getY();
double b2 = b.getX() - b.next.getX();
double c2 = a2 * (b.getX()) + b2 * (b.getY());
double determinant = a1 * b2 - a2 * b1;
assert determinant != 0;
double x = (b2 * c1 - b1 * c2) / determinant;
double y = (a1 * c2 - a2 * c1) / determinant;
throw new IllegalArgumentException("Polygon self-intersection at lat=" + y + " lon=" + x);
}
if (a.isNextEdgeFromPolygon
&& b.isNextEdgeFromPolygon
&& lineOverlapLine(
a.getX(),
a.getY(),
a.next.getX(),
a.next.getY(),
b.getX(),
b.getY(),
b.next.getX(),
b.next.getY())) {
throw new IllegalArgumentException(
"Polygon ring self-intersection at lat=" + a.getY() + " lon=" + a.getX());
}
}
/** Computes if edge defined by a and b overlaps with a polygon edge * */
private static boolean isEdgeFromPolygon(final Node a, final Node b, final boolean isMorton) {
if (isMorton) {
return isMortonEdgeFromPolygon(a, b);
}
Node next = a;
do {
if (isPointInLine(next, next.next, a) && isPointInLine(next, next.next, b)) {
return next.isNextEdgeFromPolygon;
}
if (isPointInLine(next, next.previous, a) && isPointInLine(next, next.previous, b)) {
return next.previous.isNextEdgeFromPolygon;
}
next = next.next;
} while (next != a);
return false;
}
/**
* Uses morton code for speed to determine whether or not and edge defined by a and b overlaps
* with a polygon edge
*/
private static final boolean isMortonEdgeFromPolygon(final Node a, final Node b) {
// edge bbox (flip the bits so negative encoded values are < positive encoded values)
final int minTX = StrictMath.min(a.x, b.x) ^ 0x80000000;
final int minTY = StrictMath.min(a.y, b.y) ^ 0x80000000;
final int maxTX = StrictMath.max(a.x, b.x) ^ 0x80000000;
final int maxTY = StrictMath.max(a.y, b.y) ^ 0x80000000;
// z-order range for the current edge;
final long minZ = BitUtil.interleave(minTX, minTY);
final long maxZ = BitUtil.interleave(maxTX, maxTY);
// now make sure we don't have other points inside the potential ear;
// look for points inside edge in both directions
Node p = a.previousZ;
Node n = a.nextZ;
while (p != null
&& Long.compareUnsigned(p.morton, minZ) >= 0
&& n != null
&& Long.compareUnsigned(n.morton, maxZ) <= 0) {
if (isPointInLine(p, p.next, a) && isPointInLine(p, p.next, b)) {
return p.isNextEdgeFromPolygon;
}
if (isPointInLine(p, p.previous, a) && isPointInLine(p, p.previous, b)) {
return p.previous.isNextEdgeFromPolygon;
}
p = p.previousZ;
if (isPointInLine(n, n.next, a) && isPointInLine(n, n.next, b)) {
return n.isNextEdgeFromPolygon;