1 package tim.prune.function.srtm;
3 import java.util.ArrayList;
5 import javax.swing.JOptionPane;
8 import tim.prune.DataSubscriber;
9 import tim.prune.GenericFunction;
10 import tim.prune.I18nManager;
11 import tim.prune.UpdateMessageBroker;
12 import tim.prune.data.Altitude;
13 import tim.prune.data.DataPoint;
14 import tim.prune.data.Field;
15 import tim.prune.data.Track;
16 import tim.prune.data.UnitSetLibrary;
17 import tim.prune.gui.ProgressDialog;
18 import tim.prune.undo.UndoLookupSrtm;
21 * Class to provide a lookup function for point altitudes using the Space
22 * Shuttle's SRTM data files. HGT files are downloaded into memory via HTTP and
23 * point altitudes can then be interpolated from the 3m grid data.
25 public class LookupSrtmFunction extends GenericFunction implements Runnable
27 /** Progress dialog */
28 private ProgressDialog _progress = null;
29 /** Track to process */
30 private Track _track = null;
31 /** Flag for whether this is a real track or a terrain one */
32 private boolean _normalTrack = true;
33 /** Flag to check whether this function is currently running or not */
34 private boolean _running = false;
36 /** Altitude below which is considered void */
37 private static final int VOID_VAL = -32768;
41 * @param inApp App object
43 public LookupSrtmFunction(App inApp) {
47 /** @return name key */
48 public String getNameKey() {
49 return "function.lookupsrtm";
53 * Begin the lookup using the normal track
56 begin(_app.getTrackInfo().getTrack(), true);
60 * Begin the lookup with an alternative track
61 * @param inAlternativeTrack
63 public void begin(Track inAlternativeTrack) {
64 begin(inAlternativeTrack, false);
68 * Begin the function with the given parameters
69 * @param inTrack track to process
70 * @param inNormalTrack true if this is a "normal" track, false for an artificially constructed one such as for terrain
72 private void begin(Track inTrack, boolean inNormalTrack)
75 if (! SrtmDiskCache.ensureCacheIsUsable())
77 _app.showErrorMessage(getNameKey(), "error.cache.notthere");
79 if (_progress == null) {
80 _progress = new ProgressDialog(_parentFrame, getNameKey());
84 _normalTrack = inNormalTrack;
85 // start new thread for time-consuming part
86 new Thread(this).start();
90 * Run method using separate thread
94 // Compile list of tiles to get
95 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
96 boolean hasZeroAltitudePoints = false;
97 boolean hasNonZeroAltitudePoints = false;
98 // First, loop to see what kind of points we have
99 for (int i = 0; i < _track.getNumPoints(); i++)
101 if (_track.getPoint(i).hasAltitude())
103 if (_track.getPoint(i).getAltitude().getValue() == 0) {
104 hasZeroAltitudePoints = true;
107 hasNonZeroAltitudePoints = true;
111 // Should we overwrite the zero altitude values?
112 boolean overwriteZeros = hasZeroAltitudePoints && !hasNonZeroAltitudePoints;
113 // If non-zero values present as well, ask user whether to overwrite the zeros or not
114 if (hasNonZeroAltitudePoints && hasZeroAltitudePoints && JOptionPane.showConfirmDialog(_parentFrame,
115 I18nManager.getText("dialog.lookupsrtm.overwritezeros"), I18nManager.getText(getNameKey()),
116 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
118 overwriteZeros = true;
121 // Now loop again to extract the required tiles
122 for (int i = 0; i < _track.getNumPoints(); i++)
124 // Consider points which don't have altitudes or have zero values
125 if (needsAltitude(_track.getPoint(i), overwriteZeros))
127 SrtmTile tile = new SrtmTile(_track.getPoint(i));
128 boolean alreadyGot = false;
129 for (int t = 0; t < tileList.size(); t++)
131 if (tileList.get(t).equals(tile)) {
135 if (!alreadyGot) {tileList.add(tile);}
138 lookupValues(tileList, overwriteZeros);
144 * true if we need to set the altitude of this point
146 private boolean needsAltitude(DataPoint point, boolean overwriteZeros)
148 if (!point.hasAltitude())
152 if (overwriteZeros && point.getAltitude().getValue() == 0)
160 * Lookup the values from SRTM data
161 * @param inTileList list of tiles to get
162 * @param inOverwriteZeros true to overwrite zero altitude values
164 private void lookupValues(ArrayList<SrtmTile> inTileList, boolean inOverwriteZeros)
166 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
167 int numAltitudesFound = 0;
168 // Update progress bar
169 if (_progress != null)
171 _progress.setMaximum(inTileList.size());
172 _progress.setValue(0);
174 String errorMessage = "";
175 for (int t=0; t<inTileList.size() && !_progress.isCancelled(); t++)
177 SrtmTile tile = inTileList.get(t);
178 SrtmSource srtmSource = tile.findBestCachedSource();
180 if (srtmSource == null)
182 errorMessage += "Tile "+tile.getTileName()+" not in cache!\n";
187 _progress.setValue(t);
191 heights = srtmSource.getTileHeights(tile);
193 catch (SrtmSourceException e)
195 errorMessage += e.getMessage();
199 int rowSize = srtmSource.getRowSize(tile);
202 errorMessage += "Tile "+tile.getTileName()+" is corrupted";
205 // Loop over all points in track, try to apply altitude from array
206 for (int p = 0; p < _track.getNumPoints(); p++)
208 DataPoint point = _track.getPoint(p);
209 if (needsAltitude(point, inOverwriteZeros))
211 if (new SrtmTile(point).equals(tile))
213 double x = (point.getLongitude().getDouble() - tile.getLongitude()) * (rowSize - 1);
214 double y = rowSize - (point.getLatitude().getDouble() - tile.getLatitude()) * (rowSize - 1);
215 int idx1 = ((int)y)*rowSize + (int)x;
218 int[] fouralts = {heights[idx1], heights[idx1+1], heights[idx1-rowSize], heights[idx1-rowSize+1]};
219 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
220 + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
221 // if (numVoids > 0) System.out.println(numVoids + " voids found");
222 double altitude = 0.0;
225 case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
226 case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
228 case 3: altitude = averageNonVoid(fouralts); break;
229 default: altitude = VOID_VAL;
231 // Special case for terrain tracks, don't interpolate voids yet
232 if (!_normalTrack && numVoids > 0) {
235 if (altitude != VOID_VAL)
237 point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
238 // depending on settings, this value may have been added as feet, we need to force metres
239 point.getAltitude().reset(new Altitude((int)altitude, UnitSetLibrary.UNITS_METRES));
243 catch (ArrayIndexOutOfBoundsException obe) {
244 errorMessage += "Point not in tile? lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1+"\n";
252 if (_progress.isCancelled()) {
256 if (! errorMessage.equals("")) {
257 _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
260 if (numAltitudesFound > 0)
262 // Inform app including undo information
263 _track.requestRescale();
264 UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
265 // Don't update app if we're doing another track
268 _app.completeFunction(undo,
269 I18nManager.getTextWithNumber("confirm.lookupsrtm", numAltitudesFound));
272 else if (inTileList.size() > 0) {
273 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
276 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
281 * Perform a bilinear interpolation on the given altitude array
282 * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
283 * @param inX x coordinate
284 * @param inY y coordinate
285 * @return interpolated altitude
287 private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
289 double alpha = inX - (int) inX;
290 double beta = 1 - (inY - (int) inY);
291 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
292 + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
297 * Fix a single void in the given array by replacing it with the average of the others
298 * @param inAltitudes array of altitudes containing one void
299 * @return fixed array without voids
301 private static int[] fixVoid(int[] inAltitudes)
303 int[] fixed = new int[inAltitudes.length];
304 for (int i = 0; i < inAltitudes.length; i++)
306 if (inAltitudes[i] == VOID_VAL) {
307 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
310 fixed[i] = inAltitudes[i];
317 * Calculate the average of the non-void altitudes in the given array
318 * @param inAltitudes array of altitudes with one or more voids
319 * @return average of non-void altitudes
321 private static final double averageNonVoid(int[] inAltitudes)
323 double totalAltitude = 0.0;
325 for (int i = 0; i < inAltitudes.length; i++)
327 if (inAltitudes[i] != VOID_VAL)
329 totalAltitude += inAltitudes[i];
333 if (numAlts < 1) {return VOID_VAL;}
334 return totalAltitude / numAlts;
338 * @return true if a thread is currently running
340 public boolean isRunning()