Class LineSegmentIndex

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12  
13 package org.locationtech.jts.simplify;
14  
15 import java.util.ArrayList;
16 import java.util.List;
17  
18 import org.locationtech.jts.geom.Envelope;
19 import org.locationtech.jts.geom.LineSegment;
20 import org.locationtech.jts.index.ItemVisitor;
21 import org.locationtech.jts.index.quadtree.Quadtree;
22  
23 /**
24  * An spatial index on a set of {@link LineSegment}s.
25  * Supports adding and removing items.
26  *
27  * @author Martin Davis
28  */
29 class LineSegmentIndex
30 {
31   private Quadtree index = new Quadtree();
32  
33   public LineSegmentIndex()
34   {
35   }
36  
37   public void add(TaggedLineString line) {
38     TaggedLineSegment[] segs = line.getSegments();
39     for (int i = 0; i < segs.length; i++) {
40       TaggedLineSegment seg = segs[i];
41       add(seg);
42     }
43   }
44  
45   public void add(LineSegment seg)
46   {
47     index.insert(new Envelope(seg.p0, seg.p1), seg);
48   }
49  
50   public void remove(LineSegment seg)
51   {
52     index.remove(new Envelope(seg.p0, seg.p1), seg);
53   }
54  
55   public List query(LineSegment querySeg)
56   {
57     Envelope env = new Envelope(querySeg.p0, querySeg.p1);
58  
59     LineSegmentVisitor visitor = new LineSegmentVisitor(querySeg);
60     index.query(env, visitor);
61     List itemsFound = visitor.getItems();
62  
63 //    List listQueryItems = index.query(env);
64 //    System.out.println("visitor size = " + itemsFound.size()
65 //                       + "  query size = " + listQueryItems.size());
66 //    List itemsFound = index.query(env);
67  
68     return itemsFound;
69   }
70 }
71  
72 /**
73  * ItemVisitor subclass to reduce volume of query results.
74  */
75 class LineSegmentVisitor
76     implements ItemVisitor
77 {
78 // MD - only seems to make about a 10% difference in overall time.
79  
80   private LineSegment querySeg;
81   private ArrayList items = new ArrayList();
82  
83   public LineSegmentVisitor(LineSegment querySeg) {
84     this.querySeg = querySeg;
85   }
86  
87   public void visitItem(Object item)
88   {
89     LineSegment seg = (LineSegment) item;
90     if (Envelope.intersects(seg.p0, seg.p1, querySeg.p0, querySeg.p1))
91       items.add(item);
92   }
93  
94   public ArrayList getItems() { return items; }
95 }
96