]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.maps.elevation.server/src/org/simantics/maps/elevation/server/TiffTileInterface.java
Fix elevation bounding box profile shift & elevation transform fixes
[simantics/district.git] / org.simantics.maps.elevation.server / src / org / simantics / maps / elevation / server / TiffTileInterface.java
1 package org.simantics.maps.elevation.server;
2
3 import java.awt.geom.Rectangle2D;
4 import java.io.IOException;
5 import java.nio.file.Files;
6 import java.nio.file.Path;
7 import java.util.Collection;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.concurrent.ConcurrentHashMap;
11 import java.util.concurrent.atomic.AtomicInteger;
12 import java.util.stream.Collectors;
13 import java.util.stream.Stream;
14
15 import org.geotools.geometry.DirectPosition2D;
16 import org.geotools.geometry.Envelope2D;
17 import org.geotools.geometry.jts.ReferencedEnvelope;
18 import org.geotools.referencing.CRS;
19 import org.opengis.geometry.DirectPosition;
20 import org.opengis.referencing.crs.CoordinateReferenceSystem;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import com.github.benmanes.caffeine.cache.Caffeine;
25 import com.github.benmanes.caffeine.cache.LoadingCache;
26 import com.vividsolutions.jts.geom.Coordinate;
27 import com.vividsolutions.jts.geom.Envelope;
28 import com.vividsolutions.jts.index.strtree.STRtree;
29
30 public class TiffTileInterface {
31
32     private static final Logger LOGGER = LoggerFactory.getLogger(TiffTileInterface.class);
33
34     private Path tilesFolder;
35     private LoadingCache<Path, TiffInterface> interfaceCache;
36     private int openInterfacesSize;
37     private STRtree index;
38
39     public TiffTileInterface(Path tilesFolder) {
40         this(tilesFolder, 5);
41     }
42
43     public TiffTileInterface(Path tilesFolder, int openInterfacesSize) {
44         if (!Files.isDirectory(tilesFolder)) {
45             throw new IllegalArgumentException("tilesFolder has to be a folder: " + tilesFolder.toAbsolutePath());
46         }
47         this.tilesFolder = tilesFolder;
48         this.index = new STRtree();
49         this.openInterfacesSize = openInterfacesSize;
50
51         this.interfaceCache = Caffeine.newBuilder()
52             .maximumSize(this.openInterfacesSize)
53             .removalListener((key, gdalInterface, cause) -> ((TiffInterface) gdalInterface).close())
54             .build(key -> new TiffInterface(key));
55         
56         try {
57             initializeIndex();
58         } catch (IOException e) {
59             LOGGER.error("Could not initialize index for folder {}", tilesFolder, e);
60         }
61     }
62
63     private TiffInterface openTifInterface(Path tifFile) {
64         return interfaceCache.get(tifFile);
65     }
66
67     private Stream<Path> allTiffFiles() throws IOException {
68         return Files.walk(tilesFolder).filter(Files::isRegularFile).filter(tif -> tif.getFileName().toString().endsWith(".tif"));
69     }
70
71     public void initializeIndex() throws IOException {
72         LOGGER.info("Initializing index..");
73         AtomicInteger counter = new AtomicInteger();
74         allTiffFiles().parallel().forEach(tifFile -> {
75             TiffInterface tifInterface = openTifInterface(tifFile);
76             Envelope2D coords = tifInterface.getCornerCoords();
77             try {
78                 ReferencedEnvelope refEnv = new ReferencedEnvelope(coords);
79                 ReferencedEnvelope targetEnv = refEnv.transform(c4326, false, 30);
80
81                 synchronized(index) {
82                     index.insert(targetEnv, tifFile);
83                 }
84                 envelopes.put(tifFile, targetEnv);
85             } catch (Exception e) {
86                 LOGGER.error("Could not initialize index for file {}", tifFile, e);
87             } finally {
88                 tifInterface.close();
89                 int current = counter.getAndIncrement();
90                 if (current % 100 == 0) {
91                     LOGGER.info("    {}", current);
92                 }
93             }
94         });
95     }
96
97     private Map<Path, Envelope> envelopes = new ConcurrentHashMap<>();
98
99     public Collection<Rectangle2D> getBoundingBoxes() {
100         Collection<Rectangle2D> rects = envelopes.values().stream().map(env -> {
101             double x = env.getMinX();
102             double y = env.getMinY();
103             return new Rectangle2D.Double(x, y, env.getMaxX() - x, env.getMaxY() - y);
104         }).collect(Collectors.toList());
105         return rects;
106     }
107
108     private static CoordinateReferenceSystem c4326;
109
110     static {
111         try {
112             c4326 = CRS.decode("EPSG:4326");
113         } catch (Exception e) {
114             LOGGER.error("Could not initialize epsg:4326", e);
115         }
116     }
117
118     public Number lookup(double x, double y) {
119         LOGGER.info("Looking up x={} y={}", x, y);
120         DirectPosition p = new DirectPosition2D(c4326, x, y);
121         List<Path> tifFiles = (List<Path>) index.query(new Envelope(new Coordinate(x, y)));
122         for (Path tifFile : tifFiles) {
123             TiffInterface tifInterface = openTifInterface(tifFile);
124             if (tifInterface.contains(p)) {
125                 try {
126                     return tifInterface.lookup(p);
127                 } finally {
128                     tifInterface.close();
129                 }
130             } else {
131                 System.out.println("not found");
132             }
133         }
134         return new Double(0); // use 0 by default for now
135     }
136 }