Apache Lucene open-source search software
LUCENE-10654: Add new ShapeDocValuesField for LatLonShape and XYShape (#1017)
Nick Knized7fd48c9502c
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 1ae356fcc34..13f2669898a 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -89,6 +89,8 @@ API ChangesNew Features---------------------+* LUCENE-10654: Add new ShapeDocValuesField for LatLonShape and XYShape. (Nick Knize)+* LUCENE-10629: Support match set filtering with a query in MatchingFacetSetCounts. (Stefan Vodita, Shai Erera)Improvements@@ -18755,4 +18757,4 @@ First open source release.The code has been re-organized into a new package and directorystructure for this release. It builds OK, but has not been tested-beyond that since the re-organization.+beyond that since the re-organization.\ No newline at end of filediff --git a/lucene/core/src/java/org/apache/lucene/document/BaseShapeDocValuesQuery.java b/lucene/core/src/java/org/apache/lucene/document/BaseShapeDocValuesQuery.javanew file mode 100644index 00000000000..7f1c4c1c1a2--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/BaseShapeDocValuesQuery.java@@ -0,0 +1,132 @@+/*+ * 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.document;++import java.io.IOException;+import org.apache.lucene.document.ShapeField.QueryRelation;+import org.apache.lucene.geo.Component2D;+import org.apache.lucene.geo.Geometry;+import org.apache.lucene.index.BinaryDocValues;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.LeafReader;+import org.apache.lucene.index.PointValues.Relation;+import org.apache.lucene.search.ConstantScoreScorer;+import org.apache.lucene.search.ConstantScoreWeight;+import org.apache.lucene.search.ScoreMode;+import org.apache.lucene.search.Scorer;+import org.apache.lucene.search.ScorerSupplier;+import org.apache.lucene.search.TwoPhaseIterator;+import org.apache.lucene.util.BytesRef;++/**+ * Base query class for ShapeDocValues queries. Concrete implementations include: {@link+ * LatLonShapeDocValuesQuery} and {@link XYShapeDocValuesQuery}+ *+ * @lucene.experimental+ */+abstract class BaseShapeDocValuesQuery extends SpatialQuery {++ BaseShapeDocValuesQuery(String field, QueryRelation queryRelation, Geometry... geometries) {+ super(field, validateRelation(queryRelation), geometries);+ }++ private static QueryRelation validateRelation(QueryRelation queryRelation) {+ if (queryRelation == QueryRelation.CONTAINS) {+ throw new IllegalArgumentException(+ "ShapeDocValuesBoundingBoxQuery does not yet support CONTAINS queries");+ }+ return queryRelation;+ }++ protected abstract ShapeDocValues getShapeDocValues(BytesRef binaryValue);++ @Override+ protected ScorerSupplier getScorerSupplier(+ LeafReader reader,+ SpatialVisitor spatialVisitor,+ ScoreMode scoreMode,+ ConstantScoreWeight weight,+ float boost,+ float score)+ throws IOException {+ final BinaryDocValues values = reader.getBinaryDocValues(field);+ if (values == null) {+ return null;+ }+ final FieldInfo fieldInfo = reader.getFieldInfos().fieldInfo(field);+ if (fieldInfo == null) {+ // No docs in this segment indexed this field at all+ return null;+ }++ final TwoPhaseIterator iterator =+ new TwoPhaseIterator(values) {+ @Override+ public boolean matches() throws IOException {+ return match(getShapeDocValues(values.binaryValue()));+ }++ @Override+ public float matchCost() {+ return BaseShapeDocValuesQuery.this.matchCost();+ }+ };+ return new ScorerSupplier() {++ @Override+ public Scorer get(long leadCost) {+ return new ConstantScoreScorer(weight, boost, scoreMode, iterator);+ }++ @Override+ public long cost() {+ return reader.maxDoc();+ }+ };+ }++ /** matches the doc value to the query; overridable to provide custom query logic */+ protected boolean match(ShapeDocValues shapeDocValues) throws IOException {+ boolean result = matchesComponent(shapeDocValues, queryRelation, queryComponent2D);+ if (queryRelation == QueryRelation.DISJOINT) {+ return result == false;+ }+ return result;+ }++ /** compute the cost of the query; overrideable */+ protected float matchCost() {+ // multiply comparisons (estimated 60) by number of terms (averaged at 100)+ // todo: revisit+ return 60 * 100;+ }++ protected boolean matchesComponent(+ final ShapeDocValues dv,+ final ShapeField.QueryRelation queryRelation,+ final Component2D component)+ throws IOException {+ Relation r = dv.relate(component);+ if (r != Relation.CELL_OUTSIDE_QUERY) {+ if (queryRelation == ShapeField.QueryRelation.WITHIN) {+ return r == Relation.CELL_INSIDE_QUERY;+ }+ return true;+ }+ return false;+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonPointQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonPointQuery.javaindex 96c9023c463..604e61ce484 100644--- a/lucene/core/src/java/org/apache/lucene/document/LatLonPointQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonPointQuery.java@@ -27,6 +27,7 @@ import java.util.function.Predicate;import org.apache.lucene.document.ShapeField.QueryRelation;import org.apache.lucene.geo.Component2D;import org.apache.lucene.geo.GeoEncodingUtils;+import org.apache.lucene.geo.Geometry;import org.apache.lucene.geo.LatLonGeometry;import org.apache.lucene.geo.Line;import org.apache.lucene.geo.Point;@@ -41,53 +42,62 @@ import org.apache.lucene.util.NumericUtils;* <p>The field must be indexed using one or more {@link LatLonPoint} added per document.*/final class LatLonPointQuery extends SpatialQuery {- private final LatLonGeometry[] geometries;- private final Component2D component2D;/*** Creates a query that matches all indexed shapes to the provided array of {@link LatLonGeometry}*/LatLonPointQuery(String field, QueryRelation queryRelation, LatLonGeometry... geometries) {- super(field, queryRelation);- if (queryRelation == QueryRelation.WITHIN) {- for (LatLonGeometry geometry : geometries) {- if (geometry instanceof Line) {- // TODO: line queries do not support within relations- throw new IllegalArgumentException(- "LatLonPointQuery does not support "- + QueryRelation.WITHIN- + " queries with line geometries");+ super(field, queryRelation, validateGeometry(queryRelation, geometries));+ }++ private static LatLonGeometry[] validateGeometry(+ QueryRelation queryRelation, LatLonGeometry... geometries) {+ if (geometries != null) {+ if (queryRelation == QueryRelation.WITHIN) {+ for (LatLonGeometry geometry : geometries) {+ if (geometry instanceof Line) {+ // TODO: line queries do not support within relations+ throw new IllegalArgumentException(+ "LatLonPointQuery does not support "+ + QueryRelation.WITHIN+ + " queries with line geometries");+ }}}- }- if (queryRelation == ShapeField.QueryRelation.CONTAINS) {- for (LatLonGeometry geometry : geometries) {- if ((geometry instanceof Point) == false) {- throw new IllegalArgumentException(- "LatLonPointQuery does not support "- + ShapeField.QueryRelation.CONTAINS- + " queries with non-points geometries");+ if (queryRelation == ShapeField.QueryRelation.CONTAINS) {+ for (LatLonGeometry geometry : geometries) {+ if ((geometry instanceof Point) == false) {+ throw new IllegalArgumentException(+ "LatLonPointQuery does not support "+ + ShapeField.QueryRelation.CONTAINS+ + " queries with non-points geometries");+ }}}}- this.component2D = LatLonGeometry.create(geometries);- this.geometries = geometries.clone();++ return geometries;+ }++ @Override+ protected Component2D createComponent2D(Geometry... geometries) {+ return LatLonGeometry.create((LatLonGeometry[]) geometries);}@Overrideprotected SpatialVisitor getSpatialVisitor() {final GeoEncodingUtils.Component2DPredicate component2DPredicate =- GeoEncodingUtils.createComponentPredicate(component2D);+ GeoEncodingUtils.createComponentPredicate(queryComponent2D);// bounding box over all geometries, this can speed up tree intersection/cheaply improve// approximation for complex multi-geometriesfinal byte[] minLat = new byte[Integer.BYTES];final byte[] maxLat = new byte[Integer.BYTES];final byte[] minLon = new byte[Integer.BYTES];final byte[] maxLon = new byte[Integer.BYTES];- NumericUtils.intToSortableBytes(encodeLatitude(component2D.getMinY()), minLat, 0);- NumericUtils.intToSortableBytes(encodeLatitude(component2D.getMaxY()), maxLat, 0);- NumericUtils.intToSortableBytes(encodeLongitude(component2D.getMinX()), minLon, 0);- NumericUtils.intToSortableBytes(encodeLongitude(component2D.getMaxX()), maxLon, 0);+ NumericUtils.intToSortableBytes(encodeLatitude(queryComponent2D.getMinY()), minLat, 0);+ NumericUtils.intToSortableBytes(encodeLatitude(queryComponent2D.getMaxY()), maxLat, 0);+ NumericUtils.intToSortableBytes(encodeLongitude(queryComponent2D.getMinX()), minLon, 0);+ NumericUtils.intToSortableBytes(encodeLongitude(queryComponent2D.getMaxX()), maxLon, 0);return new SpatialVisitor() {@@ -106,7 +116,7 @@ final class LatLonPointQuery extends SpatialQuery {double cellMaxLat = decodeLatitude(maxPackedValue, 0);double cellMaxLon = decodeLongitude(maxPackedValue, Integer.BYTES);- return component2D.relate(cellMinLon, cellMaxLon, cellMinLat, cellMaxLat);+ return queryComponent2D.relate(cellMinLon, cellMaxLon, cellMinLat, cellMaxLat);}@Override@@ -128,7 +138,7 @@ final class LatLonPointQuery extends SpatialQuery {@Overrideprotected Function<byte[], Component2D.WithinRelation> contains() {return packedValue ->- component2D.withinPoint(+ queryComponent2D.withinPoint(GeoEncodingUtils.decodeLongitude(NumericUtils.sortableBytesToInt(packedValue, Integer.BYTES)),GeoEncodingUtils.decodeLatitude(NumericUtils.sortableBytesToInt(packedValue, 0)));diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShape.javaindex 8b1846140bf..d749b7c52b5 100644--- a/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java@@ -19,6 +19,7 @@ package org.apache.lucene.document;import static org.apache.lucene.geo.GeoEncodingUtils.encodeLatitude;import static org.apache.lucene.geo.GeoEncodingUtils.encodeLongitude;+import java.util.ArrayList;import java.util.List;import org.apache.lucene.document.ShapeField.QueryRelation; // javadocimport org.apache.lucene.document.ShapeField.Triangle;@@ -35,6 +36,7 @@ import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.Query;+import org.apache.lucene.util.BytesRef;/*** An geo shape utility class for indexing and searching gis geometries whose vertices are latitude,@@ -44,10 +46,18 @@ import org.apache.lucene.search.Query;** <ul>* <li>{@link #createIndexableFields(String, Polygon)} for indexing a geo polygon.+ * <li>{@link #createDocValueField(String, Polygon)} for indexing a geo polygon doc value field.* <li>{@link #createIndexableFields(String, Polygon, boolean)} for indexing a geo polygon with* the possibility of checking for self-intersections.+ * <li>{@link #createIndexableFields(String, Polygon, boolean)} for indexing a geo polygon doc+ * value field with the possibility of checking for self-intersections.* <li>{@link #createIndexableFields(String, Line)} for indexing a geo linestring.+ * <li>{@link #createDocValueField(String, Line)} for indexing a geo linestring doc value.* <li>{@link #createIndexableFields(String, double, double)} for indexing a lat, lon geo point.+ * <li>{@link #createDocValueField(String, double, double)} for indexing a lat, lon geo point doc+ * value.+ * <li>{@link #createDocValueField(String, BytesRef)} for indexing a cartesian doc value from+ * existing encoding.* <li>{@link #newBoxQuery newBoxQuery()} for matching geo shapes that have some {@link* QueryRelation} with a bounding box.* <li>{@link #newLineQuery newLineQuery()} for matching geo shapes that have some {@link@@ -75,6 +85,11 @@ public class LatLonShape {return createIndexableFields(fieldName, polygon, false);}+ /** create doc value field for lat lon polygon geometry without creating indexable fields */+ public static LatLonShapeDocValuesField createDocValueField(String fieldName, Polygon polygon) {+ return createDocValueField(fieldName, polygon, false);+ }+/*** create indexable fields for polygon geometry. If {@code checkSelfIntersections} is set to true,* the validity of the provided polygon is checked with a small performance penalty.@@ -91,6 +106,30 @@ public class LatLonShape {return fields;}+ /** create doc value field for lat lon polygon geometry without creating indexable fields. */+ public static LatLonShapeDocValuesField createDocValueField(+ String fieldName, Polygon polygon, boolean checkSelfIntersections) {+ List<Tessellator.Triangle> tessellation =+ Tessellator.tessellate(polygon, checkSelfIntersections);+ ArrayList<ShapeField.DecodedTriangle> triangles = new ArrayList<>(tessellation.size());+ for (Tessellator.Triangle t : tessellation) {+ ShapeField.DecodedTriangle dt = new ShapeField.DecodedTriangle();+ dt.type = ShapeField.DecodedTriangle.TYPE.TRIANGLE;+ dt.setValues(+ t.getEncodedX(0),+ t.getEncodedY(0),+ t.isEdgefromPolygon(0),+ t.getEncodedX(1),+ t.getEncodedY(1),+ t.isEdgefromPolygon(0),+ t.getEncodedX(2),+ t.getEncodedY(2),+ t.isEdgefromPolygon(2));+ triangles.add(dt);+ }+ return new LatLonShapeDocValuesField(fieldName, triangles);+ }+/** create indexable fields for line geometry */public static Field[] createIndexableFields(String fieldName, Line line) {int numPoints = line.numPoints();@@ -110,6 +149,29 @@ public class LatLonShape {return fields;}+ /** create doc value field for lat lon line geometry without creating indexable fields. */+ public static LatLonShapeDocValuesField createDocValueField(String fieldName, Line line) {+ int numPoints = line.numPoints();+ List<ShapeField.DecodedTriangle> triangles = new ArrayList<>(numPoints - 1);+ // create "flat" triangles+ for (int i = 0, j = 1; j < numPoints; ++i, ++j) {+ ShapeField.DecodedTriangle t = new ShapeField.DecodedTriangle();+ t.type = ShapeField.DecodedTriangle.TYPE.LINE;+ t.setValues(+ encodeLongitude(line.getLon(i)),+ encodeLatitude(line.getLat(i)),+ true,+ encodeLongitude(line.getLon(j)),+ encodeLatitude(line.getLat(j)),+ true,+ encodeLongitude(line.getLon(i)),+ encodeLatitude(line.getLat(i)),+ true);+ triangles.add(t);+ }+ return new LatLonShapeDocValuesField(fieldName, triangles);+ }+/** create indexable fields for point geometry */public static Field[] createIndexableFields(String fieldName, double lat, double lon) {return new Field[] {@@ -124,6 +186,54 @@ public class LatLonShape {};}+ /** create doc value field for lat lon line geometry without creating indexable fields. */+ public static LatLonShapeDocValuesField createDocValueField(+ String fieldName, double lat, double lon) {+ List<ShapeField.DecodedTriangle> triangles = new ArrayList<>(1);+ ShapeField.DecodedTriangle t = new ShapeField.DecodedTriangle();+ t.type = ShapeField.DecodedTriangle.TYPE.POINT;+ t.setValues(+ encodeLongitude(lon),+ encodeLatitude(lat),+ true,+ encodeLongitude(lon),+ encodeLatitude(lat),+ true,+ encodeLongitude(lon),+ encodeLatitude(lat),+ true);+ triangles.add(t);+ return new LatLonShapeDocValuesField(fieldName, triangles);+ }++ /** create a {@link LatLonShapeDocValuesField} from an existing encoded representation */+ public static LatLonShapeDocValuesField createDocValueField(+ String fieldName, BytesRef binaryValue) {+ return new LatLonShapeDocValuesField(fieldName, binaryValue);+ }++ /** create a {@link LatLonShapeDocValuesField} from an existing tessellation */+ public static LatLonShapeDocValuesField createDocValueField(+ String fieldName, List<ShapeField.DecodedTriangle> tessellation) {+ return new LatLonShapeDocValuesField(fieldName, tessellation);+ }++ /** create a shape docvalue field from indexable fields */+ public static LatLonShapeDocValuesField createDocValueField(+ String fieldName, Field[] indexableFields) {+ ArrayList<ShapeField.DecodedTriangle> tess = new ArrayList<>(indexableFields.length);+ final byte[] scratch = new byte[7 * Integer.BYTES];+ for (Field f : indexableFields) {+ BytesRef br = f.binaryValue();+ assert br.length == 7 * ShapeField.BYTES;+ System.arraycopy(br.bytes, br.offset, scratch, 0, 7 * ShapeField.BYTES);+ ShapeField.DecodedTriangle t = new ShapeField.DecodedTriangle();+ ShapeField.decodeTriangle(scratch, t);+ tess.add(t);+ }+ return new LatLonShapeDocValuesField(fieldName, tess);+ }+/** create a query to find all indexed geo shapes that intersect a defined bounding box * */public static Query newBoxQuery(String field,@@ -148,6 +258,30 @@ public class LatLonShape {return new LatLonShapeBoundingBoxQuery(field, queryRelation, rectangle);}+ /** create a docvalue query to find all geo shapes that intersect a defined bounding box * */+ public static Query newSlowDocValuesBoxQuery(+ String field,+ QueryRelation queryRelation,+ double minLatitude,+ double maxLatitude,+ double minLongitude,+ double maxLongitude) {+ if (queryRelation == QueryRelation.CONTAINS && minLongitude > maxLongitude) {+ BooleanQuery.Builder builder = new BooleanQuery.Builder();+ builder.add(+ newBoxQuery(+ field, queryRelation, minLatitude, maxLatitude, minLongitude, GeoUtils.MAX_LON_INCL),+ BooleanClause.Occur.MUST);+ builder.add(+ newBoxQuery(+ field, queryRelation, minLatitude, maxLatitude, GeoUtils.MIN_LON_INCL, maxLongitude),+ BooleanClause.Occur.MUST);+ return builder.build();+ }+ return new LatLonShapeDocValuesQuery(+ field, queryRelation, new Rectangle(minLatitude, maxLatitude, minLongitude, maxLongitude));+ }+/*** create a query to find all indexed geo shapes that intersect a provided linestring (or array of* linestrings) note: does not support dateline crossingdiff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.javaindex 54ca3d2d13f..f4d9bf4b5c9 100644--- a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeBoundingBoxQuery.java@@ -28,7 +28,8 @@ import java.util.function.Function;import java.util.function.Predicate;import org.apache.lucene.document.ShapeField.QueryRelation;import org.apache.lucene.geo.Component2D;-import org.apache.lucene.geo.GeoUtils;+import org.apache.lucene.geo.Geometry;+import org.apache.lucene.geo.LatLonGeometry;import org.apache.lucene.geo.Rectangle;import org.apache.lucene.index.PointValues.Relation;import org.apache.lucene.util.ArrayUtil;@@ -39,19 +40,27 @@ import org.apache.lucene.util.NumericUtils;** <p>The field must be indexed using {@link* org.apache.lucene.document.LatLonShape#createIndexableFields} added per document.+ *+ * @lucene.internal*/final class LatLonShapeBoundingBoxQuery extends SpatialQuery {private final Rectangle rectangle;LatLonShapeBoundingBoxQuery(String field, QueryRelation queryRelation, Rectangle rectangle) {- super(field, queryRelation);+ super(field, queryRelation, rectangle);this.rectangle = rectangle;}+ @Override+ protected Component2D createComponent2D(Geometry... geometries) {+ // todo: this isn't actually used by the query so maybe we can just return null?+ return LatLonGeometry.create((Rectangle) geometries[0]);+ }+@Overrideprotected SpatialVisitor getSpatialVisitor() {- final EncodedRectangle encodedRectangle =- new EncodedRectangle(+ final EncodedLatLonRectangle encodedRectangle =+ new EncodedLatLonRectangle(rectangle.minLat, rectangle.maxLat, rectangle.minLon, rectangle.maxLon);return new SpatialVisitor() {@@ -224,26 +233,20 @@ final class LatLonShapeBoundingBoxQuery extends SpatialQuery {}/** Holds spatial logic for a bounding box that works in the encoded space */- private static class EncodedRectangle {+ private static class EncodedLatLonRectangle extends EncodedRectangle {protected final byte[] bbox;private final byte[] west;- protected final int minX;- protected final int maxX;- protected final int minY;- protected final int maxY;- private final boolean crossesDateline;- EncodedRectangle(double minLat, double maxLat, double minLon, double maxLon) {+ EncodedLatLonRectangle(double minLat, double maxLat, double minLon, double maxLon) {+ super(+ encodeLongitudeCeil(validateMinLon(minLon, maxLon)),+ encodeLongitude(maxLon),+ encodeLatitudeCeil(minLat),+ encodeLatitude(maxLat),+ validateMinLon(minLon, maxLon) > maxLon);this.bbox = new byte[4 * BYTES];- if (minLon == 180.0 && minLon > maxLon) {- minLon = -180;- }- this.minX = encodeLongitudeCeil(minLon);- this.maxX = encodeLongitude(maxLon);- this.minY = encodeLatitudeCeil(minLat);- this.maxY = encodeLatitude(maxLat);- this.crossesDateline = minLon > maxLon;- if (this.crossesDateline) {++ if (wrapsCoordinateSystem) {// crossing dateline is split into east/west boxesthis.west = new byte[4 * BYTES];encode(MIN_LON_ENCODED, this.maxX, this.minY, this.maxY, this.west);@@ -254,6 +257,14 @@ final class LatLonShapeBoundingBoxQuery extends SpatialQuery {}}+ /** returns a valid minLon (-180) if the bbox splits the dateline */+ private static double validateMinLon(double minLon, double maxLon) {+ if (minLon == 180.0 && minLon > maxLon) {+ return -180D;+ }+ return minLon;+ }+/** encodes a bounding box into the provided byte array */private static void encode(final int minX, final int maxX, final int minY, final int maxY, byte[] b) {@@ -267,7 +278,7 @@ final class LatLonShapeBoundingBoxQuery extends SpatialQuery {}private boolean crossesDateline() {- return crossesDateline;+ return wrapsCoordinateSystem;}/** compare this to a provided range bounding box */@@ -393,192 +404,5 @@ final class LatLonShapeBoundingBoxQuery extends SpatialQuery {|| ArrayUtil.compareUnsigned4(minTriangle, minYOffset, bbox, 2 * BYTES) > 0|| ArrayUtil.compareUnsigned4(maxTriangle, maxYOffset, bbox, 0) < 0;}-- /** Checks if the rectangle contains the provided point */- boolean contains(int x, int y) {- if (y < minY || y > maxY) {- return false;- }- if (crossesDateline()) {- return (x > maxX && x < minX) == false;- } else {- return (x > maxX || x < minX) == false;- }- }-- /** Checks if the rectangle intersects the provided LINE */- boolean intersectsLine(int aX, int aY, int bX, int bY) {- if (contains(aX, aY) || contains(bX, bY)) {- return true;- }- // check bounding boxes are disjoint- if (StrictMath.max(aY, bY) < minY || StrictMath.min(aY, bY) > maxY) {- return false;- }- if (crossesDateline) { // crosses dateline- if (StrictMath.min(aX, bX) > maxX && StrictMath.max(aX, bX) < minX) {- return false;- }- } else {- if (StrictMath.min(aX, bX) > maxX || StrictMath.max(aX, bX) < minX) {- return false;- }- }- // expensive part- return edgeIntersectsQuery(aX, aY, bX, bY);- }-- /** Checks if the rectangle intersects the provided triangle */- boolean intersectsTriangle(int aX, int aY, int bX, int bY, int cX, int cY) {- // query contains any triangle points- if (contains(aX, aY) || contains(bX, bY) || contains(cX, cY)) {- return true;- }- // check bounding box of triangle- int tMinY = StrictMath.min(StrictMath.min(aY, bY), cY);- int tMaxY = StrictMath.max(StrictMath.max(aY, bY), cY);- // check bounding boxes are disjoint- if (tMaxY < minY || tMinY > maxY) {- return false;- }- int tMinX = StrictMath.min(StrictMath.min(aX, bX), cX);- int tMaxX = StrictMath.max(StrictMath.max(aX, bX), cX);- if (crossesDateline) { // crosses dateline- if (tMinX > maxX && tMaxX < minX) {- return false;- }- } else {- if (tMinX > maxX || tMaxX < minX) {- return false;- }- }- // expensive part- return Component2D.pointInTriangle(- tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY)- || edgeIntersectsQuery(aX, aY, bX, bY)- || edgeIntersectsQuery(bX, bY, cX, cY)- || edgeIntersectsQuery(cX, cY, aX, aY);- }-- /** Checks if the rectangle contains the provided LINE */- boolean containsLine(int aX, int aY, int bX, int bY) {- if (aY < minY || bY < minY || aY > maxY || bY > maxY) {- return false;- }- if (crossesDateline) { // crosses dateline- return (aX >= minX && bX >= minX) || (aX <= maxX && bX <= maxX);- } else {- return aX >= minX && bX >= minX && aX <= maxX && bX <= maxX;- }- }-- /** Checks if the rectangle contains the provided triangle */- boolean containsTriangle(int aX, int aY, int bX, int bY, int cX, int cY) {- if (aY < minY || bY < minY || cY < minY || aY > maxY || bY > maxY || cY > maxY) {- return false;- }- if (crossesDateline) { // crosses dateline- return (aX >= minX && bX >= minX && cX >= minX) || (aX <= maxX && bX <= maxX && cX <= maxX);- } else {- return aX >= minX && bX >= minX && cX >= minX && aX <= maxX && bX <= maxX && cX <= maxX;- }- }-- /** Returns the Within relation to the provided triangle */- Component2D.WithinRelation withinLine(int aX, int aY, boolean ab, int bX, int bY) {- if (contains(aX, aY) || contains(bX, bY)) {- return Component2D.WithinRelation.NOTWITHIN;- }- if (ab == true && edgeIntersectsBox(aX, aY, bX, bY, minX, maxX, minY, maxY) == true) {- return Component2D.WithinRelation.NOTWITHIN;- }- return Component2D.WithinRelation.DISJOINT;- }-- /** Returns the Within relation to the provided triangle */- Component2D.WithinRelation withinTriangle(- int aX, int aY, boolean ab, int bX, int bY, boolean bc, int cX, int cY, boolean ca) {- // Points belong to the shape so if points are inside the rectangle then it cannot be within.- if (contains(aX, aY) || contains(bX, bY) || contains(cX, cY)) {- return Component2D.WithinRelation.NOTWITHIN;- }-- // Bounding boxes disjoint?- int tMinY = StrictMath.min(StrictMath.min(aY, bY), cY);- int tMaxY = StrictMath.max(StrictMath.max(aY, bY), cY);- // check bounding boxes are disjoint- if (tMaxY < minY || tMinY > maxY) {- return Component2D.WithinRelation.DISJOINT;- }- int tMinX = StrictMath.min(StrictMath.min(aX, bX), cX);- int tMaxX = StrictMath.max(StrictMath.max(aX, bX), cX);- if (crossesDateline) { // crosses dateline- if (tMinX > maxX && tMaxX < minX) {- return Component2D.WithinRelation.DISJOINT;- }- } else {- if (tMinX > maxX || tMaxX < minX) {- return Component2D.WithinRelation.DISJOINT;- }- }- // If any of the edges intersects an edge belonging to the shape then it cannot be within.- Component2D.WithinRelation relation = Component2D.WithinRelation.DISJOINT;- if (edgeIntersectsBox(aX, aY, bX, bY, minX, maxX, minY, maxY) == true) {- if (ab == true) {- return Component2D.WithinRelation.NOTWITHIN;- } else {- relation = Component2D.WithinRelation.CANDIDATE;- }- }- if (edgeIntersectsBox(bX, bY, cX, cY, minX, maxX, minY, maxY) == true) {- if (bc == true) {- return Component2D.WithinRelation.NOTWITHIN;- } else {- relation = Component2D.WithinRelation.CANDIDATE;- }- }-- if (edgeIntersectsBox(cX, cY, aX, aY, minX, maxX, minY, maxY) == true) {- if (ca == true) {- return Component2D.WithinRelation.NOTWITHIN;- } else {- relation = Component2D.WithinRelation.CANDIDATE;- }- }- // Check if shape is within the triangle- if (relation == Component2D.WithinRelation.CANDIDATE- || Component2D.pointInTriangle(- tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY)) {- return Component2D.WithinRelation.CANDIDATE;- }- return relation;- }-- /** returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the query */- private boolean edgeIntersectsQuery(int aX, int aY, int bX, int bY) {- if (crossesDateline) {- return edgeIntersectsBox(aX, aY, bX, bY, MIN_LON_ENCODED, this.maxX, this.minY, this.maxY)- || edgeIntersectsBox(aX, aY, bX, bY, this.minX, MAX_LON_ENCODED, this.minY, this.maxY);- }- return edgeIntersectsBox(aX, aY, bX, bY, this.minX, this.maxX, this.minY, this.maxY);- }-- /** returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the box */- private static boolean edgeIntersectsBox(- int aX, int aY, int bX, int bY, int minX, int maxX, int minY, int maxY) {- if (Math.max(aX, bX) < minX- || Math.min(aX, bX) > maxX- || Math.min(aY, bY) > maxY- || Math.max(aY, bY) < minY) {- return false;- }- return GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, maxY, maxX, maxY)- || // top- GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, maxY, maxX, minY)- || // bottom- GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, minY, minX, minY)- || // left- GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, minY, minX, maxY); // right- }}}diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValues.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValues.javanew file mode 100644index 00000000000..7fab9c3d958--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValues.java@@ -0,0 +1,97 @@+/*+ * 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.document;++import java.util.List;+import org.apache.lucene.geo.GeoEncodingUtils;+import org.apache.lucene.geo.Point;+import org.apache.lucene.geo.Rectangle;+import org.apache.lucene.util.BytesRef;++/**+ * A concrete implementation of {@link ShapeDocValues} for storing binary doc value representation+ * of {@link LatLonShape} geometries in a {@link LatLonShapeDocValuesField}+ *+ * <p>Note: This class cannot be instantiated directly. See {@link LatLonShape} for factory API+ * based on different geometries.+ *+ * @lucene.experimental+ */+public final class LatLonShapeDocValues extends ShapeDocValues {+ /** protected ctor for instantiating a lat lon doc value based on a tessellation */+ protected LatLonShapeDocValues(List<ShapeField.DecodedTriangle> tessellation) {+ super(tessellation);+ }++ /**+ * protected ctor for instantiating a lat lon doc value based on an already retrieved binary+ * format+ */+ protected LatLonShapeDocValues(BytesRef binaryValue) {+ super(binaryValue);+ }++ @Override+ public Point getCentroid() {+ return (Point) centroid;+ }++ @Override+ public Rectangle getBoundingBox() {+ return (Rectangle) boundingBox;+ }++ @Override+ protected Point computeCentroid() {+ Encoder encoder = getEncoder();+ return new Point(+ encoder.decodeY(getEncodedCentroidY()), encoder.decodeX(getEncodedCentroidX()));+ }++ @Override+ protected Rectangle computeBoundingBox() {+ Encoder encoder = getEncoder();+ return new Rectangle(+ encoder.decodeY(getEncodedMinY()), encoder.decodeY(getEncodedMaxY()),+ encoder.decodeX(getEncodedMinX()), encoder.decodeX(getEncodedMaxX()));+ }++ @Override+ protected Encoder getEncoder() {+ return new Encoder() {+ @Override+ public int encodeX(double x) {+ return GeoEncodingUtils.encodeLongitude(x);+ }++ @Override+ public int encodeY(double y) {+ return GeoEncodingUtils.encodeLatitude(y);+ }++ @Override+ public double decodeX(int encoded) {+ return GeoEncodingUtils.decodeLongitude(encoded);+ }++ @Override+ public double decodeY(int encoded) {+ return GeoEncodingUtils.decodeLatitude(encoded);+ }+ };+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValuesField.javanew file mode 100644index 00000000000..16f066a6e17--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValuesField.java@@ -0,0 +1,86 @@+/*+ * 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.document;++import java.util.List;+import org.apache.lucene.geo.GeoEncodingUtils;+import org.apache.lucene.geo.Line;+import org.apache.lucene.geo.Point;+import org.apache.lucene.geo.Polygon;+import org.apache.lucene.geo.Rectangle;+import org.apache.lucene.index.PointValues;+import org.apache.lucene.util.BytesRef;++/**+ * Concrete implementation of a {@link ShapeDocValuesField} for geographic geometries.+ *+ * <p>This field should be instantiated through {@link LatLonShape#createDocValueField(String,+ * Line)}+ *+ * <ul>+ * <li>{@link LatLonShape#createDocValueField(String, Polygon)} for indexing a geographic polygon+ * doc value field.+ * <li>{@link LatLonShape#createDocValueField(String, Line)} for indexing a geographic linestring+ * doc value.+ * <li>{@link LatLonShape#createDocValueField(String, double, double)} for indexing a lat, lon+ * geographic point doc value.+ * <li>{@link LatLonShape#createDocValueField(String, List)} for indexing a geographic doc value+ * from a precomputed tessellation.+ * <li>{@link LatLonShape#createDocValueField(String, BytesRef)} for indexing a geographic doc+ * value from existing encoding.+ * </ul>+ *+ * <b>WARNING</b>: Like {@link LatLonShape}, vertex values are indexed with some loss of precision+ * from the original {@code double} values.+ *+ * @see PointValues+ * @see LatLonDocValuesField+ * @lucene.experimental+ */+public final class LatLonShapeDocValuesField extends ShapeDocValuesField {+ /** constructs a {@code LatLonShapeDocValueField} from a pre-tessellated geometry */+ protected LatLonShapeDocValuesField(String name, List<ShapeField.DecodedTriangle> tessellation) {+ super(name, new LatLonShapeDocValues(tessellation));+ }++ /** Creates a {@code LatLonShapeDocValueField} from a given serialized value */+ protected LatLonShapeDocValuesField(String name, BytesRef binaryValue) {+ super(name, new LatLonShapeDocValues(binaryValue));+ }++ /** retrieves the centroid location for the geometry */+ @Override+ public Point getCentroid() {+ return (Point) shapeDocValues.getCentroid();+ }++ /** retrieves the bounding box for the geometry */+ @Override+ public Rectangle getBoundingBox() {+ return (Rectangle) shapeDocValues.getBoundingBox();+ }++ @Override+ protected double decodeX(int encoded) {+ return GeoEncodingUtils.decodeLongitude(encoded);+ }++ @Override+ protected double decodeY(int encoded) {+ return GeoEncodingUtils.decodeLatitude(encoded);+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValuesQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValuesQuery.javanew file mode 100644index 00000000000..1a9fc0ff064--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeDocValuesQuery.java@@ -0,0 +1,59 @@+/*+ * 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.document;++import org.apache.lucene.document.ShapeField.QueryRelation;+import org.apache.lucene.geo.Component2D;+import org.apache.lucene.geo.Geometry;+import org.apache.lucene.geo.LatLonGeometry;+import org.apache.lucene.util.BytesRef;++/**+ * Bounding Box query for {@link ShapeDocValuesField} representing {@link XYShape}+ *+ * @lucene.experimental+ */+final class LatLonShapeDocValuesQuery extends BaseShapeDocValuesQuery {+ LatLonShapeDocValuesQuery(+ String field, QueryRelation queryRelation, LatLonGeometry... geometries) {+ super(field, queryRelation, geometries);+ }++ @Override+ protected Component2D createComponent2D(Geometry... geometries) {+ return LatLonGeometry.create((LatLonGeometry[]) geometries);+ }++ @Override+ protected ShapeDocValues getShapeDocValues(BytesRef binaryValue) {+ return new LatLonShapeDocValues(binaryValue);+ }++ /** compute the cost of the query */+ @Override+ public float matchCost() {+ // multiply number of terms (averaged at 100) by worst number of comparisons (estimated 60+ // comparisons)+ // todo: revisit?+ return 60 * 100;+ }++ @Override+ protected SpatialVisitor getSpatialVisitor() {+ return LatLonShapeQuery.getSpatialVisitor(queryComponent2D);+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.javaindex af7c87bb36a..35cfe45c395 100644--- a/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShapeQuery.java@@ -16,12 +16,12 @@*/package org.apache.lucene.document;-import java.util.Arrays;import java.util.function.Function;import java.util.function.Predicate;import org.apache.lucene.document.ShapeField.QueryRelation;import org.apache.lucene.geo.Component2D;import org.apache.lucene.geo.GeoEncodingUtils;+import org.apache.lucene.geo.Geometry;import org.apache.lucene.geo.LatLonGeometry;import org.apache.lucene.geo.Line;import org.apache.lucene.index.PointValues.Relation;@@ -32,17 +32,21 @@ import org.apache.lucene.util.NumericUtils;* specified array of {@link LatLonGeometry}.** <p>The field must be indexed using {@link LatLonShape#createIndexableFields} added per document.+ *+ * @lucene.internal*/final class LatLonShapeQuery extends SpatialQuery {- private final LatLonGeometry[] geometries;- private final Component2D component2D;/*** Creates a query that matches all indexed shapes to the provided array of {@link LatLonGeometry}*/LatLonShapeQuery(String field, QueryRelation queryRelation, LatLonGeometry... geometries) {- super(field, queryRelation);- if (queryRelation == QueryRelation.WITHIN) {+ super(field, queryRelation, validateGeometries(queryRelation, geometries));+ }++ private static LatLonGeometry[] validateGeometries(+ QueryRelation queryRelation, LatLonGeometry... geometries) {+ if (geometries != null && queryRelation == QueryRelation.WITHIN) {for (LatLonGeometry geometry : geometries) {if (geometry instanceof Line) {// TODO: line queries do not support within relations@@ -53,13 +57,15 @@ final class LatLonShapeQuery extends SpatialQuery {}}}- this.component2D = LatLonGeometry.create(geometries);- this.geometries = geometries.clone();+ return geometries;}@Override- protected SpatialVisitor getSpatialVisitor() {+ protected Component2D createComponent2D(Geometry... geometries) {+ return LatLonGeometry.create((LatLonGeometry[]) geometries);+ }+ static SpatialVisitor getSpatialVisitor(Component2D component2D) {return new SpatialVisitor() {@Overrideprotected Relation relate(byte[] minTriangle, byte[] maxTriangle) {@@ -205,33 +211,7 @@ final class LatLonShapeQuery extends SpatialQuery {}@Override- public String toString(String field) {- final StringBuilder sb = new StringBuilder();- sb.append(getClass().getSimpleName());- sb.append(':');- if (this.field.equals(field) == false) {- sb.append(" field=");- sb.append(this.field);- sb.append(':');- }- sb.append("[");- for (int i = 0; i < geometries.length; i++) {- sb.append(geometries[i].toString());- sb.append(',');- }- sb.append(']');- return sb.toString();- }-- @Override- protected boolean equalsTo(Object o) {- return super.equalsTo(o) && Arrays.equals(geometries, ((LatLonShapeQuery) o).geometries);- }-- @Override- public int hashCode() {- int hash = super.hashCode();- hash = 31 * hash + Arrays.hashCode(geometries);- return hash;+ protected SpatialVisitor getSpatialVisitor() {+ return getSpatialVisitor(queryComponent2D);}}diff --git a/lucene/core/src/java/org/apache/lucene/document/ShapeDocValues.java b/lucene/core/src/java/org/apache/lucene/document/ShapeDocValues.javanew file mode 100644index 00000000000..0f9651607c7--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/ShapeDocValues.java@@ -0,0 +1,955 @@+/*+ * 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.document;++import java.io.IOException;+import java.util.ArrayList;+import java.util.Comparator;+import java.util.List;+import org.apache.lucene.document.ShapeField.DecodedTriangle.TYPE;+import org.apache.lucene.document.SpatialQuery.EncodedRectangle;+import org.apache.lucene.geo.Component2D;+import org.apache.lucene.geo.Geometry;+import org.apache.lucene.index.PointValues.Relation;+import org.apache.lucene.search.Query;+import org.apache.lucene.store.ByteArrayDataInput;+import org.apache.lucene.store.ByteBuffersDataOutput;+import org.apache.lucene.store.DataInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.BytesRef;++/**+ * A binary doc values format representation for {@link LatLonShape} and {@link XYShape}+ *+ * <p>Note that this class cannot be instantiated directly due to different encodings {@link+ * org.apache.lucene.geo.XYEncodingUtils} and {@link org.apache.lucene.geo.GeoEncodingUtils}+ *+ * <p>Concrete Implementations include: {@link LatLonShapeDocValues} and {@link XYShapeDocValues}+ *+ * <p>ShapeDocValues also does not support Multi Geometries because the area of the original+ * geometries must be included to compute an accurate centroid. To support multi geometries binary+ * doc values will need to be updated to support multi values (see: {@link+ * org.apache.lucene.index.NumericDocValues} and {@link+ * org.apache.lucene.index.SortedNumericDocValues}+ *+ * @lucene.experimental+ */+abstract class ShapeDocValues {+ /** doc value format version; used to support bwc for any encoding changes */+ protected static final byte VERSION = 0;+ /** the binary doc value */+ private final BytesRef data;+ /** the geometry comparator used to check relations */+ protected final ShapeComparator shapeComparator;+ /** the centroid of the shape docvalue */+ protected final Geometry centroid;+ /** the bounding box of the shape docvalue */+ protected final Geometry boundingBox;++ /**+ * Creates a {@ShapeDocValues} instance from a shape tessellation+ *+ * @param tessellation The tessellation (must not be null)+ */+ ShapeDocValues(List<ShapeField.DecodedTriangle> tessellation) {+ this.data = computeBinaryValue(tessellation);+ try {+ this.shapeComparator = new ShapeComparator(this.data);+ } catch (IOException e) {+ throw new IllegalArgumentException("unable to read binary shape doc value field. ", e);+ }+ this.centroid = computeCentroid();+ this.boundingBox = computeBoundingBox();+ }++ /** Creates a {@code ShapeDocValues} instance from a given serialized value */+ ShapeDocValues(BytesRef binaryValue) {+ this.data = binaryValue;+ try {+ this.shapeComparator = new ShapeComparator(this.data);+ } catch (IOException e) {+ throw new IllegalArgumentException("unable to read binary shape doc value field. ", e);+ }+ this.centroid = computeCentroid();+ this.boundingBox = computeBoundingBox();+ }++ /** returns the encoded doc values field as a {@link BytesRef} */+ protected BytesRef binaryValue() {+ return this.data;+ }++ /** Returns the number of terms (tessellated triangles) for this shape */+ public int numberOfTerms() {+ return shapeComparator.numberOfTerms();+ }++ /** returns the min x value for the shape's bounding box */+ public int getEncodedMinX() {+ return shapeComparator.getMinX();+ }++ /** returns the min y value for the shape's bounding box */+ public int getEncodedMinY() {+ return shapeComparator.getMinY();+ }++ /** returns the max x value for the shape's bounding box */+ public int getEncodedMaxX() {+ return shapeComparator.getMaxX();+ }++ /** returns the max y value for the shape's bounding box */+ public int getEncodedMaxY() {+ return shapeComparator.getMaxY();+ }++ /** Retrieves the encoded x centroid location for the geometry(s) */+ protected int getEncodedCentroidX() {+ return shapeComparator.getCentroidX();+ }++ /** Retrieves the encoded y centroid location for the geometry(s) */+ protected int getEncodedCentroidY() {+ return shapeComparator.getCentroidY();+ }++ /**+ * Retrieves the highest dimensional type (POINT, LINE, TRIANGLE) for computing the geometry(s)+ * centroid+ */+ public TYPE getHighestDimension() {+ return shapeComparator.getHighestDimension();+ }++ private BytesRef computeBinaryValue(List<ShapeField.DecodedTriangle> tessellation) {+ try {+ // dfs order serialization+ List<TreeNode> dfsSerialized = new ArrayList<>(tessellation.size());+ buildTree(tessellation, dfsSerialized);+ Writer w = new Writer(dfsSerialized);+ return w.getBytesRef();+ } catch (IOException e) {+ throw new RuntimeException("Internal error building LatLonShapeDocValues. Got ", e);+ }+ }++ /** Creates a geometry query for shape docvalues */+ public static Query newGeometryQuery(+ final String field, final ShapeField.QueryRelation relation, Object... geometries) {+ return null;+ // TODO+ // return new ShapeDocValuesQuery(field, relation, geometries);+ }++ public Relation relate(final Component2D component) throws IOException {+ return shapeComparator.relate(component);+ }++ protected interface Encoder {+ int encodeX(double x);++ int encodeY(double y);++ double decodeX(int encoded);++ double decodeY(int encoded);+ }++ protected abstract Encoder getEncoder();++ protected abstract Geometry computeCentroid();++ protected abstract Geometry computeBoundingBox();++ public abstract Geometry getCentroid();++ public abstract Geometry getBoundingBox();++ /** main entry point to build the tessellation tree * */+ private TreeNode buildTree(+ List<ShapeField.DecodedTriangle> tessellation, List<TreeNode> dfsSerialized)+ throws IOException {+ if (tessellation.size() == 1) {+ ShapeField.DecodedTriangle t = tessellation.get(0);+ TreeNode node = new TreeNode(t);+ if (t.type == TYPE.LINE) {+ if (node.length != 0) {+ node.midX /= node.length;+ node.midY /= node.length;+ }+ } else if (t.type == TYPE.TRIANGLE) {+ if (node.signedArea != 0) {+ node.midX /= node.signedArea;+ node.midY /= node.signedArea;+ }+ }+ node.highestType = t.type;+ dfsSerialized.add(node);+ return node;+ }+ TreeNode[] triangles = new TreeNode[tessellation.size()];+ int i = 0;+ int minY = Integer.MAX_VALUE;+ int minX = Integer.MAX_VALUE;+ int maxY = Integer.MIN_VALUE;+ int maxX = Integer.MIN_VALUE;++ // running stats for computing centroid+ double totalSignedArea = 0;+ double totalLength = 0;+ double numXPnt = 0;+ double numYPnt = 0;+ double numXLin = 0;+ double numYLin = 0;+ double numXPly = 0;+ double numYPly = 0;+ TYPE highestType = TYPE.POINT;++ for (ShapeField.DecodedTriangle t : tessellation) {+ TreeNode node = new TreeNode(t);+ triangles[i++] = node;+ // compute the bbox values up front+ minY = Math.min(minY, node.minY);+ minX = Math.min(minX, node.minX);+ maxY = Math.max(maxY, node.maxY);+ maxX = Math.max(maxX, node.maxX);++ // compute the running centroid stats+ totalSignedArea += node.signedArea; // non-zero if any components are triangles+ totalLength += node.length; // non-zero if any components are line segments+ if (t.type == TYPE.POINT) {+ numXPnt += node.midX;+ numYPnt += node.midY;+ } else if (t.type == TYPE.LINE) {+ if (highestType == TYPE.POINT) {+ highestType = TYPE.LINE;+ }+ numXLin += node.midX;+ numYLin += node.midY;+ } else {+ if (highestType != TYPE.TRIANGLE) {+ highestType = TYPE.TRIANGLE;+ }+ numXPly += node.midX;+ numYPly += node.midY;+ }+ }+ TreeNode root = createTree(triangles, 0, triangles.length - 1, false, null, dfsSerialized);++ // pull up min values for the root node so the bbox is consistent+ root.minY = minY;+ root.minX = minX;++ // set the highest dimensional type+ root.highestType = highestType;++ // compute centroid values for the root node so the centroid is consistent+ if (highestType == TYPE.POINT) {+ root.midX = numXPnt / i;+ root.midY = numYPnt / i;+ } else if (highestType == TYPE.LINE) {+ // numerator is sum of segment midPoints times segment length+ // divide by total length per+ // https://www.ae.msstate.edu/vlsm/shape/centroid_of_a_line/straight.htm+ root.midX = numXLin;+ root.midY = numYLin;+ if (totalLength != 0) {+ root.midX /= totalLength;+ root.midY /= totalLength;+ }+ } else {+ // numerator is sum of triangle centroids times triangle signed area+ // divide by total signed area per http://www.faqs.org/faqs/graphics/algorithms-faq/+ root.midX = numXPly;+ root.midY = numYPly;+ if (totalSignedArea != 0) {+ root.midX /= totalSignedArea;+ root.midY /= totalSignedArea;+ }+ }++ return root;+ }++ /** creates the tree */+ private TreeNode createTree(+ TreeNode[] triangles,+ int low,+ int high,+ boolean splitX,+ TreeNode parent,+ List<TreeNode> dfsSerialized) {+ if (low > high) {+ return null;+ }+ // add midpoint+ int mid = (low + high) >>> 1;+ if (low < high) {+ Comparator<TreeNode> comparator =+ splitX+ ? Comparator.comparingInt((TreeNode left) -> left.minX)+ .thenComparingInt(left -> left.maxX)+ : Comparator.comparingInt((TreeNode left) -> left.minY)+ .thenComparingInt(left -> left.maxY);+ ArrayUtil.select(triangles, low, high + 1, mid, comparator);+ }+ TreeNode newNode = triangles[mid];+ dfsSerialized.add(newNode);+ // set parent+ newNode.parent = parent;++ // add children+ newNode.left = createTree(triangles, low, mid - 1, !splitX, newNode, dfsSerialized);+ newNode.right = createTree(triangles, mid + 1, high, !splitX, newNode, dfsSerialized);+ // pull up values to this node+ if (newNode.left != null) {+ newNode.minX = Math.min(newNode.minX, newNode.left.minX);+ newNode.minY = Math.min(newNode.minY, newNode.left.minY);+ newNode.maxX = Math.max(newNode.maxX, newNode.left.maxX);+ newNode.maxY = Math.max(newNode.maxY, newNode.left.maxY);+ }+ if (newNode.right != null) {+ newNode.minX = Math.min(newNode.minX, newNode.right.minX);+ newNode.minY = Math.min(newNode.minY, newNode.right.minY);+ newNode.maxX = Math.max(newNode.maxX, newNode.right.maxX);+ newNode.maxY = Math.max(newNode.maxY, newNode.right.maxY);+ }++ // adjust byteSize based on new parent bbox values+ if (newNode.left != null) {+ // bounding box size+ newNode.left.byteSize += vLongSize((long) newNode.maxX - newNode.left.minX);+ newNode.left.byteSize += vLongSize((long) newNode.maxY - newNode.left.minY);+ newNode.left.byteSize += vLongSize((long) newNode.maxX - newNode.left.maxX);+ newNode.left.byteSize += vLongSize((long) newNode.maxY - newNode.left.maxY);+ // component size+ newNode.left.byteSize += computeComponentSize(newNode.left, newNode.maxX, newNode.maxY);+ // include byte size (if needed to be skipped)+ newNode.byteSize += vIntSize(newNode.left.byteSize) + newNode.left.byteSize;+ }+ if (newNode.right != null) {+ // bounding box size+ newNode.right.byteSize += vLongSize((long) newNode.maxX - newNode.right.minX);+ newNode.right.byteSize += vLongSize((long) newNode.maxY - newNode.right.minY);+ newNode.right.byteSize += vLongSize((long) newNode.maxX - newNode.right.maxX);+ newNode.right.byteSize += vLongSize((long) newNode.maxY - newNode.right.maxY);+ // component size+ newNode.right.byteSize += computeComponentSize(newNode.right, newNode.maxX, newNode.maxY);+ // include byte size (if needed to be skipped)+ newNode.byteSize += vIntSize(newNode.right.byteSize) + newNode.right.byteSize;+ }+ return newNode;+ }++ private int computeComponentSize(TreeNode node, int maxX, int maxY) {+ int size = 0;+ ShapeField.DecodedTriangle t = node.triangle;+ size += vLongSize((long) maxX - t.aX);+ size += vLongSize((long) maxY - t.aY);+ if (t.type == TYPE.LINE || t.type == TYPE.TRIANGLE) {+ size += vLongSize((long) maxX - t.bX);+ size += vLongSize((long) maxY - t.bY);+ }+ if (t.type == TYPE.TRIANGLE) {+ size += vLongSize((long) maxX - t.cX);+ size += vLongSize((long) maxY - t.cY);+ }+ return size;+ }++ /**+ * Builds an in memory binary tree of tessellated triangles. This logic comes from {@code+ * org.apache.lucene.geo.ComponentTree} which originated from {@code+ * org.apache.lucene.geo.EdgeTree}+ *+ * <p>The tree is serialized on disk in a variable format which becomes a compressed+ * representation of the doc value format for the Geometry Component Tree+ */+ private final class TreeNode {+ /** the triangle for this tree node */+ private final ShapeField.DecodedTriangle triangle;++ /** centroid running stats (in encoded space) for this tree node */+ private double midX;++ private double midY;++ private final double+ signedArea; // Units are encoded space. This is only used to compute centroid+ // in encoded space. DO NOT USE THIS FOR GEOGRAPHICAL SPATIAL AREA+ // triangles are guaranteed CCW so this will always be positive+ // unless the component is a point or line+ private final double length; // Units are encoded space. This is only used to compute centroid+ // in encoded space. DO NOT USE THIS FOR GEOGRAPHICAL DISTANCE+ // this will always be positive unless the component is a+ // point or triangle+ private TYPE highestType; // the highest dimensional type++ /** the bounding box for the tree */+ private int minX;++ private int maxX;+ private int minY;+ private int maxY;++ // left and right branch+ private TreeNode left;+ private TreeNode right;+ private TreeNode parent;++ private int byteSize = 1; // header size is one byte; remaining is accumulated on construction++ private TreeNode(ShapeField.DecodedTriangle t) {+ this.minX = StrictMath.min(StrictMath.min(t.aX, t.bX), t.cX);+ this.minY = StrictMath.min(StrictMath.min(t.aY, t.bY), t.cY);+ this.maxX = StrictMath.max(StrictMath.max(t.aX, t.bX), t.cX);+ this.maxY = StrictMath.max(StrictMath.max(t.aY, t.bY), t.cY);+ this.triangle = t;+ this.left = null;+ this.right = null;++ // compute the component level centroid, encoded area, or length based on type+ Encoder encoder = getEncoder();+ double ax = encoder.decodeX(t.aX);+ double ay = encoder.decodeY(t.aY);+ if (t.type == TYPE.POINT) {+ this.midX = ax;+ this.midY = ay;+ this.signedArea = 0;+ this.length = 0;+ } else if (t.type == TYPE.LINE || t.type == TYPE.TRIANGLE) {+ double bx = encoder.decodeX(t.bX);+ double by = encoder.decodeY(t.bY);+ if (t.type == TYPE.LINE) {+ this.length = Math.hypot(ax - bx, ay - by);+ this.midX = (0.5d * (ax + bx)) * length; // weight by length+ this.midY = (0.5d * (ay + by)) * length; // weight by length+ this.signedArea = 0;+ } else {+ double cx = encoder.decodeX(t.cX);+ double cy = encoder.decodeY(t.cY);+ this.signedArea = Math.abs(0.5d * ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)));+ this.midX = ((ax + bx + cx) / 3D) * signedArea; // weight by signed area+ this.midY = ((ay + by + cy) / 3D) * signedArea; // weight by signed area+ this.length = 0;+ }+ } else {+ throw new IllegalArgumentException("invalid type [" + t.type + "] found");+ }+ }+ }++ /** Writes data from a ShapeDocValues field to a data output array */+ private final class Writer {+ private final ByteBuffersDataOutput output;+ private BytesRef bytesRef;++ Writer(List<TreeNode> dfsSerialized) throws IOException {+ this.output = new ByteBuffersDataOutput();+ writeTree(dfsSerialized);+ this.bytesRef = new BytesRef(output.toArrayCopy(), 0, Math.toIntExact(output.size()));+ }++ BytesRef getBytesRef() {+ return bytesRef;+ }++ private void writeTree(List<TreeNode> dfsSerialized) throws IOException {+ assert output != null : "passed null datastream to ShapeDocValuesField tessellation tree";+ // write encoding version+ output.writeByte(VERSION);+ // write number of terms (triangles)+ output.writeVInt(dfsSerialized.size());+ // write root+ TreeNode root = dfsSerialized.remove(0);+ // write bounding box; convert to variable long by translating+ Encoder encoder = getEncoder();+ output.writeVLong((long) root.minX - Integer.MIN_VALUE);+ output.writeVLong((long) root.maxX - Integer.MIN_VALUE);+ output.writeVLong((long) root.minY - Integer.MIN_VALUE);+ output.writeVLong((long) root.maxY - Integer.MIN_VALUE);++ // write centroid+ output.writeVLong((long) encoder.encodeX(root.midX) - Integer.MIN_VALUE);+ output.writeVLong((long) encoder.encodeY(root.midY) - Integer.MIN_VALUE);+ // write highest dimensional type+ output.writeVInt(root.highestType.ordinal());+ // write header+ writeHeader(root);+ // write component+ writeComponent(root, root.maxX, root.maxY);++ for (TreeNode t : dfsSerialized) {+ // write each node+ writeNode(t);+ }+ }++ /** Serializes a node in the most compact way possible */+ private void writeNode(TreeNode node) throws IOException {+ // write subtree total size+ output.writeVInt(node.byteSize); // variable+ // write max bounds+ writeBounds(node); // variable+ writeHeader(node); // 1 byte+ writeComponent(node, node.parent.maxX, node.parent.maxY); // variable+ }++ /** Serializes a component (POINT, LINE, or TRIANGLE) in the most compact way possible */+ private void writeComponent(TreeNode node, int pMaxX, int pMaxY) throws IOException {+ ShapeField.DecodedTriangle t = node.triangle;+ output.writeVLong((long) pMaxX - t.aX);+ output.writeVLong((long) pMaxY - t.aY);+ if (t.type == TYPE.LINE || t.type == TYPE.TRIANGLE) {+ output.writeVLong((long) pMaxX - t.bX);+ output.writeVLong((long) pMaxY - t.bY);+ }+ if (t.type == TYPE.TRIANGLE) {+ output.writeVLong((long) pMaxX - t.cX);+ output.writeVLong((long) pMaxY - t.cY);+ }+ }++ /** Writes the header metadata in the most compact way possible */+ private void writeHeader(TreeNode node) throws IOException {+ int header = 0x00;+ // write left / right subtree+ if (node.right != null) {+ header |= 0x01;+ }+ if (node.left != null) {+ header |= 0x02;+ }++ // write type+ if (node.triangle.type == TYPE.POINT) {+ header |= 0x04;+ } else if (node.triangle.type == TYPE.LINE) {+ header |= 0x08;+ }++ // write edge member of original shape+ if (node.triangle.ab == true) {+ header |= 0x10;+ }+ if (node.triangle.bc == true) {+ header |= 0x20;+ }+ if (node.triangle.ca = true) {+ header |= 0x40;+ }++ output.writeVInt(header);+ }++ private void writeBounds(TreeNode node) throws IOException {+ output.writeVLong((long) node.parent.maxX - node.minX);+ output.writeVLong((long) node.parent.maxY - node.minY);+ output.writeVLong((long) node.parent.maxX - node.maxX);+ output.writeVLong((long) node.parent.maxY - node.maxY);+ }+ }++ /** Reads values from a ShapeDocValues Field */+ private final class Reader extends DataInput {+ /** data input array to read the docvalue data */+ private final ByteArrayDataInput data;++ // scratch classes+ private final BBox bbox; // scratch bbox instance++ /** creates the docvalue reader from the binary value */+ Reader(BytesRef binaryValue) {+ this.data = new ByteArrayDataInput(binaryValue.bytes, binaryValue.offset, binaryValue.length);+ // initialize scratch instances+ this.bbox =+ new BBox(Integer.MAX_VALUE, -Integer.MAX_VALUE, Integer.MAX_VALUE, -Integer.MAX_VALUE);+ }++ @Override+ public Reader clone() {+ return new Reader(ShapeDocValues.this.data);+ }++ /** rewinds the buffer to the beginning */+ protected void rewind() {+ this.data.rewind();+ }++ /** reads the component bounding box */+ private SpatialQuery.EncodedRectangle readBBox() {+ return bbox.reset(+ Math.toIntExact(+ data.readVLong() + Integer.MIN_VALUE), // translate back from positive values+ Math.toIntExact(data.readVLong() + Integer.MIN_VALUE),+ Math.toIntExact(data.readVLong() + Integer.MIN_VALUE),+ Math.toIntExact(data.readVLong() + Integer.MIN_VALUE));+ }++ /** resets the scratch bounding box */+ private SpatialQuery.EncodedRectangle resetBBox(+ final int minX, final int maxX, final int minY, final int maxY) {+ return bbox.reset(minX, maxX, minY, maxY);+ }++ @Override+ public byte readByte() throws IOException {+ return data.readByte();+ }++ @Override+ public void readBytes(byte[] b, int offset, int len) throws IOException {+ data.readBytes(b, offset, len);+ }++ @Override+ public void skipBytes(long numBytes) throws IOException {+ data.skipBytes(numBytes);+ }++ private final class Header {++ /**+ * reads the component type (POINT, LINE, TRIANGLE) such that triangle gives the highest+ * variable compression+ */+ private static TYPE readType(int bits) {+ if ((bits & 0x04) == 0x04) { // _____1__ : indicates a point type+ return TYPE.POINT;+ }+ if ((bits & 0x08) == 0x08) { // ____1___ : indicates a line type+ return TYPE.LINE;+ }+ assert (bits & 0x0C) == 0x00 : "invalid component type in ShapeDocValuesField";+ return TYPE.TRIANGLE; // ________ : indicates a triangle type+ }++ /** reads if the left subtree is null */+ private static boolean readHasLeftSubtree(int bits) {+ return (bits & 0x02) == 0x02; // ______1_ : indicates left subtree is not null+ }++ /** reads if the right subtree is null */+ private static boolean readHasRightSubtree(int bits) {+ return (bits & 0x01) == 0x01; // _______1 : indicates right subtree is not null+ }+ }++ private final class BBox extends SpatialQuery.EncodedRectangle {+ BBox(int minX, int maxX, int minY, int maxY) {+ super(minX, maxX, minY, maxY, false);+ }++ /** resets bounding box values */+ BBox reset(int minX, int maxX, int minY, int maxY) {+ this.minX = minX;+ this.maxX = maxX;+ this.minY = minY;+ this.maxY = maxY;+ this.wrapsCoordinateSystem = false;+ return this;+ }+ }+ }++ /** Shape Comparator class provides tree traversal relation methods */+ private final class ShapeComparator {+ private Reader dvReader;+ private final Encoder encoder;+ private final byte version;+ private final int numberOfTerms;+ private final SpatialQuery.EncodedRectangle boundingBox;+ private final int centroidX;+ private final int centroidY;+ private final TYPE highestDimension;++ ShapeComparator(BytesRef binaryValue) throws IOException {+ this.dvReader = new Reader(binaryValue);+ this.encoder = getEncoder();+ this.version = dvReader.readByte();+ assert this.version == VERSION;+ this.numberOfTerms = Math.toIntExact(dvReader.readVInt());+ this.boundingBox = dvReader.readBBox();+ this.centroidX = Math.toIntExact(dvReader.readVLong() + Integer.MIN_VALUE);+ this.centroidY = Math.toIntExact(dvReader.readVLong() + Integer.MIN_VALUE);+ this.highestDimension = TYPE.values()[dvReader.readVInt()];+ this.dvReader.rewind();+ }++ private int numberOfTerms() {+ return this.numberOfTerms;+ }++ private int getMinX() {+ return this.boundingBox.minX;+ }++ private int getMinY() {+ return this.boundingBox.minY;+ }++ private int getMaxX() {+ return this.boundingBox.maxX;+ }++ private int getMaxY() {+ return this.boundingBox.maxY;+ }++ public TYPE getHighestDimension() {+ return this.highestDimension;+ }++ private int getCentroidX() {+ return this.centroidX;+ }++ private int getCentroidY() {+ return this.centroidY;+ }++ private void skipCentroid() throws IOException {+ dvReader.readVLong();+ dvReader.readVLong();+ }++ private void skipHighestDimension() throws IOException {+ dvReader.readVInt();+ }++ /**+ * Computes a query component relation with the doc value shape; main entry point to the root of+ * the binary tree+ */+ public Relation relate(final Component2D query) throws IOException {+ try {+ // skip version+ dvReader.readByte();+ // skip number of terms+ dvReader.readVInt();+ // read bbox+ SpatialQuery.EncodedRectangle bbox = dvReader.readBBox();+ int tMinX = bbox.minX;+ int tMaxX = bbox.maxX;+ int tMaxY = bbox.maxY;++ // relate the query to the shape bounding box+ Relation r;+ if ((r =+ query.relate(+ encoder.decodeX(bbox.minX),+ encoder.decodeX(bbox.maxX),+ encoder.decodeY(bbox.minY),+ encoder.decodeY(bbox.maxY)))+ != Relation.CELL_CROSSES_QUERY) {+ return r;+ }++ // traverse the tessellation tree+ // skip the centroid & highest dimension+ skipCentroid();+ skipHighestDimension();+ // get the header+ int headerBits = Math.toIntExact(dvReader.readVInt());+ int x = Math.toIntExact(tMaxX - dvReader.readVLong());+ // relate the component+ if (relateComponent(+ Reader.Header.readType(headerBits), bbox, tMaxX, tMaxY, encoder.decodeX(x), query)+ == Relation.CELL_CROSSES_QUERY) {+ return Relation.CELL_CROSSES_QUERY;+ }+ r = Relation.CELL_OUTSIDE_QUERY;++ // recurse the left subtree+ if (Reader.Header.readHasLeftSubtree(headerBits)) {+ if ((r = relate(query, false, tMaxX, tMaxY, Math.toIntExact(dvReader.readVInt())))+ == Relation.CELL_CROSSES_QUERY) {+ return Relation.CELL_CROSSES_QUERY;+ }+ }+ // recurse the right subtree+ if (Reader.Header.readHasRightSubtree(headerBits)) {+ if (query.getMaxX() >= encoder.decodeX(tMinX)) {+ if ((r = relate(query, false, tMaxX, tMaxY, Math.toIntExact(dvReader.readVInt())))+ == Relation.CELL_CROSSES_QUERY) {+ return Relation.CELL_CROSSES_QUERY;+ }+ }+ }+ return r;+ } finally {+ dvReader.rewind();+ }+ }++ /**+ * recursive traversal method recurses through tree nodes to compute relation with the query+ * component+ */+ private Relation relate(+ Component2D queryComponent2D, boolean splitX, int pMaxX, int pMaxY, int nodeSize)+ throws IOException {+ // mark the data position because we need to subtract the maxX, maxY, and header from node+ // bytesize+ int prePos = dvReader.data.getPosition();+ // read the minX and minY+ int tMinX = Math.toIntExact(pMaxX - dvReader.readVLong());+ int tMinY = Math.toIntExact(pMaxY - dvReader.readVLong());+ // read the maxX and maxY+ int tMaxX = Math.toIntExact(pMaxX - dvReader.readVLong());+ int tMaxY = Math.toIntExact(pMaxY - dvReader.readVLong());+ // read the header+ int headerBits = Math.toIntExact(dvReader.readVInt());+ // subtract the bbox and header byteSize to get remaining node byteSize+ nodeSize -= dvReader.data.getPosition() - prePos;++ // base case query is disjoint+ if (queryComponent2D.getMinX() > encoder.decodeX(tMaxX)+ || queryComponent2D.getMinY() > encoder.decodeY(tMaxY)) {+ // now skip the entire subtree+ dvReader.skipBytes(nodeSize);+ return Relation.CELL_OUTSIDE_QUERY;+ }++ // traverse the tessellation tree+ int x = Math.toIntExact(pMaxX - dvReader.readVLong());+ // minY is set in relate component+ SpatialQuery.EncodedRectangle bbox = dvReader.resetBBox(tMinX, tMaxX, tMinY, tMaxY);+ // relate the component+ if (relateComponent(+ Reader.Header.readType(headerBits),+ bbox,+ pMaxX,+ pMaxY,+ encoder.decodeX(x),+ queryComponent2D)+ == Relation.CELL_CROSSES_QUERY) {+ return Relation.CELL_CROSSES_QUERY;+ }++ // traverse left subtree+ if (Reader.Header.readHasLeftSubtree(headerBits) == true) {+ if (relate(queryComponent2D, !splitX, tMaxX, tMaxY, Math.toIntExact(dvReader.readVInt()))+ == Relation.CELL_CROSSES_QUERY) {+ return Relation.CELL_CROSSES_QUERY;+ }+ }++ // traverse right subtree+ if (Reader.Header.readHasRightSubtree(headerBits) == true) {+ int size = Math.toIntExact(dvReader.readVInt());+ if ((splitX == false && queryComponent2D.getMaxY() >= encoder.decodeY(tMinY))+ || (splitX == true && queryComponent2D.getMaxX() >= encoder.decodeX(tMinX))) {+ if (relate(queryComponent2D, !splitX, tMaxX, tMaxY, size)+ == Relation.CELL_CROSSES_QUERY) {+ return Relation.CELL_CROSSES_QUERY;+ }+ } else {+ // skip the subtree if the bbox doesn't match+ dvReader.skipBytes(size);+ }+ }+ return Relation.CELL_OUTSIDE_QUERY;+ }++ /** relates the component based on type (POINT, LINE, TRIANGLE) */+ private Relation relateComponent(+ final TYPE type,+ SpatialQuery.EncodedRectangle bbox,+ int pMaxX,+ int pMaxY,+ double x,+ Component2D queryComponent2D)+ throws IOException {+ Relation r = Relation.CELL_OUTSIDE_QUERY;+ if (type == TYPE.POINT) {+ r = relatePoint(bbox, pMaxY, x, queryComponent2D);+ } else if (type == TYPE.LINE) {+ r = relateLine(bbox, pMaxX, pMaxY, x, queryComponent2D);+ } else if (type == TYPE.TRIANGLE) {+ r = relateTriangle(bbox, pMaxX, pMaxY, x, queryComponent2D);+ }+ if (r == Relation.CELL_CROSSES_QUERY) {+ return Relation.CELL_CROSSES_QUERY;+ }+ return Relation.CELL_OUTSIDE_QUERY;+ }++ private Relation relatePoint(+ SpatialQuery.EncodedRectangle bbox, int pMaxY, double ax, Component2D query)+ throws IOException {+ int y = Math.toIntExact(pMaxY - dvReader.readVLong());+ if (query.contains(ax, encoder.decodeY(y))) {+ return Relation.CELL_CROSSES_QUERY;+ }+ return Relation.CELL_OUTSIDE_QUERY;+ }++ private Relation relateLine(+ EncodedRectangle bbox, int pMaxX, int pMaxY, double ax, Component2D query)+ throws IOException {+ int ay = Math.toIntExact(pMaxY - dvReader.readVLong());+ double bx = encoder.decodeX(Math.toIntExact(pMaxX - dvReader.readVLong()));+ int by = Math.toIntExact(pMaxY - dvReader.readVLong());+ if (query.intersectsLine(ax, encoder.decodeY(ay), bx, encoder.decodeY(by))) {+ return Relation.CELL_CROSSES_QUERY;+ }+ return Relation.CELL_OUTSIDE_QUERY;+ }++ private Relation relateTriangle(+ SpatialQuery.EncodedRectangle bbox,+ int pMaxX,+ int pMaxY,+ double ax,+ Component2D queryComponent2D)+ throws IOException {+ int ay = Math.toIntExact(pMaxY - dvReader.readVLong());+ double bx = encoder.decodeX(Math.toIntExact(pMaxX - dvReader.readVLong()));+ int by = Math.toIntExact(pMaxY - dvReader.readVLong());+ double cx = encoder.decodeX(Math.toIntExact(pMaxX - dvReader.readVLong()));+ int cy = Math.toIntExact(pMaxY - dvReader.readVLong());++ if (queryComponent2D.intersectsTriangle(+ ax, encoder.decodeY(ay), bx, encoder.decodeY(by), cx, encoder.decodeY(cy))) {+ return Relation.CELL_CROSSES_QUERY;+ }+ return Relation.CELL_OUTSIDE_QUERY;+ }+ }++ /** Computes the variable Long size in bytes */+ protected static int vLongSize(long i) {+ int size = 0;+ while ((i & ~0x7FL) != 0L) {+ i >>>= 7;+ ++size;+ }+ return ++size;+ }++ /** Computes the variable Integer size in bytes */+ protected static int vIntSize(int i) {+ int size = 0;+ while ((i & ~0x7F) != 0) {+ i >>>= 7;+ ++size;+ }+ return ++size;+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/ShapeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/ShapeDocValuesField.javanew file mode 100644index 00000000000..326fbdf38f4--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/ShapeDocValuesField.java@@ -0,0 +1,116 @@+/*+ * 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.document;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.document.ShapeField.DecodedTriangle.TYPE;+import org.apache.lucene.document.ShapeField.QueryRelation;+import org.apache.lucene.geo.Geometry;+import org.apache.lucene.index.DocValuesType;+import org.apache.lucene.index.IndexableFieldType;+import org.apache.lucene.search.Query;++/**+ * A doc values field for {@link LatLonShape} and {@link XYShape} that uses {@link ShapeDocValues}+ * as the underlying binary doc value format.+ *+ * <p>Note that this class cannot be instantiated directly due to different encodings {@link+ * org.apache.lucene.geo.XYEncodingUtils} and {@link org.apache.lucene.geo.GeoEncodingUtils}+ *+ * <p>Concrete Implementations include: {@link LatLonShapeDocValuesField} and {@link+ * XYShapeDocValuesField}+ *+ * @lucene.experimental+ */+public abstract class ShapeDocValuesField extends Field {++ /** the binary doc value format for this field */+ protected final ShapeDocValues shapeDocValues;++ /** FieldType for ShapeDocValues field */+ protected static final FieldType FIELD_TYPE = new FieldType();++ static {+ FIELD_TYPE.setDocValuesType(DocValuesType.BINARY);+ FIELD_TYPE.setOmitNorms(true);+ FIELD_TYPE.freeze();+ }++ ShapeDocValuesField(String name, ShapeDocValues shapeDocValues) {+ super(name, FIELD_TYPE);+ this.shapeDocValues = shapeDocValues;+ this.fieldsData = shapeDocValues.binaryValue();+ }++ /** The name of the field */+ @Override+ public String name() {+ return name;+ }++ /** Gets the {@code IndexableFieldType} for this ShapeDocValue field */+ @Override+ public IndexableFieldType fieldType() {+ return FIELD_TYPE;+ }++ /** Currently there is no string representation for the ShapeDocValueField */+ @Override+ public String stringValue() {+ return null;+ }++ /** TokenStreams are not yet supported */+ @Override+ public TokenStream tokenStream(Analyzer analyzer, TokenStream reuse) {+ return null;+ }++ /** Returns the number of terms (tessellated triangles) for this shape */+ public int numberOfTerms() {+ return shapeDocValues.numberOfTerms();+ }++ /** Creates a geometry query for shape docvalues */+ public static Query newGeometryQuery(+ final String field, final QueryRelation relation, Object... geometries) {+ // TODO add general geometry query+ throw new IllegalStateException(+ "geometry queries not yet supported on shape doc values for field [" + field + "]");+ }++ /** retrieves the centroid location for the geometry */+ public abstract Geometry getCentroid();++ /** retrieves the bounding box for the geometry */+ public abstract Geometry getBoundingBox();++ /**+ * Retrieves the highest dimensional type (POINT, LINE, TRIANGLE) for computing the geometry(s)+ * centroid+ */+ public TYPE getHighestDimensionType() {+ return shapeDocValues.getHighestDimension();+ }++ /** decodes x coordinates from encoded space */+ protected abstract double decodeX(int encoded);++ /** decodes y coordinates from encoded space */+ protected abstract double decodeY(int encoded);+}diff --git a/lucene/core/src/java/org/apache/lucene/document/ShapeField.java b/lucene/core/src/java/org/apache/lucene/document/ShapeField.javaindex 6a3edfe2fbb..bd85a5771fc 100644--- a/lucene/core/src/java/org/apache/lucene/document/ShapeField.java+++ b/lucene/core/src/java/org/apache/lucene/document/ShapeField.java@@ -371,7 +371,7 @@ public final class ShapeField {resolveTriangleType(triangle);}- private static void resolveTriangleType(DecodedTriangle triangle) {+ static void resolveTriangleType(DecodedTriangle triangle) {if (triangle.aX == triangle.bX && triangle.aY == triangle.bY) {if (triangle.aX == triangle.cX && triangle.aY == triangle.cY) {triangle.type = DecodedTriangle.TYPE.POINT;@@ -430,7 +430,8 @@ public final class ShapeField {/** default xtor */public DecodedTriangle() {}- private void setValues(+ /** Sets the values of the DecodedTriangle */+ protected void setValues(int aX, int aY, boolean ab, int bX, int bY, boolean bc, int cX, int cY, boolean ca) {this.aX = aX;this.aY = aY;diff --git a/lucene/core/src/java/org/apache/lucene/document/SpatialQuery.java b/lucene/core/src/java/org/apache/lucene/document/SpatialQuery.javaindex e170a6391fe..f429f1cc046 100644--- a/lucene/core/src/java/org/apache/lucene/document/SpatialQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/SpatialQuery.java@@ -16,13 +16,19 @@*/package org.apache.lucene.document;+import static org.apache.lucene.geo.GeoEncodingUtils.MAX_LON_ENCODED;+import static org.apache.lucene.geo.GeoEncodingUtils.MIN_LON_ENCODED;+import java.io.IOException;+import java.util.Arrays;import java.util.Objects;import java.util.function.BiFunction;import java.util.function.Function;import java.util.function.Predicate;import org.apache.lucene.document.ShapeField.QueryRelation;import org.apache.lucene.geo.Component2D;+import org.apache.lucene.geo.GeoUtils;+import org.apache.lucene.geo.Geometry;import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.LeafReader;import org.apache.lucene.index.LeafReaderContext;@@ -47,6 +53,8 @@ import org.apache.lucene.util.FixedBitSet;/*** Base query class for all spatial geometries: {@link LatLonShape}, {@link LatLonPoint} and {@link* XYShape}. In order to create a query, use the factory methods on those classes.+ *+ * @lucene.internal*/abstract class SpatialQuery extends Query {/** field name */@@ -58,7 +66,10 @@ abstract class SpatialQuery extends Query {*/final QueryRelation queryRelation;- protected SpatialQuery(String field, final QueryRelation queryRelation) {+ final Geometry[] geometries;+ final Component2D queryComponent2D;++ protected SpatialQuery(String field, final QueryRelation queryRelation, Geometry... geometries) {if (field == null) {throw new IllegalArgumentException("field must not be null");}@@ -67,8 +78,12 @@ abstract class SpatialQuery extends Query {}this.field = field;this.queryRelation = queryRelation;+ this.geometries = geometries.clone();+ this.queryComponent2D = createComponent2D(geometries);}+ protected abstract Component2D createComponent2D(Geometry... geometries);+/*** returns the spatial visitor to be used for this query. Called before generating the query* {@link Weight}@@ -126,12 +141,74 @@ abstract class SpatialQuery extends Query {}}+ protected boolean queryIsCacheable(LeafReaderContext ctx) {+ return true;+ }++ protected ScorerSupplier getScorerSupplier(+ LeafReader reader,+ SpatialVisitor spatialVisitor,+ ScoreMode scoreMode,+ ConstantScoreWeight weight,+ float boost,+ float score)+ throws IOException {+ final PointValues values = reader.getPointValues(field);+ if (values == null) {+ // No docs in this segment had any points fields+ return null;+ }+ final FieldInfo fieldInfo = reader.getFieldInfos().fieldInfo(field);+ if (fieldInfo == null) {+ // No docs in this segment indexed this field at all+ return null;+ }++ final Relation rel =+ spatialVisitor+ .getInnerFunction(queryRelation)+ .apply(values.getMinPackedValue(), values.getMaxPackedValue());+ if (rel == Relation.CELL_OUTSIDE_QUERY+ || (rel == Relation.CELL_INSIDE_QUERY && queryRelation == QueryRelation.CONTAINS)) {+ // no documents match the query+ return null;+ } else if (values.getDocCount() == reader.maxDoc() && rel == Relation.CELL_INSIDE_QUERY) {+ // all documents match the query+ return new ScorerSupplier() {+ @Override+ public Scorer get(long leadCost) {+ return new ConstantScoreScorer(+ weight, score, scoreMode, DocIdSetIterator.all(reader.maxDoc()));+ }++ @Override+ public long cost() {+ return reader.maxDoc();+ }+ };+ } else {+ if (queryRelation != QueryRelation.INTERSECTS+ && queryRelation != QueryRelation.CONTAINS+ && values.getDocCount() != values.size()+ && hasAnyHits(spatialVisitor, queryRelation, values) == false) {+ // First we check if we have any hits so we are fast in the adversarial case where+ // the shape does not match any documents and we are in the dense case+ return null;+ }+ // walk the tree to get matching documents+ return new RelationScorerSupplier(values, spatialVisitor, queryRelation, field) {+ @Override+ public Scorer get(long leadCost) throws IOException {+ return getScorer(reader, weight, score, scoreMode);+ }+ };+ }+ }+@Overridepublic final Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) {final SpatialQuery query = this;- final SpatialVisitor spatialVisitor = getSpatialVisitor();return new ConstantScoreWeight(query, boost) {-@Overridepublic Scorer scorer(LeafReaderContext context) throws IOException {final ScorerSupplier scorerSupplier = scorerSupplier(context);@@ -144,61 +221,12 @@ abstract class SpatialQuery extends Query {@Overridepublic ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOException {final LeafReader reader = context.reader();- final PointValues values = reader.getPointValues(field);- if (values == null) {- // No docs in this segment had any points fields- return null;- }- final FieldInfo fieldInfo = reader.getFieldInfos().fieldInfo(field);- if (fieldInfo == null) {- // No docs in this segment indexed this field at all- return null;- }- final Weight weight = this;- final Relation rel =- spatialVisitor- .getInnerFunction(queryRelation)- .apply(values.getMinPackedValue(), values.getMaxPackedValue());- if (rel == Relation.CELL_OUTSIDE_QUERY- || (rel == Relation.CELL_INSIDE_QUERY && queryRelation == QueryRelation.CONTAINS)) {- // no documents match the query- return null;- } else if (values.getDocCount() == reader.maxDoc() && rel == Relation.CELL_INSIDE_QUERY) {- // all documents match the query- return new ScorerSupplier() {- @Override- public Scorer get(long leadCost) {- return new ConstantScoreScorer(- weight, score(), scoreMode, DocIdSetIterator.all(reader.maxDoc()));- }-- @Override- public long cost() {- return reader.maxDoc();- }- };- } else {- if (queryRelation != QueryRelation.INTERSECTS- && queryRelation != QueryRelation.CONTAINS- && values.getDocCount() != values.size()- && hasAnyHits(spatialVisitor, queryRelation, values) == false) {- // First we check if we have any hits so we are fast in the adversarial case where- // the shape does not match any documents and we are in the dense case- return null;- }- // walk the tree to get matching documents- return new RelationScorerSupplier(values, spatialVisitor, queryRelation, field) {- @Override- public Scorer get(long leadCost) throws IOException {- return getScorer(reader, weight, score(), scoreMode);- }- };- }+ return getScorerSupplier(reader, getSpatialVisitor(), scoreMode, this, boost, score());}@Overridepublic boolean isCacheable(LeafReaderContext ctx) {- return true;+ return queryIsCacheable(ctx);}};}@@ -218,6 +246,7 @@ abstract class SpatialQuery extends Query {int hash = classHash();hash = 31 * hash + field.hashCode();hash = 31 * hash + queryRelation.hashCode();+ hash = 31 * hash + Arrays.hashCode(geometries);return hash;}@@ -229,7 +258,8 @@ abstract class SpatialQuery extends Query {/** class specific equals check */protected boolean equalsTo(Object o) {return Objects.equals(field, ((SpatialQuery) o).field)- && this.queryRelation == ((SpatialQuery) o).queryRelation;+ && this.queryRelation == ((SpatialQuery) o).queryRelation+ && Arrays.equals(geometries, ((SpatialQuery) o).geometries);}/**@@ -741,4 +771,254 @@ abstract class SpatialQuery extends Query {}return false;}++ /** Holds spatial logic for a bounding box that works in the encoded space */+ public static class EncodedRectangle {+ protected int minX;+ protected int maxX;+ protected int minY;+ protected int maxY;+ protected boolean wrapsCoordinateSystem;++ protected EncodedRectangle(+ int minX, int maxX, int minY, int maxY, boolean wrapsCoordinateSystem) {+ this.minX = minX;+ this.maxX = maxX;+ this.minY = minY;+ this.maxY = maxY;+ this.wrapsCoordinateSystem = wrapsCoordinateSystem;+ }++ protected boolean wrapsCoordinateSystem() {+ return wrapsCoordinateSystem;+ }++ /** Checks if the rectangle contains the provided point */+ boolean contains(int x, int y) {+ if (y < minY || y > maxY) {+ return false;+ }+ if (wrapsCoordinateSystem()) {+ return (x > maxX && x < minX) == false;+ } else {+ return (x > maxX || x < minX) == false;+ }+ }++ /** Checks if the rectangle intersects the provided LINE */+ boolean intersectsLine(int aX, int aY, int bX, int bY) {+ if (contains(aX, aY) || contains(bX, bY)) {+ return true;+ }+ // check bounding boxes are disjoint+ if (StrictMath.max(aY, bY) < minY || StrictMath.min(aY, bY) > maxY) {+ return false;+ }+ if (wrapsCoordinateSystem) { // crosses dateline+ if (StrictMath.min(aX, bX) > maxX && StrictMath.max(aX, bX) < minX) {+ return false;+ }+ } else {+ if (StrictMath.min(aX, bX) > maxX || StrictMath.max(aX, bX) < minX) {+ return false;+ }+ }+ // expensive part+ return edgeIntersectsQuery(aX, aY, bX, bY);+ }++ /** Checks if the rectangle intersects the provided triangle */+ boolean intersectsTriangle(int aX, int aY, int bX, int bY, int cX, int cY) {+ // query contains any triangle points+ if (contains(aX, aY) || contains(bX, bY) || contains(cX, cY)) {+ return true;+ }+ // check bounding box of triangle+ int tMinY = StrictMath.min(StrictMath.min(aY, bY), cY);+ int tMaxY = StrictMath.max(StrictMath.max(aY, bY), cY);+ // check bounding boxes are disjoint+ if (tMaxY < minY || tMinY > maxY) {+ return false;+ }+ int tMinX = StrictMath.min(StrictMath.min(aX, bX), cX);+ int tMaxX = StrictMath.max(StrictMath.max(aX, bX), cX);+ if (wrapsCoordinateSystem) { // wraps coordinate system+ if (tMinX > maxX && tMaxX < minX) {+ return false;+ }+ } else {+ if (tMinX > maxX || tMaxX < minX) {+ return false;+ }+ }+ // expensive part+ return Component2D.pointInTriangle(+ tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY)+ || edgeIntersectsQuery(aX, aY, bX, bY)+ || edgeIntersectsQuery(bX, bY, cX, cY)+ || edgeIntersectsQuery(cX, cY, aX, aY);+ }++ boolean intersectsRectangle(final int minX, final int maxX, final int minY, final int maxY) {+ // simple Y check+ if (this.minY > maxY || this.maxY < minY) {+ return false;+ }++ if (this.minX <= maxX) {+ // if the triangle's minX is less than the query maxX+ if (wrapsCoordinateSystem || this.maxX >= minX) {+ // intersects if the query box is wrapping (western box) or+ // the triangle maxX is greater than the query minX+ return true;+ }+ }++ return wrapsCoordinateSystem;+ }++ boolean containsRectangle(final int minX, final int maxX, final int minY, final int maxY) {+ return this.minX <= minX && this.maxX >= maxX && this.minY <= minY && this.maxY >= maxY;+ }++ /** Checks if the rectangle contains the provided LINE */+ boolean containsLine(int aX, int aY, int bX, int bY) {+ if (aY < minY || bY < minY || aY > maxY || bY > maxY) {+ return false;+ }+ if (wrapsCoordinateSystem) { // wraps coordinate system+ return (aX >= minX && bX >= minX) || (aX <= maxX && bX <= maxX);+ } else {+ return aX >= minX && bX >= minX && aX <= maxX && bX <= maxX;+ }+ }++ /** Checks if the rectangle contains the provided triangle */+ boolean containsTriangle(int aX, int aY, int bX, int bY, int cX, int cY) {+ if (aY < minY || bY < minY || cY < minY || aY > maxY || bY > maxY || cY > maxY) {+ return false;+ }+ if (wrapsCoordinateSystem) { // wraps coordinate system+ return (aX >= minX && bX >= minX && cX >= minX) || (aX <= maxX && bX <= maxX && cX <= maxX);+ } else {+ return aX >= minX && bX >= minX && cX >= minX && aX <= maxX && bX <= maxX && cX <= maxX;+ }+ }++ /** Returns the Within relation to the provided triangle */+ Component2D.WithinRelation withinLine(int aX, int aY, boolean ab, int bX, int bY) {+ if (contains(aX, aY) || contains(bX, bY)) {+ return Component2D.WithinRelation.NOTWITHIN;+ }+ if (ab == true && edgeIntersectsBox(aX, aY, bX, bY, minX, maxX, minY, maxY) == true) {+ return Component2D.WithinRelation.NOTWITHIN;+ }+ return Component2D.WithinRelation.DISJOINT;+ }++ /** Returns the Within relation to the provided triangle */+ Component2D.WithinRelation withinTriangle(+ int aX, int aY, boolean ab, int bX, int bY, boolean bc, int cX, int cY, boolean ca) {+ // Points belong to the shape so if points are inside the rectangle then it cannot be within.+ if (contains(aX, aY) || contains(bX, bY) || contains(cX, cY)) {+ return Component2D.WithinRelation.NOTWITHIN;+ }++ // Bounding boxes disjoint?+ int tMinY = StrictMath.min(StrictMath.min(aY, bY), cY);+ int tMaxY = StrictMath.max(StrictMath.max(aY, bY), cY);+ // check bounding boxes are disjoint+ if (tMaxY < minY || tMinY > maxY) {+ return Component2D.WithinRelation.DISJOINT;+ }+ int tMinX = StrictMath.min(StrictMath.min(aX, bX), cX);+ int tMaxX = StrictMath.max(StrictMath.max(aX, bX), cX);+ if (wrapsCoordinateSystem) { // wraps coordinate system+ if (tMinX > maxX && tMaxX < minX) {+ return Component2D.WithinRelation.DISJOINT;+ }+ } else {+ if (tMinX > maxX || tMaxX < minX) {+ return Component2D.WithinRelation.DISJOINT;+ }+ }+ // If any of the edges intersects an edge belonging to the shape then it cannot be within.+ Component2D.WithinRelation relation = Component2D.WithinRelation.DISJOINT;+ if (edgeIntersectsBox(aX, aY, bX, bY, minX, maxX, minY, maxY) == true) {+ if (ab == true) {+ return Component2D.WithinRelation.NOTWITHIN;+ } else {+ relation = Component2D.WithinRelation.CANDIDATE;+ }+ }+ if (edgeIntersectsBox(bX, bY, cX, cY, minX, maxX, minY, maxY) == true) {+ if (bc == true) {+ return Component2D.WithinRelation.NOTWITHIN;+ } else {+ relation = Component2D.WithinRelation.CANDIDATE;+ }+ }++ if (edgeIntersectsBox(cX, cY, aX, aY, minX, maxX, minY, maxY) == true) {+ if (ca == true) {+ return Component2D.WithinRelation.NOTWITHIN;+ } else {+ relation = Component2D.WithinRelation.CANDIDATE;+ }+ }+ // Check if shape is within the triangle+ if (relation == Component2D.WithinRelation.CANDIDATE+ || Component2D.pointInTriangle(+ tMinX, tMaxX, tMinY, tMaxY, minX, minY, aX, aY, bX, bY, cX, cY)) {+ return Component2D.WithinRelation.CANDIDATE;+ }+ return relation;+ }++ /** returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the query */+ private boolean edgeIntersectsQuery(int aX, int aY, int bX, int bY) {+ if (wrapsCoordinateSystem) {+ return edgeIntersectsBox(aX, aY, bX, bY, MIN_LON_ENCODED, this.maxX, this.minY, this.maxY)+ || edgeIntersectsBox(aX, aY, bX, bY, this.minX, MAX_LON_ENCODED, this.minY, this.maxY);+ }+ return edgeIntersectsBox(aX, aY, bX, bY, this.minX, this.maxX, this.minY, this.maxY);+ }++ /** returns true if the edge (defined by (aX, aY) (bX, bY)) intersects the box */+ private static boolean edgeIntersectsBox(+ int aX, int aY, int bX, int bY, int minX, int maxX, int minY, int maxY) {+ if (Math.max(aX, bX) < minX+ || Math.min(aX, bX) > maxX+ || Math.min(aY, bY) > maxY+ || Math.max(aY, bY) < minY) {+ return false;+ }+ return GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, maxY, maxX, maxY)+ || // top+ GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, maxY, maxX, minY)+ || // bottom+ GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, maxX, minY, minX, minY)+ || // left+ GeoUtils.lineCrossesLineWithBoundary(aX, aY, bX, bY, minX, minY, minX, maxY); // right+ }+ }++ @Override+ public String toString(String field) {+ final StringBuilder sb = new StringBuilder();+ sb.append(getClass().getSimpleName());+ sb.append(':');+ if (this.field.equals(field) == false) {+ sb.append(" field=");+ sb.append(this.field);+ sb.append(':');+ }+ sb.append("[");+ for (int i = 0; i < geometries.length; i++) {+ sb.append(geometries[i].toString());+ sb.append(',');+ }+ sb.append(']');+ return sb.toString();+ }}diff --git a/lucene/core/src/java/org/apache/lucene/document/XYShape.java b/lucene/core/src/java/org/apache/lucene/document/XYShape.javaindex d52ff49a361..de648d3ba09 100644--- a/lucene/core/src/java/org/apache/lucene/document/XYShape.java+++ b/lucene/core/src/java/org/apache/lucene/document/XYShape.java@@ -18,6 +18,7 @@ package org.apache.lucene.document;import static org.apache.lucene.geo.XYEncodingUtils.encode;+import java.util.ArrayList;import java.util.List;import org.apache.lucene.document.ShapeField.QueryRelation;import org.apache.lucene.document.ShapeField.Triangle;@@ -33,6 +34,7 @@ import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.Query;+import org.apache.lucene.util.BytesRef;/*** A cartesian shape utility class for indexing and searching geometries whose vertices are unitless@@ -42,10 +44,19 @@ import org.apache.lucene.search.Query;** <ul>* <li>{@link #createIndexableFields(String, XYPolygon)} for indexing a cartesian polygon.+ * <li>{@link #createDocValueField(String, XYPolygon)} for indexing a cartesian polygon doc value+ * field.* <li>{@link #createIndexableFields(String, XYPolygon, boolean)} for indexing a cartesian polygon* with the possibility of checking for self-intersections.+ * <li>{@link #createIndexableFields(String, XYPolygon, boolean)} for indexing a cartesian polygon+ * doc value field with the possibility of checking for self-intersections.* <li>{@link #createIndexableFields(String, XYLine)} for indexing a cartesian linestring.+ * <li>{@link #createDocValueField(String, XYLine)} for indexing a cartesian linestring doc value.* <li>{@link #createIndexableFields(String, float, float)} for indexing a x, y cartesian point.+ * <li>{@link #createDocValueField(String, float, float)} for indexing a x, y cartesian point doc+ * value.+ * <li>{@link #createDocValueField(String, BytesRef)} for indexing a cartesian doc value from+ * existing encoding.* <li>{@link #newBoxQuery newBoxQuery()} for matching cartesian shapes that have some {@link* QueryRelation} with a bounding box.* <li>{@link #newBoxQuery newLineQuery()} for matching cartesian shapes that have some {@link@@ -60,7 +71,7 @@ import org.apache.lucene.search.Query;* from the original {@code double} values.** @see PointValues- * @see LatLonDocValuesField+ * @see XYDocValuesField*/public class XYShape {@@ -72,6 +83,11 @@ public class XYShape {return createIndexableFields(fieldName, polygon, false);}+ /** create doc value field for X,Y polygon geometry without creating indexable fields */+ public static XYShapeDocValuesField createDocValueField(String fieldName, XYPolygon polygon) {+ return createDocValueField(fieldName, polygon, false);+ }+/*** create indexable fields for cartesian polygon geometry. If {@code checkSelfIntersections} is* set to true, the validity of the provided polygon is checked with a small performance penalty.@@ -88,6 +104,30 @@ public class XYShape {return fields;}+ /** create doc value field for lat lon polygon geometry without creating indexable fields. */+ public static XYShapeDocValuesField createDocValueField(+ String fieldName, XYPolygon polygon, boolean checkSelfIntersections) {+ List<Tessellator.Triangle> tessellation =+ Tessellator.tessellate(polygon, checkSelfIntersections);+ ArrayList<ShapeField.DecodedTriangle> triangles = new ArrayList<>(tessellation.size());+ for (Tessellator.Triangle t : tessellation) {+ ShapeField.DecodedTriangle dt = new ShapeField.DecodedTriangle();+ dt.type = ShapeField.DecodedTriangle.TYPE.TRIANGLE;+ dt.setValues(+ t.getEncodedX(0),+ t.getEncodedY(0),+ t.isEdgefromPolygon(0),+ t.getEncodedX(1),+ t.getEncodedY(1),+ t.isEdgefromPolygon(0),+ t.getEncodedX(2),+ t.getEncodedY(2),+ t.isEdgefromPolygon(2));+ triangles.add(dt);+ }+ return new XYShapeDocValuesField(fieldName, triangles);+ }+/** create indexable fields for cartesian line geometry */public static Field[] createIndexableFields(String fieldName, XYLine line) {int numPoints = line.numPoints();@@ -107,6 +147,29 @@ public class XYShape {return fields;}+ /** create doc value field for x, y line geometry without creating indexable fields. */+ public static XYShapeDocValuesField createDocValueField(String fieldName, XYLine line) {+ int numPoints = line.numPoints();+ List<ShapeField.DecodedTriangle> triangles = new ArrayList<>(numPoints - 1);+ // create "flat" triangles+ for (int i = 0, j = 1; j < numPoints; ++i, ++j) {+ ShapeField.DecodedTriangle t = new ShapeField.DecodedTriangle();+ t.type = ShapeField.DecodedTriangle.TYPE.LINE;+ t.setValues(+ encode(line.getX(i)),+ encode(line.getY(i)),+ true,+ encode(line.getX(j)),+ encode(line.getY(j)),+ true,+ encode(line.getX(i)),+ encode(line.getY(i)),+ true);+ triangles.add(t);+ }+ return new XYShapeDocValuesField(fieldName, triangles);+ }+/** create indexable fields for cartesian point geometry */public static Field[] createIndexableFields(String fieldName, float x, float y) {return new Field[] {@@ -114,6 +177,29 @@ public class XYShape {};}+ /**+ * create a {@link XYShapeDocValuesField} for cartesian points without creating indexable fields.+ */+ public static XYShapeDocValuesField createDocValueField(String fieldName, float x, float y) {+ List<ShapeField.DecodedTriangle> triangles = new ArrayList<>(1);+ ShapeField.DecodedTriangle t = new ShapeField.DecodedTriangle();+ t.type = ShapeField.DecodedTriangle.TYPE.POINT;+ t.setValues(encode(x), encode(y), true, encode(x), encode(y), true, encode(x), encode(y), true);+ triangles.add(t);+ return new XYShapeDocValuesField(fieldName, triangles);+ }++ /** create a {@link XYShapeDocValuesField} from an existing encoded representation */+ public static XYShapeDocValuesField createDocValueField(String fieldName, BytesRef binaryValue) {+ return new XYShapeDocValuesField(fieldName, binaryValue);+ }++ /** create a {@link XYShapeDocValuesField} from a precomputed tessellation */+ public static XYShapeDocValuesField createDocValueField(+ String fieldName, List<ShapeField.DecodedTriangle> tessellation) {+ return new XYShapeDocValuesField(fieldName, tessellation);+ }+/** create a query to find all cartesian shapes that intersect a defined bounding box * */public static Query newBoxQuery(String field, QueryRelation queryRelation, float minX, float maxX, float minY, float maxY) {@@ -121,6 +207,14 @@ public class XYShape {return newGeometryQuery(field, queryRelation, rectangle);}+ /**+ * create a docvalue query to find all cartesian shapes that intersect a defined bounding box *+ */+ public static Query newSlowDocValuesBoxQuery(+ String field, QueryRelation queryRelation, float minX, float maxX, float minY, float maxY) {+ return new XYShapeDocValuesQuery(field, queryRelation, new XYRectangle(minX, maxX, minY, maxY));+ }+/*** create a query to find all cartesian shapes that intersect a provided linestring (or array of* linestrings) *diff --git a/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValues.java b/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValues.javanew file mode 100644index 00000000000..053cf8003e9--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValues.java@@ -0,0 +1,98 @@+/*+ * 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.document;++import java.util.List;+import org.apache.lucene.geo.XYEncodingUtils;+import org.apache.lucene.geo.XYPoint;+import org.apache.lucene.geo.XYRectangle;+import org.apache.lucene.util.BytesRef;++/**+ * A concrete implementation of {@link ShapeDocValues} for storing binary doc value representation+ * of {@link XYShape} geometries in a {@link XYShapeDocValuesField}+ *+ * <p>Note: This class cannot be instantiated directly. See {@link XYShape} for factory API based on+ * different geometries.+ *+ * @lucene.experimental+ */+public final class XYShapeDocValues extends ShapeDocValues {+ /** protected ctor for instantiating a cartesian doc value based on a tessellation */+ protected XYShapeDocValues(List<ShapeField.DecodedTriangle> tessellation) {+ super(tessellation);+ }++ /**+ * protected ctor for instantiating a cartesian doc value based on an already retrieved binary+ * format+ */+ protected XYShapeDocValues(BytesRef binaryValue) {+ super(binaryValue);+ }++ @Override+ public XYPoint getCentroid() {+ return (XYPoint) centroid;+ }++ @Override+ public XYRectangle getBoundingBox() {+ return (XYRectangle) boundingBox;+ }++ @Override+ protected XYPoint computeCentroid() {+ Encoder encoder = getEncoder();+ return new XYPoint(+ (float) encoder.decodeX(getEncodedCentroidX()),+ (float) encoder.decodeY(getEncodedCentroidY()));+ }++ @Override+ protected XYRectangle computeBoundingBox() {+ Encoder encoder = getEncoder();+ return new XYRectangle(+ (float) encoder.decodeX(getEncodedMinX()), (float) encoder.decodeX(getEncodedMaxX()),+ (float) encoder.decodeY(getEncodedMinY()), (float) encoder.decodeY(getEncodedMaxY()));+ }++ @Override+ protected Encoder getEncoder() {+ return new Encoder() {+ @Override+ public int encodeX(double x) {+ return XYEncodingUtils.encode((float) x);+ }++ @Override+ public int encodeY(double y) {+ return XYEncodingUtils.encode((float) y);+ }++ @Override+ public double decodeX(int encoded) {+ return XYEncodingUtils.decode(encoded);+ }++ @Override+ public double decodeY(int encoded) {+ return XYEncodingUtils.decode(encoded);+ }+ };+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValuesField.java b/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValuesField.javanew file mode 100644index 00000000000..4297fc3505a--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValuesField.java@@ -0,0 +1,85 @@+/*+ * 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.document;++import java.util.List;+import org.apache.lucene.geo.XYEncodingUtils;+import org.apache.lucene.geo.XYLine;+import org.apache.lucene.geo.XYPoint;+import org.apache.lucene.geo.XYPolygon;+import org.apache.lucene.geo.XYRectangle;+import org.apache.lucene.index.PointValues;+import org.apache.lucene.util.BytesRef;++/**+ * Concrete implementation of a {@link ShapeDocValuesField} for cartesian geometries.+ *+ * <p>This field should be instantiated through {@link XYShape#createDocValueField(String, XYLine)}+ *+ * <ul>+ * <li>{@link XYShape#createDocValueField(String, XYPolygon)} for indexing a cartesian polygon doc+ * value field.+ * <li>{@link XYShape#createDocValueField(String, XYLine)} for indexing a cartesian linestring doc+ * value.+ * <li>{@link XYShape#createDocValueField(String, float, float)} for indexing a x, y cartesian+ * point doc value.+ * <li>{@link XYShape#createDocValueField(String, List)} for indexing a cartesian doc value from a+ * precomputed tessellation.+ * <li>{@link XYShape#createDocValueField(String, BytesRef)} for indexing a cartesian doc value+ * from existing encoding.+ * </ul>+ *+ * <b>WARNING</b>: Like {@link LatLonPoint}, vertex values are indexed with some loss of precision+ * from the original {@code double} values.+ *+ * @see PointValues+ * @see XYDocValuesField+ * @lucene.experimental+ */+public final class XYShapeDocValuesField extends ShapeDocValuesField {++ /** constructs a {@code XYShapeDocValueField} from a pre-tessellated geometry */+ protected XYShapeDocValuesField(String name, List<ShapeField.DecodedTriangle> tessellation) {+ super(name, new XYShapeDocValues(tessellation));+ }++ /** Creates a {@code XYShapeDocValueField} from a given serialized value */+ protected XYShapeDocValuesField(String name, BytesRef binaryValue) {+ super(name, new XYShapeDocValues(binaryValue));+ }++ /** retrieves the centroid location for the geometry */+ @Override+ public XYPoint getCentroid() {+ return (XYPoint) shapeDocValues.getCentroid();+ }++ @Override+ public XYRectangle getBoundingBox() {+ return (XYRectangle) shapeDocValues.getBoundingBox();+ }++ @Override+ protected double decodeX(int encoded) {+ return XYEncodingUtils.decode(encoded);+ }++ @Override+ protected double decodeY(int encoded) {+ return XYEncodingUtils.decode(encoded);+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValuesQuery.java b/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValuesQuery.javanew file mode 100644index 00000000000..fe797fd259b--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/document/XYShapeDocValuesQuery.java@@ -0,0 +1,49 @@+/*+ * 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.document;++import org.apache.lucene.geo.Component2D;+import org.apache.lucene.geo.Geometry;+import org.apache.lucene.geo.XYGeometry;+import org.apache.lucene.util.BytesRef;++/**+ * Bounding Box query for {@link ShapeDocValuesField} representing {@link XYShape}+ *+ * @lucene.experimental+ */+final class XYShapeDocValuesQuery extends BaseShapeDocValuesQuery {+ XYShapeDocValuesQuery(+ String field, ShapeField.QueryRelation queryRelation, XYGeometry... geometries) {+ super(field, queryRelation, geometries);+ }++ @Override+ protected Component2D createComponent2D(Geometry... geometries) {+ return XYGeometry.create((XYGeometry[]) geometries);+ }++ @Override+ protected ShapeDocValues getShapeDocValues(BytesRef binaryValue) {+ return new XYShapeDocValues(binaryValue);+ }++ @Override+ protected SpatialVisitor getSpatialVisitor() {+ return XYShapeQuery.getSpatialVisitor(queryComponent2D);+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/document/XYShapeQuery.java b/lucene/core/src/java/org/apache/lucene/document/XYShapeQuery.javaindex 9726d0bfa0f..70dd239dcb0 100644--- a/lucene/core/src/java/org/apache/lucene/document/XYShapeQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/XYShapeQuery.java@@ -18,11 +18,11 @@ package org.apache.lucene.document;import static org.apache.lucene.geo.XYEncodingUtils.decode;-import java.util.Arrays;import java.util.function.Function;import java.util.function.Predicate;import org.apache.lucene.document.ShapeField.QueryRelation;import org.apache.lucene.geo.Component2D;+import org.apache.lucene.geo.Geometry;import org.apache.lucene.geo.XYEncodingUtils;import org.apache.lucene.geo.XYGeometry;import org.apache.lucene.index.PointValues.Relation;@@ -33,20 +33,22 @@ import org.apache.lucene.util.NumericUtils;* the specified array of {@link XYGeometry}.** <p>The field must be indexed using {@link XYShape#createIndexableFields} added per document.+ *+ * @lucene.internal*/final class XYShapeQuery extends SpatialQuery {- final XYGeometry[] geometries;- private final Component2D component2D;/** Creates a query that matches all indexed shapes to the provided polygons */XYShapeQuery(String field, QueryRelation queryRelation, XYGeometry... geometries) {- super(field, queryRelation);- this.component2D = XYGeometry.create(geometries);- this.geometries = geometries.clone();+ super(field, queryRelation, geometries);}@Override- protected SpatialVisitor getSpatialVisitor() {+ protected Component2D createComponent2D(Geometry... geometries) {+ return XYGeometry.create((XYGeometry[]) geometries);+ }++ static SpatialVisitor getSpatialVisitor(Component2D component2D) {return new SpatialVisitor() {@Overrideprotected Relation relate(byte[] minTriangle, byte[] maxTriangle) {@@ -191,33 +193,7 @@ final class XYShapeQuery extends SpatialQuery {}@Override- public String toString(String field) {- final StringBuilder sb = new StringBuilder();- sb.append(getClass().getSimpleName());- sb.append(':');- if (this.field.equals(field) == false) {- sb.append(" field=");- sb.append(this.field);- sb.append(':');- }- sb.append("[");- for (int i = 0; i < geometries.length; i++) {- sb.append(geometries[i].toString());- sb.append(',');- }- sb.append(']');- return sb.toString();- }-- @Override- protected boolean equalsTo(Object o) {- return super.equalsTo(o) && Arrays.equals(geometries, ((XYShapeQuery) o).geometries);- }-- @Override- public int hashCode() {- int hash = super.hashCode();- hash = 31 * hash + Arrays.hashCode(geometries);- return hash;+ protected SpatialVisitor getSpatialVisitor() {+ return getSpatialVisitor(queryComponent2D);}}diff --git a/lucene/core/src/java/org/apache/lucene/geo/Geometry.java b/lucene/core/src/java/org/apache/lucene/geo/Geometry.javanew file mode 100644index 00000000000..d1007ccf845--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/geo/Geometry.java@@ -0,0 +1,23 @@+/*+ * 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;++/** Base class for {@link LatLonGeometry} and {@link XYGeometry} */+public abstract class Geometry {+ /** get a Component2D from the geometry object */+ protected abstract Component2D toComponent2D();+}diff --git a/lucene/core/src/java/org/apache/lucene/geo/LatLonGeometry.java b/lucene/core/src/java/org/apache/lucene/geo/LatLonGeometry.javaindex ecdf05eb7a4..1d9631e1a98 100644--- a/lucene/core/src/java/org/apache/lucene/geo/LatLonGeometry.java+++ b/lucene/core/src/java/org/apache/lucene/geo/LatLonGeometry.java@@ -18,10 +18,7 @@package org.apache.lucene.geo;/** Lat/Lon Geometry object. */-public abstract class LatLonGeometry {-- /** get a {@link Component2D} from this geometry */- protected abstract Component2D toComponent2D();+public abstract class LatLonGeometry extends Geometry {/** Creates a Component2D from the provided LatLonGeometry array */public static Component2D create(LatLonGeometry... latLonGeometries) {diff --git a/lucene/core/src/java/org/apache/lucene/geo/XYGeometry.java b/lucene/core/src/java/org/apache/lucene/geo/XYGeometry.javaindex a450adcd6db..cb7837ef8ea 100644--- a/lucene/core/src/java/org/apache/lucene/geo/XYGeometry.java+++ b/lucene/core/src/java/org/apache/lucene/geo/XYGeometry.java@@ -18,10 +18,7 @@package org.apache.lucene.geo;/** Cartesian Geometry object. */-public abstract class XYGeometry {-- /** get a Component2D from this object */- protected abstract Component2D toComponent2D();+public abstract class XYGeometry extends Geometry {/** Creates a Component2D from the provided XYGeometries array */public static Component2D create(XYGeometry... xyGeometries) {diff --git a/lucene/core/src/test/org/apache/lucene/document/BaseLatLonShapeDocValueTestCase.java b/lucene/core/src/test/org/apache/lucene/document/BaseLatLonShapeDocValueTestCase.javanew file mode 100644index 00000000000..1f79b6b8f97--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/BaseLatLonShapeDocValueTestCase.java@@ -0,0 +1,75 @@+/*+ * 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.document;++import java.util.Arrays;+import org.apache.lucene.geo.Circle;+import org.apache.lucene.geo.Line;+import org.apache.lucene.geo.Polygon;+import org.apache.lucene.search.Query;++/** Base test class for LatLonShape doc values */+public abstract class BaseLatLonShapeDocValueTestCase extends BaseLatLonSpatialTestCase {++ @Override+ protected ShapeField.QueryRelation[] getSupportedQueryRelations() {+ return new ShapeField.QueryRelation[] {+ ShapeField.QueryRelation.INTERSECTS,+ ShapeField.QueryRelation.WITHIN,+ ShapeField.QueryRelation.DISJOINT+ };+ }++ @Override+ protected Query newRectQuery(+ String field,+ ShapeField.QueryRelation queryRelation,+ double minLon,+ double maxLon,+ double minLat,+ double maxLat) {+ return LatLonShape.newSlowDocValuesBoxQuery(+ field, queryRelation, minLat, maxLat, minLon, maxLon);+ }++ @Override+ protected Query newLineQuery(+ String field, ShapeField.QueryRelation queryRelation, Object... lines) {+ return ShapeDocValuesField.newGeometryQuery(+ field, queryRelation, (Object) Arrays.stream(lines).toArray(Line[]::new));+ }++ @Override+ protected Query newPolygonQuery(+ String field, ShapeField.QueryRelation queryRelation, Object... polygons) {+ return ShapeDocValuesField.newGeometryQuery(+ field, queryRelation, (Object) Arrays.stream(polygons).toArray(Polygon[]::new));+ }++ @Override+ protected Query newPointsQuery(+ String field, ShapeField.QueryRelation queryRelation, Object... points) {+ return ShapeDocValuesField.newGeometryQuery(+ field, queryRelation, (Object) Arrays.stream(points).toArray(double[][]::new));+ }++ @Override+ protected Query newDistanceQuery(+ String field, ShapeField.QueryRelation queryRelation, Object circle) {+ return LatLonShape.newDistanceQuery(field, queryRelation, (Circle) circle);+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/BaseSpatialTestCase.java b/lucene/core/src/test/org/apache/lucene/document/BaseSpatialTestCase.javaindex 233b152370f..ae05a73843a 100644--- a/lucene/core/src/test/org/apache/lucene/document/BaseSpatialTestCase.java+++ b/lucene/core/src/test/org/apache/lucene/document/BaseSpatialTestCase.java@@ -174,6 +174,10 @@ public abstract class BaseSpatialTestCase extends LuceneTestCase {protected abstract boolean rectCrossesDateline(Object rect);+ protected QueryRelation[] getSupportedQueryRelations() {+ return QueryRelation.values();+ }+/*** return a semi-random line used for queries*@@ -304,7 +308,7 @@ public abstract class BaseSpatialTestCase extends LuceneTestCase {// BBoxObject rect = randomQueryBox();- QueryRelation queryRelation = RandomPicks.randomFrom(random(), QueryRelation.values());+ QueryRelation queryRelation = RandomPicks.randomFrom(random(), getSupportedQueryRelations());Query query =newRectQuery(FIELD_NAME,diff --git a/lucene/core/src/test/org/apache/lucene/document/BaseXYShapeDocValueTestCase.java b/lucene/core/src/test/org/apache/lucene/document/BaseXYShapeDocValueTestCase.javanew file mode 100644index 00000000000..112ef6412ea--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/BaseXYShapeDocValueTestCase.java@@ -0,0 +1,74 @@+/*+ * 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.document;++import java.util.Arrays;+import org.apache.lucene.geo.Circle;+import org.apache.lucene.geo.XYLine;+import org.apache.lucene.geo.XYPolygon;+import org.apache.lucene.search.Query;++/** Base test class for XYShape doc values */+public abstract class BaseXYShapeDocValueTestCase extends BaseXYShapeTestCase {+ @Override+ protected ShapeField.QueryRelation[] getSupportedQueryRelations() {+ return new ShapeField.QueryRelation[] {+ ShapeField.QueryRelation.INTERSECTS,+ ShapeField.QueryRelation.WITHIN,+ ShapeField.QueryRelation.DISJOINT+ };+ }++ @Override+ protected Query newRectQuery(+ String field,+ ShapeField.QueryRelation queryRelation,+ double minX,+ double maxX,+ double minY,+ double maxY) {+ return XYShape.newSlowDocValuesBoxQuery(+ field, queryRelation, (float) minX, (float) maxX, (float) minY, (float) maxY);+ }++ @Override+ protected Query newLineQuery(+ String field, ShapeField.QueryRelation queryRelation, Object... lines) {+ return ShapeDocValuesField.newGeometryQuery(+ field, queryRelation, (Object) Arrays.stream(lines).toArray(XYLine[]::new));+ }++ @Override+ protected Query newPolygonQuery(+ String field, ShapeField.QueryRelation queryRelation, Object... polygons) {+ return ShapeDocValuesField.newGeometryQuery(+ field, queryRelation, (Object) Arrays.stream(polygons).toArray(XYPolygon[]::new));+ }++ @Override+ protected Query newPointsQuery(+ String field, ShapeField.QueryRelation queryRelation, Object... points) {+ return ShapeDocValuesField.newGeometryQuery(+ field, queryRelation, (Object) Arrays.stream(points).toArray(float[][]::new));+ }++ @Override+ protected Query newDistanceQuery(+ String field, ShapeField.QueryRelation queryRelation, Object circle) {+ return LatLonShape.newDistanceQuery(field, queryRelation, (Circle) circle);+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestLatLonLineShapeDVQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestLatLonLineShapeDVQueries.javanew file mode 100644index 00000000000..0551dc9b447--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestLatLonLineShapeDVQueries.java@@ -0,0 +1,66 @@+/*+ * 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.document;++import org.apache.lucene.geo.Line;+import org.apache.lucene.index.IndexReader;++/** Tests queries over geographic line shape doc values */+public class TestLatLonLineShapeDVQueries extends BaseLatLonShapeDocValueTestCase {+ @Override+ protected ShapeType getShapeType() {+ return ShapeType.LINE;+ }++ @Override+ protected Field[] createIndexableFields(String field, Object shape) {+ Line line = (Line) shape;+ Field[] fields = new Field[1];+ fields[0] = LatLonShape.createDocValueField(FIELD_NAME, line);+ return fields;+ }++ @Override+ protected Validator getValidator() {+ return new TestLatLonLineShapeQueries.LineValidator(this.ENCODER);+ }++ /** test random line queries */+ @Override+ protected void verifyRandomLineQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random polygon queries */+ @Override+ protected void verifyRandomPolygonQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random point queries */+ @Override+ protected void verifyRandomPointQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random distance queries */+ @Override+ protected void verifyRandomDistanceQueries(IndexReader reader, Object... shapes)+ throws Exception {+ // NOT IMPLEMENTED YET+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestLatLonLineShapeQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestLatLonLineShapeQueries.javaindex 9b96f1280ca..21bf0122f22 100644--- a/lucene/core/src/test/org/apache/lucene/document/TestLatLonLineShapeQueries.java+++ b/lucene/core/src/test/org/apache/lucene/document/TestLatLonLineShapeQueries.java@@ -68,7 +68,7 @@ public class TestLatLonLineShapeQueries extends BaseLatLonShapeTestCase {return new LineValidator(this.ENCODER);}- protected static class LineValidator extends Validator {+ public static class LineValidator extends Validator {protected LineValidator(Encoder encoder) {super(encoder);}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestLatLonPointShapeDVQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestLatLonPointShapeDVQueries.javanew file mode 100644index 00000000000..398d2aefddd--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestLatLonPointShapeDVQueries.java@@ -0,0 +1,66 @@+/*+ * 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.document;++import org.apache.lucene.geo.Point;+import org.apache.lucene.index.IndexReader;++/** Tests queries over geographic point shape doc values */+public class TestLatLonPointShapeDVQueries extends BaseLatLonShapeDocValueTestCase {+ @Override+ protected ShapeType getShapeType() {+ return ShapeType.POINT;+ }++ @Override+ protected Field[] createIndexableFields(String field, Object shape) {+ Point point = (Point) shape;+ Field[] fields = new Field[1];+ fields[0] = LatLonShape.createDocValueField(FIELD_NAME, point.getLat(), point.getLon());+ return fields;+ }++ @Override+ protected Validator getValidator() {+ return new TestLatLonPointShapeQueries.PointValidator(this.ENCODER);+ }++ /** test random line queries */+ @Override+ protected void verifyRandomLineQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random polygon queries */+ @Override+ protected void verifyRandomPolygonQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random point queries */+ @Override+ protected void verifyRandomPointQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random distance queries */+ @Override+ protected void verifyRandomDistanceQueries(IndexReader reader, Object... shapes)+ throws Exception {+ // NOT IMPLEMENTED YET+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestLatLonPolygonShapeDVQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestLatLonPolygonShapeDVQueries.javanew file mode 100644index 00000000000..9713da7c849--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestLatLonPolygonShapeDVQueries.java@@ -0,0 +1,67 @@+/*+ * 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.document;++import org.apache.lucene.geo.Polygon;+import org.apache.lucene.index.IndexReader;++/** Test queries over LatLon Polygon ShapeDocValues */+public class TestLatLonPolygonShapeDVQueries extends BaseLatLonShapeDocValueTestCase {++ @Override+ protected ShapeType getShapeType() {+ return ShapeType.POLYGON;+ }++ @Override+ protected Field[] createIndexableFields(String field, Object shape) {+ Polygon polygon = (Polygon) shape;+ Field[] fields = new Field[1];+ fields[0] = LatLonShape.createDocValueField(FIELD_NAME, polygon);+ return fields;+ }++ @Override+ protected Validator getValidator() {+ return new TestLatLonPolygonShapeQueries.PolygonValidator(this.ENCODER);+ }++ /** test random line queries */+ @Override+ protected void verifyRandomLineQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random polygon queries */+ @Override+ protected void verifyRandomPolygonQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random point queries */+ @Override+ protected void verifyRandomPointQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random distance queries */+ @Override+ protected void verifyRandomDistanceQueries(IndexReader reader, Object... shapes)+ throws Exception {+ // NOT IMPLEMENTED YET+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestLatLonPolygonShapeQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestLatLonPolygonShapeQueries.javaindex 002cf4be49e..bbb50153f51 100644--- a/lucene/core/src/test/org/apache/lucene/document/TestLatLonPolygonShapeQueries.java+++ b/lucene/core/src/test/org/apache/lucene/document/TestLatLonPolygonShapeQueries.java@@ -38,7 +38,7 @@ public class TestLatLonPolygonShapeQueries extends BaseLatLonShapeTestCase {return new PolygonValidator(this.ENCODER);}- protected static class PolygonValidator extends Validator {+ public static class PolygonValidator extends Validator {protected PolygonValidator(Encoder encoder) {super(encoder);}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestShapeDocValues.java b/lucene/core/src/test/org/apache/lucene/document/TestShapeDocValues.javanew file mode 100644index 00000000000..e00cd82156f--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestShapeDocValues.java@@ -0,0 +1,213 @@+/*+ * 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.document;++import java.util.ArrayList;+import java.util.List;+import java.util.function.BiFunction;+import java.util.function.IntFunction;+import org.apache.lucene.document.ShapeField.DecodedTriangle.TYPE;+import org.apache.lucene.geo.GeoEncodingUtils;+import org.apache.lucene.geo.Geometry;+import org.apache.lucene.geo.LatLonGeometry;+import org.apache.lucene.geo.Point;+import org.apache.lucene.geo.Polygon;+import org.apache.lucene.geo.Rectangle;+import org.apache.lucene.geo.SimpleWKTShapeParser;+import org.apache.lucene.geo.XYEncodingUtils;+import org.apache.lucene.geo.XYPoint;+import org.apache.lucene.geo.XYPolygon;+import org.apache.lucene.geo.XYRectangle;+import org.apache.lucene.index.PointValues;+import org.apache.lucene.store.ByteBuffersDataOutput;+import org.apache.lucene.tests.geo.GeoTestUtil;+import org.apache.lucene.tests.util.LuceneTestCase;++/** Simple tests for {@link org.apache.lucene.document.ShapeDocValuesField} */+public class TestShapeDocValues extends LuceneTestCase {+ private static double TOLERANCE = 1E-7;++ private static final String FIELD_NAME = "field";++ public void testSimpleDocValue() throws Exception {+ ShapeDocValues dv = new LatLonShapeDocValues(getTessellation(getTestPolygonWithHole()));+ // tests geometry inside a hole and crossing+ assertEquals(+ dv.relate(LatLonGeometry.create(new Rectangle(-0.25, -0.24, -3.8, -3.7))),+ PointValues.Relation.CELL_OUTSIDE_QUERY);+ assertNotEquals(+ dv.relate(LatLonGeometry.create(new Rectangle(-1.2, 1.2, -1.5, 1.7))),+ PointValues.Relation.CELL_CROSSES_QUERY);+ }++ public void testLatLonPolygonBBox() {+ Polygon p = GeoTestUtil.nextPolygon();+ Rectangle expected = new Rectangle(p.minLat, p.maxLat, p.minLon, p.maxLon);+ LatLonShapeDocValuesField dv = LatLonShape.createDocValueField(FIELD_NAME, p);+ assertEquals(expected.minLat, dv.getBoundingBox().minLat, TOLERANCE);+ assertEquals(expected.maxLat, dv.getBoundingBox().maxLat, TOLERANCE);+ assertEquals(expected.minLon, dv.getBoundingBox().minLon, TOLERANCE);+ assertEquals(expected.maxLon, dv.getBoundingBox().maxLon, TOLERANCE);+ }++ public void testXYPolygonBBox() {+ XYPolygon p = (XYPolygon) BaseXYShapeTestCase.ShapeType.POLYGON.nextShape();+ XYRectangle expected = new XYRectangle(p.minX, p.maxX, p.minY, p.maxY);+ XYShapeDocValuesField dv = XYShape.createDocValueField(FIELD_NAME, p);+ assertEquals(expected.minX, dv.getBoundingBox().minX, TOLERANCE);+ assertEquals(expected.maxX, dv.getBoundingBox().maxX, TOLERANCE);+ assertEquals(expected.minY, dv.getBoundingBox().minY, TOLERANCE);+ assertEquals(expected.maxY, dv.getBoundingBox().maxY, TOLERANCE);+ }++ public void testLatLonPolygonCentroid() {+ Polygon p = GeoTestUtil.nextPolygon();+ Point expected = (Point) computeCentroid(p);+ List<ShapeField.DecodedTriangle> tess = getTessellation(p);+ LatLonShapeDocValuesField dvField = LatLonShape.createDocValueField(FIELD_NAME, p);+ assertEquals(tess.size(), dvField.numberOfTerms());+ assertEquals(expected.getLat(), dvField.getCentroid().getLat(), TOLERANCE);+ assertEquals(expected.getLon(), dvField.getCentroid().getLon(), TOLERANCE);+ assertEquals(TYPE.TRIANGLE, dvField.getHighestDimensionType());+ }++ public void testXYPolygonCentroid() {+ XYPolygon p = (XYPolygon) BaseXYShapeTestCase.ShapeType.POLYGON.nextShape();+ XYPoint expected = (XYPoint) computeCentroid(p);+ XYShapeDocValuesField dvField = XYShape.createDocValueField(FIELD_NAME, getTessellation(p));+ assertEquals(expected.getX(), dvField.getCentroid().getX(), TOLERANCE);+ assertEquals(expected.getY(), dvField.getCentroid().getY(), TOLERANCE);+ assertEquals(TYPE.TRIANGLE, dvField.getHighestDimensionType());+ }++ private Geometry computeCentroid(Geometry p) {+ List<ShapeField.DecodedTriangle> tess = getTessellation(p);+ double totalSignedArea = 0;+ double numXPly = 0;+ double numYPly = 0;+ double ax, bx, cx;+ double ay, by, cy;+ IntFunction<Double> decodeX =+ p instanceof Polygon+ ? (x) -> GeoEncodingUtils.decodeLongitude(x)+ : (x) -> (double) XYEncodingUtils.decode(x);+ IntFunction<Double> decodeY =+ p instanceof Polygon+ ? (y) -> GeoEncodingUtils.decodeLatitude(y)+ : (y) -> (double) XYEncodingUtils.decode(y);+ BiFunction<Double, Double, Geometry> createPoint =+ p instanceof Polygon+ ? (x, y) -> new Point(y, x)+ : (x, y) -> new XYPoint(x.floatValue(), y.floatValue());++ for (ShapeField.DecodedTriangle t : tess) {+ ax = decodeX.apply(t.aX);+ ay = decodeY.apply(t.aY);+ bx = decodeX.apply(t.bX);+ by = decodeY.apply(t.bY);+ cx = decodeX.apply(t.cX);+ cy = decodeY.apply(t.cY);++ double signedArea = Math.abs(0.5d * ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)));+ // accumulate midPoints and signed area+ numXPly += (((ax + bx + cx) / 3d) * signedArea);+ numYPly += (((ay + by + cy) / 3d) * signedArea);+ totalSignedArea += signedArea;+ }+ totalSignedArea = totalSignedArea == 0d ? 1 : totalSignedArea;+ return createPoint.apply(numXPly / totalSignedArea, numYPly / totalSignedArea);+ }++ public void testExplicitLatLonPolygonCentroid() throws Exception {+ String mp = "POLYGON((-80 -10, -40 -10, -40 10, -80 10, -80 -10))";+ Polygon p = (Polygon) SimpleWKTShapeParser.parse(mp);+ List<ShapeField.DecodedTriangle> tess = getTessellation(p);+ LatLonShapeDocValuesField dvField = LatLonShape.createDocValueField(FIELD_NAME, tess);+ assertEquals(0d, dvField.getCentroid().getLat(), 1E-7);+ assertEquals(-60.0, dvField.getCentroid().getLon(), 1E-7);+ assertEquals(TYPE.TRIANGLE, dvField.getHighestDimensionType());+ }++ /**+ * ensures consistency between {@link ByteBuffersDataOutput#writeVInt(int)} and {@link+ * ShapeDocValues#vIntSize(int)} and {@link ByteBuffersDataOutput#writeVLong(long)} and {@link+ * ShapeDocValues#vLongSize(long)} so the serialization is valid.+ */+ public void testVariableValueSizes() throws Exception {+ // scratch buffer+ ByteBuffersDataOutput out = new ByteBuffersDataOutput();++ for (int i = 0; i < random().nextInt(100, 500); ++i) {+ // test variable int sizes+ int testInt = random().nextInt(Integer.MAX_VALUE);+ long pB = out.size();+ out.writeVInt(testInt);+ long pA = out.size();+ assertEquals(ShapeDocValues.vIntSize(testInt), (int) (pA - pB));++ // test variable long sizes+ long testLong = random().nextLong(Long.MAX_VALUE);+ out.writeVLong(testLong);+ assertEquals(ShapeDocValues.vLongSize(testLong), out.size() - pA);+ }+ }++ private Polygon getTestPolygonWithHole() {+ Polygon poly = GeoTestUtil.createRegularPolygon(0.0, 0.0, 100000, 7);+ Polygon inner =+ new Polygon(+ new double[] {-1.0, -1.0, 0.5, 1.0, 1.0, 0.5, -1.0},+ new double[] {1.0, -1.0, -0.5, -1.0, 1.0, 0.5, 1.0});+ Polygon inner2 =+ new Polygon(+ new double[] {-1.0, -1.0, 0.5, 1.0, 1.0, 0.5, -1.0},+ new double[] {-2.0, -4.0, -3.5, -4.0, -2.0, -2.5, -2.0});++ return new Polygon(poly.getPolyLats(), poly.getPolyLons(), inner, inner2);+ }++ private List<ShapeField.DecodedTriangle> getTessellation(Geometry p) {+ if (p instanceof Polygon) {+ return getTessellation((Polygon) p);+ } else if (p instanceof XYPolygon) {+ return getTessellation((XYPolygon) p);+ }+ throw new IllegalArgumentException("invalid geometry type: " + p.getClass());+ }++ private List<ShapeField.DecodedTriangle> getTessellation(Polygon p) {+ Field[] fields = LatLonShape.createIndexableFields(FIELD_NAME, p);+ List<ShapeField.DecodedTriangle> tess = new ArrayList<>(fields.length);+ for (Field f : fields) {+ ShapeField.DecodedTriangle d = new ShapeField.DecodedTriangle();+ ShapeField.decodeTriangle(f.binaryValue().bytes, d);+ tess.add(d);+ }+ return tess;+ }++ private List<ShapeField.DecodedTriangle> getTessellation(XYPolygon p) {+ Field[] fields = XYShape.createIndexableFields(FIELD_NAME, p, true);+ List<ShapeField.DecodedTriangle> tess = new ArrayList<>(fields.length);+ for (Field f : fields) {+ ShapeField.DecodedTriangle d = new ShapeField.DecodedTriangle();+ ShapeField.decodeTriangle(f.binaryValue().bytes, d);+ tess.add(d);+ }+ return tess;+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestXYLineShapeDVQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestXYLineShapeDVQueries.javanew file mode 100644index 00000000000..d92425509f5--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestXYLineShapeDVQueries.java@@ -0,0 +1,66 @@+/*+ * 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.document;++import org.apache.lucene.geo.XYLine;+import org.apache.lucene.index.IndexReader;++/** Tests queries over cartesian line shape doc values */+public class TestXYLineShapeDVQueries extends BaseXYShapeDocValueTestCase {+ @Override+ protected ShapeType getShapeType() {+ return ShapeType.LINE;+ }++ @Override+ protected Field[] createIndexableFields(String field, Object shape) {+ XYLine line = (XYLine) shape;+ Field[] fields = new Field[1];+ fields[0] = XYShape.createDocValueField(FIELD_NAME, line);+ return fields;+ }++ @Override+ protected Validator getValidator() {+ return new TestXYLineShapeQueries.LineValidator(this.ENCODER);+ }++ /** test random line queries */+ @Override+ protected void verifyRandomLineQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random polygon queries */+ @Override+ protected void verifyRandomPolygonQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random point queries */+ @Override+ protected void verifyRandomPointQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random distance queries */+ @Override+ protected void verifyRandomDistanceQueries(IndexReader reader, Object... shapes)+ throws Exception {+ // NOT IMPLEMENTED YET+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestXYPointShapeDVQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestXYPointShapeDVQueries.javanew file mode 100644index 00000000000..e735ca4fefe--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestXYPointShapeDVQueries.java@@ -0,0 +1,66 @@+/*+ * 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.document;++import org.apache.lucene.geo.XYPoint;+import org.apache.lucene.index.IndexReader;++/** Tests queries over cartesian point shape doc values */+public class TestXYPointShapeDVQueries extends BaseXYShapeDocValueTestCase {+ @Override+ protected ShapeType getShapeType() {+ return ShapeType.POINT;+ }++ @Override+ protected Field[] createIndexableFields(String field, Object shape) {+ XYPoint point = (XYPoint) shape;+ Field[] fields = new Field[1];+ fields[0] = XYShape.createDocValueField(FIELD_NAME, point.getX(), point.getY());+ return fields;+ }++ @Override+ protected Validator getValidator() {+ return new TestXYPointShapeQueries.PointValidator(this.ENCODER);+ }++ /** test random line queries */+ @Override+ protected void verifyRandomLineQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random polygon queries */+ @Override+ protected void verifyRandomPolygonQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random point queries */+ @Override+ protected void verifyRandomPointQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random distance queries */+ @Override+ protected void verifyRandomDistanceQueries(IndexReader reader, Object... shapes)+ throws Exception {+ // NOT IMPLEMENTED YET+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestXYPolygonShapeDVQueries.java b/lucene/core/src/test/org/apache/lucene/document/TestXYPolygonShapeDVQueries.javanew file mode 100644index 00000000000..8dd7439f9e5--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/document/TestXYPolygonShapeDVQueries.java@@ -0,0 +1,67 @@+/*+ * 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.document;++import org.apache.lucene.geo.XYPolygon;+import org.apache.lucene.index.IndexReader;++/** Test queries over {@link org.apache.lucene.geo.XYPolygon} doc value geometries */+public class TestXYPolygonShapeDVQueries extends BaseXYShapeDocValueTestCase {++ @Override+ protected ShapeType getShapeType() {+ return ShapeType.POLYGON;+ }++ @Override+ protected Field[] createIndexableFields(String field, Object shape) {+ XYPolygon polygon = (XYPolygon) shape;+ Field[] fields = new Field[1];+ fields[0] = XYShape.createDocValueField(FIELD_NAME, polygon);+ return fields;+ }++ @Override+ protected Validator getValidator() {+ return new TestXYPolygonShapeQueries.PolygonValidator(this.ENCODER);+ }++ /** test random line queries */+ @Override+ protected void verifyRandomLineQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random polygon queries */+ @Override+ protected void verifyRandomPolygonQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random point queries */+ @Override+ protected void verifyRandomPointQueries(IndexReader reader, Object... shapes) throws Exception {+ // NOT IMPLEMENTED YET+ }++ /** test random distance queries */+ @Override+ protected void verifyRandomDistanceQueries(IndexReader reader, Object... shapes)+ throws Exception {+ // NOT IMPLEMENTED YET+ }+}