1 package tim.prune.function.srtm;
4 import java.io.FileInputStream;
5 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.zip.ZipEntry;
9 import java.util.zip.ZipInputStream;
11 import javax.swing.JOptionPane;
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;
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.
33 public class LookupSrtmFunction extends GenericFunction implements Runnable
35 /** Whether to overwrite all altitudes, or only fill in missing data */
36 private boolean _overwriteAlt = false;
37 /** Progress dialog */
38 private ProgressDialog _progress = null;
39 /** Track to process */
40 private Track _track = null;
41 /** Flag for whether this is a real track or a terrain one */
42 private boolean _normalTrack = true;
43 /** Flag set when any tiles had to be downloaded (rather than just loaded locally) */
44 private boolean _hadToDownload = false;
45 /** Flag to check whether this function is currently running or not */
46 private boolean _running = false;
48 /** Expected size of hgt file in bytes */
49 private static final int HGT_ROW = 3601;
50 private static final int HGT_SIZE = 2 * HGT_ROW * HGT_ROW;
51 /** Altitude below which is considered void */
52 private static final int VOID_VAL = -32768;
56 * @param inApp App object
58 public LookupSrtmFunction(App inApp, boolean overwriteAlt) {
60 _overwriteAlt = overwriteAlt;
63 /** @return name key */
64 public String getNameKey() {
66 return "function.overwritesrtm";
68 return "function.lookupsrtm";
73 * Begin the lookup using the normal track
76 begin(_app.getTrackInfo().getTrack(), true);
80 * Begin the lookup with an alternative track
81 * @param inAlternativeTrack
83 public void begin(Track inAlternativeTrack) {
84 begin(inAlternativeTrack, false);
88 * Begin the function with the given parameters
89 * @param inTrack track to process
90 * @param inNormalTrack true if this is a "normal" track, false for an artificially constructed one such as for terrain
92 private void begin(Track inTrack, boolean inNormalTrack)
95 _hadToDownload = false;
96 if (_progress == null) {
97 _progress = new ProgressDialog(_parentFrame, getNameKey());
101 _normalTrack = inNormalTrack;
102 // start new thread for time-consuming part
103 new Thread(this).start();
107 * Run method using separate thread
111 // Compile list of tiles to get
112 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
114 boolean overwriteZeros = overwriteZeros();
116 // Now loop again to extract the required tiles
117 for (int i = 0; i < _track.getNumPoints(); i++)
119 // Consider points which don't have altitudes or have zero values
120 if (needsAltitude(_track.getPoint(i), overwriteZeros))
122 SrtmTile tile = new SrtmTile(_track.getPoint(i));
123 boolean alreadyGot = false;
124 for (int t = 0; t < tileList.size(); t++)
126 if (tileList.get(t).equals(tile)) {
130 if (!alreadyGot) {tileList.add(tile);}
133 lookupValues(tileList, overwriteZeros);
136 // Show tip if lots of online lookups were necessary
137 if (_hadToDownload) {
138 _app.showTip(TipManager.Tip_DownloadSrtm);
143 * true if we need to set the altitude of this point
145 private boolean needsAltitude(DataPoint point, boolean overwriteZeros)
151 if (!point.hasAltitude())
155 if (overwriteZeros && point.getAltitude().getValue() == 0)
162 private boolean overwriteZeros()
164 // nothing to do if we overwrite all altitudes anyway
169 boolean hasZeroAltitudePoints = false;
170 boolean hasNonZeroAltitudePoints = false;
171 // First, loop to see what kind of points we have
172 for (int i = 0; i < _track.getNumPoints(); i++)
174 if (_track.getPoint(i).hasAltitude())
176 if (_track.getPoint(i).getAltitude().getValue() == 0) {
177 hasZeroAltitudePoints = true;
180 hasNonZeroAltitudePoints = true;
184 // Should we overwrite the zero altitude values?
185 boolean overwriteZeros = hasZeroAltitudePoints && !hasNonZeroAltitudePoints;
186 // If non-zero values present as well, ask user whether to overwrite the zeros or not
187 if (hasNonZeroAltitudePoints && hasZeroAltitudePoints && JOptionPane.showConfirmDialog(_parentFrame,
188 I18nManager.getText("dialog.lookupsrtm.overwritezeros"), I18nManager.getText(getNameKey()),
189 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
191 overwriteZeros = true;
193 return overwriteZeros;
198 * Lookup the values from SRTM data
199 * @param inTileList list of tiles to get
200 * @param inOverwriteZeros true to overwrite zero altitude values
202 private void lookupValues(ArrayList<SrtmTile> inTileList, boolean overwriteZeros)
204 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo(), _overwriteAlt);
205 int numAltitudesFound = 0;
206 // Update progress bar
207 if (_progress != null)
209 _progress.setMaximum(inTileList.size());
210 _progress.setValue(0);
212 String errorMessage = null;
213 // Get urls for each tile
214 URL[] urls = TileFinder.getUrls(inTileList);
215 for (int t=0; t<inTileList.size() && !_progress.isCancelled(); t++)
219 SrtmTile tile = inTileList.get(t);
223 _progress.setValue(t);
224 final int ARRLENGTH = HGT_ROW * HGT_ROW;
225 int[] heights = new int[ARRLENGTH];
226 // Open zipinputstream on url and check size
227 ZipInputStream inStream = getStreamToHgtFile(urls[t]);
228 boolean entryOk = false;
229 if (inStream != null)
231 ZipEntry entry = inStream.getNextEntry();
232 entryOk = (entry != null && entry.getSize() == HGT_SIZE);
235 // Read entire file contents into one byte array
236 for (int i = 0; i < ARRLENGTH; i++)
238 heights[i] = inStream.read() * 256 + inStream.read();
239 if (heights[i] >= 32768) {heights[i] -= 65536;}
243 // System.out.println("length not ok: " + entry.getSize());
245 // Close stream from url
251 // Loop over all points in track, try to apply altitude from array
252 for (int p = 0; p < _track.getNumPoints(); p++)
254 DataPoint point = _track.getPoint(p);
255 if (needsAltitude(point, overwriteZeros))
257 if (new SrtmTile(point).equals(tile))
259 double x = (point.getLongitude().getDouble() - tile.getLongitude()) * (HGT_ROW - 1);
260 double y = HGT_ROW - (point.getLatitude().getDouble() - tile.getLatitude()) * (HGT_ROW - 1);
261 int idx1 = ((int)y)*HGT_ROW + (int)x;
264 int[] fouralts = {heights[idx1], heights[idx1+1], heights[idx1-HGT_ROW], heights[idx1-HGT_ROW+1]};
265 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
266 + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
267 // if (numVoids > 0) System.out.println(numVoids + " voids found");
268 double altitude = 0.0;
271 case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
272 case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
274 case 3: altitude = averageNonVoid(fouralts); break;
275 default: altitude = VOID_VAL;
277 // Special case for terrain tracks, don't interpolate voids yet
278 if (!_normalTrack && numVoids > 0) {
281 if (altitude != VOID_VAL)
283 point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
284 // depending on settings, this value may have been added as feet, we need to force metres
285 point.getAltitude().reset(new Altitude((int)altitude, UnitSetLibrary.UNITS_METRES));
289 catch (ArrayIndexOutOfBoundsException obe) {
290 // System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
297 catch (IOException ioe) {errorMessage = ioe.getClass().getName() + " - " + ioe.getMessage();
303 if (_progress.isCancelled()) {
307 if (numAltitudesFound > 0)
309 // Inform app including undo information
310 _track.requestRescale();
311 UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
312 // Don't update app if we're doing another track
315 _app.completeFunction(undo,
316 I18nManager.getTextWithNumber("confirm.lookupsrtm", numAltitudesFound));
319 else if (errorMessage != null) {
320 _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
322 else if (inTileList.size() > 0) {
323 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
326 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
331 * See whether the SRTM file is already available locally first, then try online
332 * @param inUrl URL for online resource
333 * @return ZipInputStream either on the local file or on the downloaded zip file
335 private ZipInputStream getStreamToHgtFile(URL inUrl)
338 String diskCachePath = Config.getConfigString(Config.KEY_DISK_CACHE);
339 if (diskCachePath != null)
341 File srtmDir = new File(diskCachePath, "srtm");
342 if (srtmDir.exists() && srtmDir.isDirectory() && srtmDir.canRead())
344 File srtmFile = new File(srtmDir, new File(inUrl.getFile()).getName());
345 if (srtmFile.exists() && srtmFile.isFile() && srtmFile.canRead()
346 && srtmFile.length() > 400)
348 // System.out.println("Lookup: Using file " + srtmFile.getAbsolutePath());
349 // File found, use this one
350 return new ZipInputStream(new FileInputStream(srtmFile));
354 // System.out.println("Lookup: Trying online: " + inUrl.toString());
355 _hadToDownload = true;
356 // MAYBE: Only download if we're in online mode?
357 // return new ZipInputStream(inUrl.openStream());
362 * Perform a bilinear interpolation on the given altitude array
363 * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
364 * @param inX x coordinate
365 * @param inY y coordinate
366 * @return interpolated altitude
368 private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
370 double alpha = inX - (int) inX;
371 double beta = 1 - (inY - (int) inY);
372 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
373 + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
378 * Fix a single void in the given array by replacing it with the average of the others
379 * @param inAltitudes array of altitudes containing one void
380 * @return fixed array without voids
382 private static int[] fixVoid(int[] inAltitudes)
384 int[] fixed = new int[inAltitudes.length];
385 for (int i = 0; i < inAltitudes.length; i++)
387 if (inAltitudes[i] == VOID_VAL) {
388 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
391 fixed[i] = inAltitudes[i];
398 * Calculate the average of the non-void altitudes in the given array
399 * @param inAltitudes array of altitudes with one or more voids
400 * @return average of non-void altitudes
402 private static final double averageNonVoid(int[] inAltitudes)
404 double totalAltitude = 0.0;
406 for (int i = 0; i < inAltitudes.length; i++)
408 if (inAltitudes[i] != VOID_VAL)
410 totalAltitude += inAltitudes[i];
414 if (numAlts < 1) {return VOID_VAL;}
415 return totalAltitude / numAlts;
419 * @return true if a thread is currently running
421 public boolean isRunning()