]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/function/srtm/LookupSrtmFunction.java
Version 11, August 2010
[GpsPrune.git] / tim / prune / function / srtm / LookupSrtmFunction.java
1 package tim.prune.function.srtm;
2
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.Dimension;
6 import java.awt.FlowLayout;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.io.IOException;
10 import java.net.URL;
11 import java.util.ArrayList;
12 import java.util.zip.ZipEntry;
13 import java.util.zip.ZipInputStream;
14
15 import javax.swing.JButton;
16 import javax.swing.JDialog;
17 import javax.swing.JLabel;
18 import javax.swing.JOptionPane;
19 import javax.swing.JPanel;
20 import javax.swing.JProgressBar;
21
22 import tim.prune.App;
23 import tim.prune.DataSubscriber;
24 import tim.prune.GenericFunction;
25 import tim.prune.I18nManager;
26 import tim.prune.UpdateMessageBroker;
27 import tim.prune.data.DataPoint;
28 import tim.prune.data.Field;
29 import tim.prune.data.Track;
30 import tim.prune.undo.UndoLookupSrtm;
31
32 /**
33  * Class to provide a lookup function for point altitudes
34  * using the Space Shuttle's SRTM data files.
35  * HGT files are downloaded into memory via HTTP and point altitudes
36  * can then be interpolated from the 3m grid data.
37  */
38 public class LookupSrtmFunction extends GenericFunction implements Runnable
39 {
40         /** function dialog */
41         private JDialog _dialog = null;
42         /** Progress bar for function */
43         private JProgressBar _progressBar = null;
44         /** Cancel flag */
45         private boolean _cancelled = false;
46
47         /** Expected size of hgt file in bytes */
48         private static final long HGT_SIZE = 2884802L;
49         /** Altitude below which is considered void */
50         private static final int VOID_VAL = -32768;
51
52
53         /**
54          * Constructor
55          * @param inApp App object
56          */
57         public LookupSrtmFunction(App inApp)
58         {
59                 super(inApp);
60         }
61
62         /** @return name key */
63         public String getNameKey() {
64                 return "function.lookupsrtm";
65         }
66
67         /**
68          * Begin the lookup
69          */
70         public void begin()
71         {
72                 if (_dialog == null)
73                 {
74                         _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), false);
75                         _dialog.setLocationRelativeTo(_parentFrame);
76                         _dialog.getContentPane().add(makeDialogComponents());
77                         _dialog.pack();
78                 }
79                 _progressBar.setMinimum(0);
80                 _progressBar.setMaximum(100);
81                 _progressBar.setValue(20);
82                 _cancelled = false;
83                 // start new thread for time-consuming part
84                 new Thread(this).start();
85         }
86
87
88         /**
89          * Make the dialog components
90          * @return the GUI components for the dialog
91          */
92         private Component makeDialogComponents()
93         {
94                 JPanel dialogPanel = new JPanel();
95                 dialogPanel.setLayout(new BorderLayout());
96                 dialogPanel.add(new JLabel(I18nManager.getText("confirm.running")), BorderLayout.NORTH);
97                 _progressBar = new JProgressBar();
98                 _progressBar.setPreferredSize(new Dimension(250, 30));
99                 dialogPanel.add(_progressBar, BorderLayout.CENTER);
100                 // Cancel button at the bottom
101                 JPanel buttonPanel = new JPanel();
102                 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
103                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
104                 cancelButton.addActionListener(new ActionListener() {
105                         public void actionPerformed(ActionEvent e) {
106                                 _cancelled = true;
107                         }
108                 });
109                 buttonPanel.add(cancelButton);
110                 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
111                 return dialogPanel;
112         }
113
114         /**
115          * Run method using separate thread
116          */
117         public void run()
118         {
119                 // Compile list of tiles to get
120                 Track track = _app.getTrackInfo().getTrack();
121                 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
122                 boolean hasZeroAltitudePoints = false;
123                 boolean hasNonZeroAltitudePoints = false;
124                 // First, loop to see what kind of points we have
125                 for (int i=0; i<track.getNumPoints(); i++)
126                 {
127                         if (track.getPoint(i).hasAltitude())
128                         {
129                                 if (track.getPoint(i).getAltitude().getValue() == 0) {
130                                         hasZeroAltitudePoints = true;
131                                 }
132                                 else {
133                                         hasNonZeroAltitudePoints = true;
134                                 }
135                         }
136                 }
137                 // Should we overwrite the zero altitude values?
138                 boolean overwriteZeros = hasZeroAltitudePoints && !hasNonZeroAltitudePoints;
139                 // If non-zero values present as well, ask user whether to overwrite the zeros or not
140                 if (hasNonZeroAltitudePoints && hasZeroAltitudePoints && JOptionPane.showConfirmDialog(_parentFrame,
141                         I18nManager.getText("dialog.lookupsrtm.overwritezeros"), I18nManager.getText(getNameKey()),
142                         JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
143                 {
144                         overwriteZeros = true;
145                 }
146
147                 _dialog.setVisible(true);
148                 // Now loop again to extract the required tiles
149                 for (int i=0; i<track.getNumPoints(); i++)
150                 {
151                         // Consider points which don't have altitudes or have zero values
152                         if (!track.getPoint(i).hasAltitude() || (overwriteZeros && track.getPoint(i).getAltitude().getValue() == 0))
153                         {
154                                 SrtmTile tile = new SrtmTile(track.getPoint(i));
155                                 boolean alreadyGot = false;
156                                 for (int t=0; t<tileList.size(); t++) {
157                                         if (tileList.get(t).equals(tile)) {
158                                                 alreadyGot = true;
159                                         }
160                                 }
161                                 if (!alreadyGot) {tileList.add(tile);}
162                         }
163                 }
164                 lookupValues(tileList, overwriteZeros);
165         }
166
167         /**
168          * Lookup the values from SRTM data
169          * @param inTileList list of tiles to get
170          * @param inOverwriteZeros true to overwrite zero altitude values
171          */
172         private void lookupValues(ArrayList<SrtmTile> inTileList, boolean inOverwriteZeros)
173         {
174                 Track track = _app.getTrackInfo().getTrack();
175                 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
176                 int numAltitudesFound = 0;
177                 // Update progress bar
178                 _progressBar.setMaximum(inTileList.size());
179                 _progressBar.setIndeterminate(inTileList.size() <= 1);
180                 _progressBar.setValue(0);
181                 // Get urls for each tile
182                 URL[] urls = TileFinder.getUrls(inTileList);
183                 for (int t=0; t<inTileList.size() && !_cancelled; t++)
184                 {
185                         if (urls[t] != null)
186                         {
187                                 SrtmTile tile = inTileList.get(t);
188                                 // System.out.println("tile " + t + " of " + tileList.size() + " = " + urls[t].toString());
189                                 try {
190                                         _progressBar.setValue(t);
191                                         final int ARRLENGTH = 1201*1201;
192                                         int[] heights = new int[ARRLENGTH];
193                                         // Open zipinputstream on url and check size
194                                         ZipInputStream inStream = new ZipInputStream(urls[t].openStream());
195                                         ZipEntry entry = inStream.getNextEntry();
196                                         boolean entryOk = (entry.getSize() == HGT_SIZE);
197                                         if (entryOk)
198                                         {
199                                                 // Read entire file contents into one byte array
200                                                 for (int i=0; i<ARRLENGTH; i++) {
201                                                         heights[i] = inStream.read()*256 + inStream.read();
202                                                         if (heights[i] >= 32768) {heights[i] -= 65536;}
203                                                 }
204                                         }
205                                         //else {
206                                         //      System.out.println("length not ok: " + entry.getSize());
207                                         //}
208                                         // Close stream from url
209                                         inStream.close();
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() || (inOverwriteZeros && point.getAltitude().getValue() == 0)) {
218                                                                 if (new SrtmTile(point).equals(tile))
219                                                                 {
220                                                                         double x = (point.getLongitude().getDouble() - tile.getLongitude()) * 1200;
221                                                                         double y = 1201 - (point.getLatitude().getDouble() - tile.getLatitude()) * 1200;
222                                                                         int idx1 = ((int)y)*1201 + (int)x;
223                                                                         try {
224                                                                                 int[] fouralts = {heights[idx1], heights[idx1+1], heights[idx1-1201], heights[idx1-1200]};
225                                                                                 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
226                                                                                         + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
227                                                                                 // if (numVoids > 0) System.out.println(numVoids + " voids found");
228                                                                                 double altitude = 0.0;
229                                                                                 switch (numVoids) {
230                                                                                         case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
231                                                                                         case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
232                                                                                         case 2:
233                                                                                         case 3: altitude = averageNonVoid(fouralts); break;
234                                                                                         default: altitude = VOID_VAL;
235                                                                                 }
236                                                                                 if (altitude != VOID_VAL) {
237                                                                                         point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
238                                                                                         numAltitudesFound++;
239                                                                                 }
240                                                                         }
241                                                                         catch (ArrayIndexOutOfBoundsException obe) {
242                                                                                 //System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
243                                                                         }
244                                                                 }
245                                                         }
246                                                 }
247                                         }
248                                 }
249                                 catch (IOException ioe) {
250                                         //System.err.println("eek - " + ioe.getMessage());
251                                 }
252                         }
253                 }
254                 _dialog.dispose();
255                 if (numAltitudesFound > 0)
256                 {
257                         // Inform app including undo information
258                         track.requestRescale();
259                         UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
260                         _app.completeFunction(undo, I18nManager.getText("confirm.lookupsrtm1") + " " + numAltitudesFound
261                                 + " " + I18nManager.getText("confirm.lookupsrtm2"));
262                 }
263                 else if (inTileList.size() > 0) {
264                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
265                 }
266                 else {
267                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
268                 }
269         }
270
271         /**
272          * Perform a bilinear interpolation on the given altitude array
273          * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
274          * @param inX x coordinate
275          * @param inY y coordinate
276          * @return interpolated altitude
277          */
278         private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
279         {
280                 double alpha = inX - (int) inX;
281                 double beta  = 1 - (inY - (int) inY);
282                 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
283                         + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
284                 return alt;
285         }
286
287         /**
288          * Fix a single void in the given array by replacing it with the average of the others
289          * @param inAltitudes array of altitudes containing one void
290          * @return fixed array without voids
291          */
292         private static int[] fixVoid(int[] inAltitudes)
293         {
294                 int[] fixed = new int[inAltitudes.length];
295                 for (int i=0; i<inAltitudes.length; i++) {
296                         if (inAltitudes[i] == VOID_VAL) {
297                                 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
298                         }
299                         else {
300                                 fixed[i] = inAltitudes[i];
301                         }
302                 }
303                 return fixed;
304         }
305
306         /**
307          * Calculate the average of the non-void altitudes in the given array
308          * @param inAltitudes array of altitudes with one or more voids
309          * @return average of non-void altitudes
310          */
311         private static final double averageNonVoid(int[] inAltitudes)
312         {
313                 double totalAltitude = 0.0;
314                 int numAlts = 0;
315                 for (int i=0; i<inAltitudes.length; i++) {
316                         if (inAltitudes[i] != VOID_VAL) {
317                                 totalAltitude += inAltitudes[i];
318                                 numAlts++;
319                         }
320                 }
321                 if (numAlts < 1) {return VOID_VAL;}
322                 return totalAltitude / numAlts;
323         }
324 }