]> 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.util.ArrayList;
4
5 import javax.swing.JOptionPane;
6
7 import tim.prune.App;
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;
19
20 /**
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.
24  */
25 public class LookupSrtmFunction extends GenericFunction implements Runnable
26 {
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;
35
36         /** Altitude below which is considered void */
37         private static final int VOID_VAL = -32768;
38
39         /**
40          * Constructor
41          * @param inApp  App object
42          */
43         public LookupSrtmFunction(App inApp) {
44                 super(inApp);
45         }
46
47         /** @return name key */
48         public String getNameKey() {
49                 return "function.lookupsrtm";
50         }
51
52         /**
53          * Begin the lookup using the normal track
54          */
55         public void begin() {
56                 begin(_app.getTrackInfo().getTrack(), true);
57         }
58
59         /**
60          * Begin the lookup with an alternative track
61          * @param inAlternativeTrack
62          */
63         public void begin(Track inAlternativeTrack) {
64                 begin(inAlternativeTrack, false);
65         }
66
67         /**
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
71          */
72         private void begin(Track inTrack, boolean inNormalTrack)
73         {
74                 _running = true;
75                 if (! SrtmDiskCache.ensureCacheIsUsable())
76                 {
77                         _app.showErrorMessage(getNameKey(), "error.cache.notthere");
78                 }
79                 if (_progress == null) {
80                         _progress = new ProgressDialog(_parentFrame, getNameKey());
81                 }
82                 _progress.show();
83                 _track = inTrack;
84                 _normalTrack = inNormalTrack;
85                 // start new thread for time-consuming part
86                 new Thread(this).start();
87         }
88
89         /**
90          * Run method using separate thread
91          */
92         public void run()
93         {
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++)
100                 {
101                         if (_track.getPoint(i).hasAltitude())
102                         {
103                                 if (_track.getPoint(i).getAltitude().getValue() == 0) {
104                                         hasZeroAltitudePoints = true;
105                                 }
106                                 else {
107                                         hasNonZeroAltitudePoints = true;
108                                 }
109                         }
110                 }
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)
117                 {
118                         overwriteZeros = true;
119                 }
120
121                 // Now loop again to extract the required tiles
122                 for (int i = 0; i < _track.getNumPoints(); i++)
123                 {
124                         // Consider points which don't have altitudes or have zero values
125                         if (needsAltitude(_track.getPoint(i), overwriteZeros))
126                         {
127                                 SrtmTile tile = new SrtmTile(_track.getPoint(i));
128                                 boolean alreadyGot = false;
129                                 for (int t = 0; t < tileList.size(); t++)
130                                 {
131                                         if (tileList.get(t).equals(tile)) {
132                                                 alreadyGot = true;
133                                         }
134                                 }
135                                 if (!alreadyGot) {tileList.add(tile);}
136                         }
137                 }
138                 lookupValues(tileList, overwriteZeros);
139                 // Finished
140                 _running = false;
141         }
142
143         /**
144          * true if we need to set the altitude of this point
145          */
146         private boolean needsAltitude(DataPoint point, boolean overwriteZeros)
147         {
148                 if (!point.hasAltitude())
149                 {
150                         return true;
151                 }
152                 if (overwriteZeros && point.getAltitude().getValue() == 0)
153                 {
154                         return true;
155                 }
156                 return false;
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 = "";
175                 for (int t=0; t<inTileList.size() && !_progress.isCancelled(); t++)
176                 {
177                         SrtmTile tile = inTileList.get(t);
178                         SrtmSource srtmSource = tile.findBestCachedSource();
179
180                         if (srtmSource == null)
181                         {
182                                 errorMessage += "Tile "+tile.getTileName()+" not in cache!\n";
183                                 continue;
184                         }
185
186                         // Set progress
187                         _progress.setValue(t);
188
189                         int[] heights;
190                         try {
191                                 heights = srtmSource.getTileHeights(tile);
192                         }
193                         catch (SrtmSourceException e)
194                         {
195                                 errorMessage += e.getMessage();
196                                 continue;
197                         }
198                         int rowSize = srtmSource.getRowSize(tile);
199                         if (rowSize <= 0)
200                         {
201                                 errorMessage += "Tile "+tile.getTileName()+" is corrupted";
202                         }
203
204                         try {
205                                 numAltitudesFound += applySrtmTileToWholeTrack(tile, heights, rowSize, inOverwriteZeros);
206                         }
207                         catch (SrtmSourceException e)
208                         {
209                                 errorMessage += e.getMessage();
210                                 continue;
211                         }
212                 }
213
214                 _progress.dispose();
215                 if (_progress.isCancelled()) {
216                         return;
217                 }
218
219                 if (! errorMessage.equals("")) {
220                         _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
221                         return;
222                 }
223                 if (numAltitudesFound > 0)
224                 {
225                         // Inform app including undo information
226                         _track.requestRescale();
227                         UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
228                         // Don't update app if we're doing another track
229                         if (_normalTrack)
230                         {
231                                 _app.completeFunction(undo,
232                                         I18nManager.getTextWithNumber("confirm.lookupsrtm", numAltitudesFound));
233                         }
234                 }
235                 else if (inTileList.size() > 0) {
236                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
237                 }
238                 else {
239                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
240                 }
241         }
242
243         /**
244          * Given the height data read in from file, apply the given tile to all points
245          * in the track with missing altitude
246          * @param inTile tile being applied
247          * @param inHeights height data read in from file
248          * @param inOverwriteZeros true to overwrite zero altitude values
249          * @return number of altitudes found
250          */
251         private int applySrtmTileToWholeTrack(SrtmTile inTile, int[] inHeights, int inRowSize, boolean inOverwriteZeros)
252                 throws SrtmSourceException
253         {
254                 int numAltitudesFound = 0;
255                 // Loop over all points in track, try to apply altitude from array
256                 for (int p = 0; p < _track.getNumPoints(); p++)
257                 {
258                         DataPoint point = _track.getPoint(p);
259                         if (needsAltitude(point, inOverwriteZeros))
260                         {
261                                 if (new SrtmTile(point).equals(inTile))
262                                 {
263                                         double x = (point.getLongitude().getDouble() - inTile.getLongitude()) * (inRowSize - 1);
264                                         double y = inRowSize - (point.getLatitude().getDouble() - inTile.getLatitude()) * (inRowSize - 1);
265                                         int idx1 = ((int)y)*inRowSize + (int)x;
266                                         try
267                                         {
268                                                 int[] fouralts = {inHeights[idx1], inHeights[idx1+1], inHeights[idx1-inRowSize], inHeights[idx1-inRowSize+1]};
269                                                 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
270                                                         + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
271                                                 // if (numVoids > 0) System.out.println(numVoids + " voids found");
272                                                 double altitude = 0.0;
273                                                 switch (numVoids)
274                                                 {
275                                                 case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
276                                                 case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
277                                                 case 2:
278                                                 case 3: altitude = averageNonVoid(fouralts); break;
279                                                 default: altitude = VOID_VAL;
280                                                 }
281                                                 // Special case for terrain tracks, don't interpolate voids yet
282                                                 if (!_normalTrack && numVoids > 0) {
283                                                         altitude = VOID_VAL;
284                                                 }
285                                                 if (altitude != VOID_VAL)
286                                                 {
287                                                         point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
288                                                         // depending on settings, this value may have been added as feet, we need to force metres
289                                                         point.getAltitude().reset(new Altitude((int)altitude, UnitSetLibrary.UNITS_METRES));
290                                                         numAltitudesFound++;
291                                                 }
292                                         }
293                                         catch (ArrayIndexOutOfBoundsException obe) {
294                                                 throw new SrtmSourceException("Point not in tile? lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1+"\n");
295                                         }
296                                 }
297                         }
298                 }
299                 return numAltitudesFound;
300         }
301
302         /**
303          * Perform a bilinear interpolation on the given altitude array
304          * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
305          * @param inX x coordinate
306          * @param inY y coordinate
307          * @return interpolated altitude
308          */
309         private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
310         {
311                 double alpha = inX - (int) inX;
312                 double beta  = 1 - (inY - (int) inY);
313                 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
314                         + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
315                 return alt;
316         }
317
318         /**
319          * Fix a single void in the given array by replacing it with the average of the others
320          * @param inAltitudes array of altitudes containing one void
321          * @return fixed array without voids
322          */
323         private static int[] fixVoid(int[] inAltitudes)
324         {
325                 int[] fixed = new int[inAltitudes.length];
326                 for (int i = 0; i < inAltitudes.length; i++)
327                 {
328                         if (inAltitudes[i] == VOID_VAL) {
329                                 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
330                         }
331                         else {
332                                 fixed[i] = inAltitudes[i];
333                         }
334                 }
335                 return fixed;
336         }
337
338         /**
339          * Calculate the average of the non-void altitudes in the given array
340          * @param inAltitudes array of altitudes with one or more voids
341          * @return average of non-void altitudes
342          */
343         private static final double averageNonVoid(int[] inAltitudes)
344         {
345                 double totalAltitude = 0.0;
346                 int numAlts = 0;
347                 for (int i = 0; i < inAltitudes.length; i++)
348                 {
349                         if (inAltitudes[i] != VOID_VAL)
350                         {
351                                 totalAltitude += inAltitudes[i];
352                                 numAlts++;
353                         }
354                 }
355                 if (numAlts < 1) {return VOID_VAL;}
356                 return totalAltitude / numAlts;
357         }
358
359         /**
360          * @return true if a thread is currently running
361          */
362         public boolean isRunning()
363         {
364                 return _running;
365         }
366 }