This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit 9c2621366ee6c1d440db2fff1d3d67ae9d68f22f Author: jsorel <[email protected]> AuthorDate: Fri Nov 27 09:58:47 2026 +0100 feat(Geometry): add Orthtree, a quadtree and octree index --- .../org/apache/sis/geometries/index/Orthtree.java | 321 +++++++++++++++++++++ .../apache/sis/geometries/index/OrthtreeTest.java | 120 ++++++++ 2 files changed, 441 insertions(+) diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/index/Orthtree.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/index/Orthtree.java new file mode 100644 index 0000000000..eeae843de8 --- /dev/null +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/index/Orthtree.java @@ -0,0 +1,321 @@ +/* + * 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.sis.geometries.index; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Predicate; +import org.opengis.geometry.Envelope; +import org.apache.sis.geometries.operation.Intersection; +import org.apache.sis.geometry.GeneralEnvelope; +import org.apache.sis.maths.Vector; +import org.apache.sis.util.ArgumentChecks; + + +/** + * A tree dividing a box in 2<sup><var>n</var></sup> equal boxes at each level, in <var>n</var> dimensions: + * a quadtree in 2 dimensions, an octree in 3 dimensions. Each item is stored with its box in the deepest node + * whose region contains the whole box, so the queries visit only the nodes whose regions meet the queried region. + * + * <ul> + * <li>The nodes are created when items are inserted, and removed when they become empty.</li> + * <li>An item crossing the boundary between two regions stays in the node containing both.</li> + * <li>The items are compared with {@code equals}: an item is held at most once.</li> + * <li>This class is not thread-safe.</li> + * </ul> + * + * @author Johann Sorel (Geomatys) + * @param <T> type of the items. + * + * @see <a href="https://en.wikipedia.org/wiki/Quadtree">Quadtree</a> + * @see <a href="https://en.wikipedia.org/wiki/Octree">Octree</a> + */ +public final class Orthtree<T> { + + /** + * Default maximal depth of the tree, the root having a depth of 0. + */ + public static final int DEFAULT_MAX_DEPTH = 16; + + /** + * Maximal depth of the tree, the root having a depth of 0. + */ + private final int maxDepth; + + /** + * The node covering the whole region of this tree. + */ + private final Node<T> root; + + /** + * The node holding each item. + */ + private final Map<T, Node<T>> locations = new HashMap<>(); + + /** + * Creates an empty tree covering the given region, with the {@linkplain #DEFAULT_MAX_DEPTH default maximal depth}. + * + * @param region the region covered by this tree. + */ + public Orthtree(final Envelope region) { + this(region, DEFAULT_MAX_DEPTH); + } + + /** + * Creates an empty tree covering the given region. + * + * @param region the region covered by this tree. + * @param maxDepth maximal depth of the tree, 0 for a single node. + */ + public Orthtree(final Envelope region, final int maxDepth) { + ArgumentChecks.ensurePositive("maxDepth", maxDepth); + this.maxDepth = maxDepth; + this.root = new Node<>(null, -1, new GeneralEnvelope(region)); + } + + /** + * Returns the region covered by this tree. + * + * @return a copy of the region covered by this tree. + */ + public Envelope getRegion() { + return new GeneralEnvelope(root.region); + } + + /** + * Returns the number of items in this tree. + * + * @return number of items. + */ + public int size() { + return locations.size(); + } + + /** + * Returns whether this tree has no item. + * + * @return whether this tree is empty. + */ + public boolean isEmpty() { + return locations.isEmpty(); + } + + /** + * Inserts an item with its box. An item already in this tree is moved to the new box. + * + * @param item the item to insert. + * @param box the box of the item, of the dimension of this tree. + * @return {@code true} if the item has been inserted, or {@code false} if the box is outside the region of this tree. + */ + public boolean insert(final T item, final Envelope box) { + ArgumentChecks.ensureDimensionMatches("box", root.region.getDimension(), box); + if (!root.region.contains(box, true)) { + return false; + } + remove(item); + Node<T> node = root; + for (int depth = 0; depth < maxDepth; depth++) { + final int index = node.childIndex(box); + if (index < 0) { + break; // The box crosses the boundaries of the children. + } + node = node.child(index); + } + node.items.put(item, new GeneralEnvelope(box)); + locations.put(item, node); + return true; + } + + /** + * Removes an item. + * + * @param item the item to remove. + * @return whether the item was in this tree. + */ + public boolean remove(final T item) { + Node<T> node = locations.remove(item); + if (node == null) { + return false; + } + node.items.remove(item); + while (node.parent != null && node.isEmpty()) { + node.parent.children[node.index] = null; + node = node.parent; + } + return true; + } + + /** + * Returns the items whose boxes intersect the given region, boundaries included. + * + * @param region the region to query, of the dimension of this tree. + * @return the items whose boxes intersect the region. + */ + public List<T> intersecting(final Envelope region) { + final List<T> result = new ArrayList<>(); + visit((node) -> node.region.intersects(region, true), (item, box) -> { + if (box.intersects(region, true)) result.add(item); + }); + return result; + } + + /** + * Returns the items whose boxes are inside the given region, boundaries included. + * + * @param region the region to query, of the dimension of this tree. + * @return the items whose boxes are inside the region. + */ + public List<T> within(final Envelope region) { + final GeneralEnvelope query = new GeneralEnvelope(region); + final List<T> result = new ArrayList<>(); + visit((node) -> node.region.intersects(region, true), (item, box) -> { + if (query.contains(box, true)) result.add(item); + }); + return result; + } + + /** + * Returns the items whose boxes are crossed by the given ray, the nearest first. + * + * @param origin start of the ray. + * @param direction direction of the ray, not zero. + * @return the items whose boxes are crossed by the ray, by increasing distance from the origin. + * + * @see Intersection#rayBox(Vector, Vector, Envelope) + */ + public List<T> raycast(final Vector<?> origin, final Vector<?> direction) { + final Map<T, Double> hits = new LinkedHashMap<>(); + visit((node) -> !Intersection.rayBox(origin, direction, node.region).isEmpty(), (item, box) -> { + final Intersection.RayInterval hit = Intersection.rayBox(origin, direction, box); + if (!hit.isEmpty()) hits.put(item, hit.start()); + }); + final List<T> result = new ArrayList<>(hits.keySet()); + result.sort(Comparator.comparingDouble(hits::get)); + return result; + } + + /** + * Visits the items of the nodes accepted by the given filter, the children of a node being visited + * only if that node is accepted. + */ + private void visit(final Predicate<Node<T>> filter, + final BiConsumer<T, GeneralEnvelope> action) + { + final Deque<Node<T>> stack = new ArrayDeque<>(); + stack.push(root); + while (!stack.isEmpty()) { + final Node<T> node = stack.pop(); + if (filter.test(node)) { + node.items.forEach(action); + if (node.children != null) { + for (final Node<T> child : node.children) { + if (child != null) stack.push(child); + } + } + } + } + } + + /** + * A node of the tree: a region, the items held in this region but in none of its children, and the children. + */ + private static final class Node<T> { + /** The node containing this node, or {@code null} for the root. */ + final Node<T> parent; + + /** Index of this node in the children of its parent, or -1 for the root. */ + final int index; + + /** The region covered by this node. */ + final GeneralEnvelope region; + + /** The items of this node with their boxes, in insertion order. */ + final Map<T, GeneralEnvelope> items = new LinkedHashMap<>(); + + /** The 2<sup><var>n</var></sup> children, created when needed, or {@code null} if none. */ + Node<T>[] children; + + Node(final Node<T> parent, final int index, final GeneralEnvelope region) { + this.parent = parent; + this.index = index; + this.region = region; + } + + /** + * Returns whether this node has no item and no child. + */ + boolean isEmpty() { + if (!items.isEmpty()) return false; + if (children != null) { + for (final Node<T> child : children) { + if (child != null) return false; + } + } + return true; + } + + /** + * Returns the index of the child whose region contains the whole box, or -1 if the box crosses + * the middle of this region on an axis. Bit <var>i</var> of the index is set for the upper half on axis <var>i</var>. + */ + int childIndex(final Envelope box) { + int index = 0; + for (int i = 0; i < region.getDimension(); i++) { + final double median = region.getMedian(i); + if (box.getMinimum(i) >= median) { + index |= (1 << i); + } else if (box.getMaximum(i) > median) { + return -1; + } + } + return index; + } + + /** + * Returns the child at the given index, created if it does not exist yet. + */ + @SuppressWarnings("unchecked") + Node<T> child(final int index) { + final int dimension = region.getDimension(); + if (children == null) { + children = new Node[1 << dimension]; + } + Node<T> child = children[index]; + if (child == null) { + final GeneralEnvelope bounds = new GeneralEnvelope(region); + for (int i = 0; i < dimension; i++) { + final double median = region.getMedian(i); + if ((index & (1 << i)) != 0) { + bounds.setRange(i, median, region.getMaximum(i)); + } else { + bounds.setRange(i, region.getMinimum(i), median); + } + } + child = new Node<>(this, index, bounds); + children[index] = child; + } + return child; + } + } +} diff --git a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/index/OrthtreeTest.java b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/index/OrthtreeTest.java new file mode 100644 index 0000000000..933f646ead --- /dev/null +++ b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/index/OrthtreeTest.java @@ -0,0 +1,120 @@ +/* + * 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.sis.geometries.index; + +import java.util.List; +import java.util.Set; +import org.apache.sis.geometry.GeneralEnvelope; +import org.apache.sis.maths.Vector; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + + +/** + * Tests {@link Orthtree} as a quadtree and as an octree. + * + * @author Johann Sorel (Geomatys) + */ +public class OrthtreeTest { + + private static GeneralEnvelope box(final double... corners) { + final GeneralEnvelope box = new GeneralEnvelope(corners.length / 2); + box.setEnvelope(corners); + return box; + } + + /** + * A quadtree over the square from (0 0) to (16 16) holding a box crossing the center, + * which stays in the root node, and three boxes in the corners. + */ + private static Orthtree<String> quadtree() { + final Orthtree<String> tree = new Orthtree<>(box(0, 0, 16, 16), 4); + assertTrue(tree.insert("a", box( 1, 1, 2, 2))); + assertTrue(tree.insert("b", box( 9, 9, 10, 10))); + assertTrue(tree.insert("c", box( 7, 7, 9, 9))); + assertTrue(tree.insert("d", box(15, 1, 16, 2))); + return tree; + } + + @Test + public void testInsert() { + final Orthtree<String> tree = quadtree(); + assertEquals(4, tree.size()); + assertFalse(tree.insert("e", box(20, 20, 21, 21)), "Outside the region of the tree."); + assertEquals(4, tree.size()); + } + + @Test + public void testIntersecting() { + final Orthtree<String> tree = quadtree(); + assertEquals(List.of("a"), tree.intersecting(box(0, 0, 3, 3))); + assertEquals(Set.of("b", "c"), Set.copyOf(tree.intersecting(box(8, 8, 9.5, 9.5)))); + assertEquals(Set.of("a", "b", "c", "d"), Set.copyOf(tree.intersecting(box(0, 0, 16, 16)))); + } + + @Test + public void testWithin() { + final Orthtree<String> tree = quadtree(); + assertEquals(List.of("a"), tree.within(box(0, 0, 8, 8))); + assertEquals(Set.of("b", "c"), Set.copyOf(tree.within(box(6, 6, 12, 12)))); + } + + /** + * The items crossed by a ray are sorted from the nearest to the farthest. + */ + @Test + public void testRaycast() { + final Orthtree<String> tree = quadtree(); + assertEquals(List.of("a", "d"), tree.raycast(Vector.of(0, 1.5), Vector.of(1, 0))); + assertEquals(List.of("d", "a"), tree.raycast(Vector.of(17, 1.5), Vector.of(-1, 0))); + assertEquals(List.of("a", "c", "b"), tree.raycast(Vector.of(0, 0), Vector.of(1, 1))); + } + + /** + * Removing an item, then moving an item by inserting it again with another box. + */ + @Test + public void testRemove() { + final Orthtree<String> tree = quadtree(); + assertTrue (tree.remove("a")); + assertFalse(tree.remove("a")); + assertEquals(3, tree.size()); + assertTrue(tree.intersecting(box(0, 0, 3, 3)).isEmpty()); + + assertTrue(tree.insert("b", box(1, 1, 2, 2))); + assertEquals(3, tree.size()); + assertEquals(List.of("b"), tree.intersecting(box(0, 0, 3, 3))); + assertTrue(tree.intersecting(box(9.5, 9.5, 10, 10)).isEmpty()); + } + + /** + * An octree over the cube from (0 0 0) to (8 8 8). + */ + @Test + public void testOctree() { + final Orthtree<Integer> tree = new Orthtree<>(box(0, 0, 0, 8, 8, 8)); + assertTrue(tree.insert(1, box(1, 1, 1, 2, 2, 2))); + assertTrue(tree.insert(2, box(5, 1, 1, 6, 2, 2))); + assertTrue(tree.insert(3, box(5, 5, 5, 6, 6, 6))); + assertEquals(List.of(1, 2), tree.raycast(Vector.of(-1, 1.5, 1.5), Vector.of(1, 0, 0))); + assertEquals(List.of(3), tree.intersecting(box(4, 4, 4, 8, 8, 8))); + } +}
