]> gitweb.fperrin.net Git - GpsPrune.git/blob - src/tim/prune/function/srtm/LookupSrtmFunction.java
Use SRTM 1deg data from NASA servers
[GpsPrune.git] / src / tim / prune / function / srtm / LookupSrtmFunction.java
1 package tim.prune.function.srtm;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.net.URL;
7 import java.util.ArrayList;
8 import java.util.zip.ZipEntry;
9 import java.util.zip.ZipInputStream;
10
11 import javax.swing.JOptionPane;
12
13 import tim.prune.App;
14 import tim.prune.DataSubscriber;
15 import tim.prune.GenericFunction;
16 import tim.prune.I18nManager;
17 import tim.prune.UpdateMessageBroker;
18 import tim.prune.config.Config;
19 import tim.prune.data.Altitude;
20 import tim.prune.data.DataPoint;
21 import tim.prune.data.Field;
22 import tim.prune.data.Track;
23 import tim.prune.data.UnitSetLibrary;
24 import tim.prune.gui.ProgressDialog;
25 import tim.prune.tips.TipManager;
26 import tim.prune.undo.UndoLookupSrtm;
27
28 /**
29  * Class to provide a lookup function for point altitudes using the Space
30  * Shuttle's SRTM data files. HGT files are downloaded into memory via HTTP and
31  * point altitudes can then be interpolated from the 3m grid data.
32  */
33 public class LookupSrtmFunction extends GenericFunction implements Runnable
34 {
35         /** Progress dialog */
36         private ProgressDialog _progress = null;
37         /** Track to process */
38         private Track _track = null;
39         /** Flag for whether this is a real track or a terrain one */
40         private boolean _normalTrack = true;
41         /** Flag set when any tiles had to be downloaded (rather than just loaded locally) */
42         private boolean _hadToDownload = false;
43         /** Flag to check whether this function is currently running or not */
44         private boolean _running = false;
45
46         /** Expected size of hgt file in bytes */
47         private static final int HGT_ROW = 3601;
48         private static final int HGT_SIZE = 2 * HGT_ROW * HGT_ROW;
49         /** Altitude below which is considered void */
50         private static final int VOID_VAL = -32768;
51
52         /**
53          * Constructor
54          * @param inApp  App object
55          */
56         public LookupSrtmFunction(App inApp) {
57                 super(inApp);
58         }
59
60         /** @return name key */
61         public String getNameKey() {
62                 return "function.lookupsrtm";
63         }
64
65         /**
66          * Begin the lookup using the normal track
67          */
68         public void begin() {
69                 begin(_app.getTrackInfo().getTrack(), true);
70         }
71
72         /**
73          * Begin the lookup with an alternative track
74          * @param inAlternativeTrack
75          */
76         public void begin(Track inAlternativeTrack) {
77                 begin(inAlternativeTrack, false);
78         }
79
80         /**
81          * Begin the function with the given parameters
82          * @param inTrack track to process
83          * @param inNormalTrack true if this is a "normal" track, false for an artificially constructed one such as for terrain
84          */
85         private void begin(Track inTrack, boolean inNormalTrack)
86         {
87                 _running = true;
88                 _hadToDownload = false;
89                 if (_progress == null) {
90                         _progress = new ProgressDialog(_parentFrame, getNameKey());
91                 }
92                 _progress.show();
93                 _track = inTrack;
94                 _normalTrack = inNormalTrack;
95                 // start new thread for time-consuming part
96                 new Thread(this).start();
97         }
98
99         /**
100          * Run method using separate thread
101          */
102         public void run()
103         {
104                 // Compile list of tiles to get
105                 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
106                 boolean hasZeroAltitudePoints = false;
107                 boolean hasNonZeroAltitudePoints = false;
108                 // First, loop to see what kind of points we have
109                 for (int i = 0; i < _track.getNumPoints(); i++)
110                 {
111                         if (_track.getPoint(i).hasAltitude())
112                         {
113                                 if (_track.getPoint(i).getAltitude().getValue() == 0) {
114                                         hasZeroAltitudePoints = true;
115                                 }
116                                 else {
117                                         hasNonZeroAltitudePoints = true;
118                                 }
119                         }
120                 }
121                 // Should we overwrite the zero altitude values?
122                 boolean overwriteZeros = hasZeroAltitudePoints && !hasNonZeroAltitudePoints;
123                 // If non-zero values present as well, ask user whether to overwrite the zeros or not
124                 if (hasNonZeroAltitudePoints && hasZeroAltitudePoints && JOptionPane.showConfirmDialog(_parentFrame,
125                         I18nManager.getText("dialog.lookupsrtm.overwritezeros"), I18nManager.getText(getNameKey()),
126                         JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
127                 {
128                         overwriteZeros = true;
129                 }
130
131                 // Now loop again to extract the required tiles
132                 for (int i = 0; i < _track.getNumPoints(); i++)
133                 {
134                         // Consider points which don't have altitudes or have zero values
135                         if (!_track.getPoint(i).hasAltitude()
136                                 || (overwriteZeros && _track.getPoint(i).getAltitude().getValue() == 0))
137                         {
138                                 SrtmTile tile = new SrtmTile(_track.getPoint(i));
139                                 boolean alreadyGot = false;
140                                 for (int t = 0; t < tileList.size(); t++)
141                                 {
142                                         if (tileList.get(t).equals(tile)) {
143                                                 alreadyGot = true;
144                                         }
145                                 }
146                                 if (!alreadyGot) {tileList.add(tile);}
147                         }
148                 }
149                 lookupValues(tileList, overwriteZeros);
150                 // Finished
151                 _running = false;
152                 // Show tip if lots of online lookups were necessary
153                 if (_hadToDownload) {
154                         _app.showTip(TipManager.Tip_DownloadSrtm);
155                 }
156         }
157
158
159         /**
160          * Lookup the values from SRTM data
161          * @param inTileList list of tiles to get
162          * @param inOverwriteZeros true to overwrite zero altitude values
163          */
164         private void lookupValues(ArrayList<SrtmTile> inTileList, boolean inOverwriteZeros)
165         {
166                 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
167                 int numAltitudesFound = 0;
168                 // Update progress bar
169                 if (_progress != null)
170                 {
171                         _progress.setMaximum(inTileList.size());
172                         _progress.setValue(0);
173                 }
174                 String errorMessage = null;
175                 // Get urls for each tile
176                 URL[] urls = TileFinder.getUrls(inTileList);
177                 for (int t=0; t<inTileList.size() && !_progress.isCancelled(); t++)
178                 {
179                         if (urls[t] != null)
180                         {
181                                 SrtmTile tile = inTileList.get(t);
182                                 try
183                                 {
184                                         // Set progress
185                                         _progress.setValue(t);
186                                         final int ARRLENGTH = HGT_ROW * HGT_ROW;
187                                         int[] heights = new int[ARRLENGTH];
188                                         // Open zipinputstream on url and check size
189                                         ZipInputStream inStream = getStreamToHgtFile(urls[t]);
190                                         boolean entryOk = false;
191                                         if (inStream != null)
192                                         {
193                                                 ZipEntry entry = inStream.getNextEntry();
194                                                 entryOk = (entry != null && entry.getSize() == HGT_SIZE);
195                                                 if (entryOk)
196                                                 {
197                                                         // Read entire file contents into one byte array
198                                                         for (int i = 0; i < ARRLENGTH; i++)
199                                                         {
200                                                                 heights[i] = inStream.read() * 256 + inStream.read();
201                                                                 if (heights[i] >= 32768) {heights[i] -= 65536;}
202                                                         }
203                                                 }
204                                                 // else {
205                                                 //      System.out.println("length not ok: " + entry.getSize());
206                                                 // }
207                                                 // Close stream from url
208                                                 inStream.close();
209                                         }
210
211                                         if (entryOk)
212                                         {
213                                                 // Loop over all points in track, try to apply altitude from array
214                                                 for (int p = 0; p < _track.getNumPoints(); p++)
215                                                 {
216                                                         DataPoint point = _track.getPoint(p);
217                                                         if (!point.hasAltitude()
218                                                                 || (inOverwriteZeros && point.getAltitude().getValue() == 0))
219                                                         {
220                                                                 if (new SrtmTile(point).equals(tile))
221                                                                 {
222                                                                         double x = (point.getLongitude().getDouble() - tile.getLongitude()) * (HGT_ROW - 1);
223                                                                         double y = HGT_ROW - (point.getLatitude().getDouble() - tile.getLatitude()) * (HGT_ROW - 1);
224                                                                         int idx1 = ((int)y)*HGT_ROW + (int)x;
225                                                                         try
226                                                                         {
227                                                                                 int[] fouralts = {heights[idx1], heights[idx1+1], heights[idx1-HGT_ROW], heights[idx1-HGT_ROW+1]};
228                                                                                 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
229                                                                                         + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
230                                                                                 // if (numVoids > 0) System.out.println(numVoids + " voids found");
231                                                                                 double altitude = 0.0;
232                                                                                 switch (numVoids)
233                                                                                 {
234                                                                                         case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
235                                                                                         case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
236                                                                                         case 2:
237                                                                                         case 3: altitude = averageNonVoid(fouralts); break;
238                                                                                         default: altitude = VOID_VAL;
239                                                                                 }
240                                                                                 // Special case for terrain tracks, don't interpolate voids yet
241                                                                                 if (!_normalTrack && numVoids > 0) {
242                                                                                         altitude = VOID_VAL;
243                                                                                 }
244                                                                                 if (altitude != VOID_VAL)
245                                                                                 {
246                                                                                         point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
247                                                                                         // depending on settings, this value may have been added as feet, we need to force metres
248                                                                                         point.getAltitude().reset(new Altitude((int)altitude, UnitSetLibrary.UNITS_METRES));
249                                                                                         numAltitudesFound++;
250                                                                                 }
251                                                                         }
252                                                                         catch (ArrayIndexOutOfBoundsException obe) {
253                                                                                 // System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
254                                                                         }
255                                                                 }
256                                                         }
257                                                 }
258                                         }
259                                 }
260                                 catch (IOException ioe) {errorMessage = ioe.getClass().getName() + " - " + ioe.getMessage();
261                                 }
262                         }
263                 }
264
265                 _progress.dispose();
266                 if (_progress.isCancelled()) {
267                         return;
268                 }
269
270                 if (numAltitudesFound > 0)
271                 {
272                         // Inform app including undo information
273                         _track.requestRescale();
274                         UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
275                         // Don't update app if we're doing another track
276                         if (_normalTrack)
277                         {
278                                 _app.completeFunction(undo,
279                                         I18nManager.getTextWithNumber("confirm.lookupsrtm", numAltitudesFound));
280                         }
281                 }
282                 else if (errorMessage != null) {
283                         _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
284                 }
285                 else if (inTileList.size() > 0) {
286                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
287                 }
288                 else {
289                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
290                 }
291         }
292
293         /**
294          * See whether the SRTM file is already available locally first, then try online
295          * @param inUrl URL for online resource
296          * @return ZipInputStream either on the local file or on the downloaded zip file
297          */
298         private ZipInputStream getStreamToHgtFile(URL inUrl)
299         throws IOException
300         {
301                 String diskCachePath = Config.getConfigString(Config.KEY_DISK_CACHE);
302                 if (diskCachePath != null)
303                 {
304                         File srtmDir = new File(diskCachePath, "srtm");
305                         if (srtmDir.exists() && srtmDir.isDirectory() && srtmDir.canRead())
306                         {
307                                 File srtmFile = new File(srtmDir, new File(inUrl.getFile()).getName());
308                                 if (srtmFile.exists() && srtmFile.isFile() && srtmFile.canRead()
309                                         && srtmFile.length() > 400)
310                                 {
311                                         // System.out.println("Lookup: Using file " + srtmFile.getAbsolutePath());
312                                         // File found, use this one
313                                         return new ZipInputStream(new FileInputStream(srtmFile));
314                                 }
315                         }
316                 }
317                 // System.out.println("Lookup: Trying online: " + inUrl.toString());
318                 _hadToDownload = true;
319                 // MAYBE: Only download if we're in online mode?
320                 // return new ZipInputStream(inUrl.openStream());
321                 return null;
322         }
323
324         /**
325          * Perform a bilinear interpolation on the given altitude array
326          * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
327          * @param inX x coordinate
328          * @param inY y coordinate
329          * @return interpolated altitude
330          */
331         private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
332         {
333                 double alpha = inX - (int) inX;
334                 double beta  = 1 - (inY - (int) inY);
335                 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
336                         + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
337                 return alt;
338         }
339
340         /**
341          * Fix a single void in the given array by replacing it with the average of the others
342          * @param inAltitudes array of altitudes containing one void
343          * @return fixed array without voids
344          */
345         private static int[] fixVoid(int[] inAltitudes)
346         {
347                 int[] fixed = new int[inAltitudes.length];
348                 for (int i = 0; i < inAltitudes.length; i++)
349                 {
350                         if (inAltitudes[i] == VOID_VAL) {
351                                 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
352                         }
353                         else {
354                                 fixed[i] = inAltitudes[i];
355                         }
356                 }
357                 return fixed;
358         }
359
360         /**
361          * Calculate the average of the non-void altitudes in the given array
362          * @param inAltitudes array of altitudes with one or more voids
363          * @return average of non-void altitudes
364          */
365         private static final double averageNonVoid(int[] inAltitudes)
366         {
367                 double totalAltitude = 0.0;
368                 int numAlts = 0;
369                 for (int i = 0; i < inAltitudes.length; i++)
370                 {
371                         if (inAltitudes[i] != VOID_VAL)
372                         {
373                                 totalAltitude += inAltitudes[i];
374                                 numAlts++;
375                         }
376                 }
377                 if (numAlts < 1) {return VOID_VAL;}
378                 return totalAltitude / numAlts;
379         }
380
381         /**
382          * @return true if a thread is currently running
383          */
384         public boolean isRunning()
385         {
386                 return _running;
387         }
388 }