1 package tim.prune.function.srtm;
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;
11 import java.util.ArrayList;
12 import java.util.zip.ZipEntry;
13 import java.util.zip.ZipInputStream;
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;
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;
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.
38 public class LookupSrtmFunction extends GenericFunction implements Runnable
40 /** function dialog */
41 private JDialog _dialog = null;
42 /** Progress bar for function */
43 private JProgressBar _progressBar = null;
45 private boolean _cancelled = false;
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;
55 * @param inApp App object
57 public LookupSrtmFunction(App inApp)
62 /** @return name key */
63 public String getNameKey() {
64 return "function.lookupsrtm";
74 _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), false);
75 _dialog.setLocationRelativeTo(_parentFrame);
76 _dialog.getContentPane().add(makeDialogComponents());
79 _progressBar.setMinimum(0);
80 _progressBar.setMaximum(100);
81 _progressBar.setValue(20);
83 // start new thread for time-consuming part
84 new Thread(this).start();
89 * Make the dialog components
90 * @return the GUI components for the dialog
92 private Component makeDialogComponents()
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) {
109 buttonPanel.add(cancelButton);
110 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
115 * Run method using separate thread
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++)
127 if (track.getPoint(i).hasAltitude())
129 if (track.getPoint(i).getAltitude().getValue() == 0) {
130 hasZeroAltitudePoints = true;
133 hasNonZeroAltitudePoints = true;
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)
144 overwriteZeros = true;
147 _dialog.setVisible(true);
148 // Now loop again to extract the required tiles
149 for (int i=0; i<track.getNumPoints(); i++)
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))
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)) {
161 if (!alreadyGot) {tileList.add(tile);}
164 lookupValues(tileList, overwriteZeros);
168 * Lookup the values from SRTM data
169 * @param inTileList list of tiles to get
170 * @param inOverwriteZeros true to overwrite zero altitude values
172 private void lookupValues(ArrayList<SrtmTile> inTileList, boolean inOverwriteZeros)
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++)
187 SrtmTile tile = inTileList.get(t);
188 // System.out.println("tile " + t + " of " + tileList.size() + " = " + urls[t].toString());
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);
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;}
206 // System.out.println("length not ok: " + entry.getSize());
208 // Close stream from url
213 // Loop over all points in track, try to apply altitude from array
214 for (int p=0; p<track.getNumPoints(); p++)
216 DataPoint point = track.getPoint(p);
217 if (!point.hasAltitude() || (inOverwriteZeros && point.getAltitude().getValue() == 0)) {
218 if (new SrtmTile(point).equals(tile))
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;
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;
230 case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
231 case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
233 case 3: altitude = averageNonVoid(fouralts); break;
234 default: altitude = VOID_VAL;
236 if (altitude != VOID_VAL) {
237 point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
241 catch (ArrayIndexOutOfBoundsException obe) {
242 //System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
249 catch (IOException ioe) {
250 //System.err.println("eek - " + ioe.getMessage());
255 if (numAltitudesFound > 0)
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"));
263 else if (inTileList.size() > 0) {
264 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
267 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
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
278 private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
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];
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
292 private static int[] fixVoid(int[] inAltitudes)
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));
300 fixed[i] = inAltitudes[i];
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
311 private static final double averageNonVoid(int[] inAltitudes)
313 double totalAltitude = 0.0;
315 for (int i=0; i<inAltitudes.length; i++) {
316 if (inAltitudes[i] != VOID_VAL) {
317 totalAltitude += inAltitudes[i];
321 if (numAlts < 1) {return VOID_VAL;}
322 return totalAltitude / numAlts;