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) {
110 buttonPanel.add(cancelButton);
111 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
116 * Run method using separate thread
120 // Compile list of tiles to get
121 Track track = _app.getTrackInfo().getTrack();
122 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
123 boolean hasZeroAltitudePoints = false;
124 boolean hasNonZeroAltitudePoints = false;
125 // First, loop to see what kind of points we have
126 for (int i=0; i<track.getNumPoints(); i++)
128 if (track.getPoint(i).hasAltitude())
130 if (track.getPoint(i).getAltitude().getValue() == 0) {
131 hasZeroAltitudePoints = true;
134 hasNonZeroAltitudePoints = true;
138 // Should we overwrite the zero altitude values?
139 boolean overwriteZeros = hasZeroAltitudePoints && !hasNonZeroAltitudePoints;
140 // If non-zero values present as well, ask user whether to overwrite the zeros or not
141 if (hasNonZeroAltitudePoints && hasZeroAltitudePoints && JOptionPane.showConfirmDialog(_parentFrame,
142 I18nManager.getText("dialog.lookupsrtm.overwritezeros"), I18nManager.getText(getNameKey()),
143 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
145 overwriteZeros = true;
148 _dialog.setVisible(true);
149 // Now loop again to extract the required tiles
150 for (int i=0; i<track.getNumPoints(); i++)
152 // Consider points which don't have altitudes or have zero values
153 if (!track.getPoint(i).hasAltitude() || (overwriteZeros && track.getPoint(i).getAltitude().getValue() == 0))
155 SrtmTile tile = new SrtmTile(track.getPoint(i));
156 boolean alreadyGot = false;
157 for (int t=0; t<tileList.size(); t++) {
158 if (tileList.get(t).equals(tile)) {
162 if (!alreadyGot) {tileList.add(tile);}
165 lookupValues(tileList, overwriteZeros);
169 * Lookup the values from SRTM data
170 * @param inTileList list of tiles to get
171 * @param inOverwriteZeros true to overwrite zero altitude values
173 private void lookupValues(ArrayList<SrtmTile> inTileList, boolean inOverwriteZeros)
175 Track track = _app.getTrackInfo().getTrack();
176 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
177 int numAltitudesFound = 0;
178 // Update progress bar
179 _progressBar.setMaximum(inTileList.size());
180 _progressBar.setIndeterminate(inTileList.size() <= 1);
181 _progressBar.setValue(0);
182 String errorMessage = null;
183 // Get urls for each tile
184 URL[] urls = TileFinder.getUrls(inTileList);
185 for (int t=0; t<inTileList.size() && !_cancelled; t++)
189 SrtmTile tile = inTileList.get(t);
192 _progressBar.setValue(t);
193 final int ARRLENGTH = 1201*1201;
194 int[] heights = new int[ARRLENGTH];
195 // Open zipinputstream on url and check size
196 ZipInputStream inStream = new ZipInputStream(urls[t].openStream());
197 ZipEntry entry = inStream.getNextEntry();
198 boolean entryOk = (entry.getSize() == HGT_SIZE);
201 // Read entire file contents into one byte array
202 for (int i=0; i<ARRLENGTH; i++) {
203 heights[i] = inStream.read()*256 + inStream.read();
204 if (heights[i] >= 32768) {heights[i] -= 65536;}
208 // System.out.println("length not ok: " + entry.getSize());
210 // Close stream from url
215 // Loop over all points in track, try to apply altitude from array
216 for (int p=0; p<track.getNumPoints(); p++)
218 DataPoint point = track.getPoint(p);
219 if (!point.hasAltitude() || (inOverwriteZeros && point.getAltitude().getValue() == 0)) {
220 if (new SrtmTile(point).equals(tile))
222 double x = (point.getLongitude().getDouble() - tile.getLongitude()) * 1200;
223 double y = 1201 - (point.getLatitude().getDouble() - tile.getLatitude()) * 1200;
224 int idx1 = ((int)y)*1201 + (int)x;
226 int[] fouralts = {heights[idx1], heights[idx1+1], heights[idx1-1201], heights[idx1-1200]};
227 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
228 + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
229 // if (numVoids > 0) System.out.println(numVoids + " voids found");
230 double altitude = 0.0;
232 case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
233 case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
235 case 3: altitude = averageNonVoid(fouralts); break;
236 default: altitude = VOID_VAL;
238 if (altitude != VOID_VAL) {
239 point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
243 catch (ArrayIndexOutOfBoundsException obe) {
244 //System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
251 catch (IOException ioe) {
252 errorMessage = ioe.getClass().getName() + " - " + ioe.getMessage();
257 if (_cancelled) {return;}
258 if (numAltitudesFound > 0)
260 // Inform app including undo information
261 track.requestRescale();
262 UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
263 _app.completeFunction(undo, I18nManager.getText("confirm.lookupsrtm1") + " " + numAltitudesFound
264 + " " + I18nManager.getText("confirm.lookupsrtm2"));
266 else if (errorMessage != null) {
267 _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
269 else if (inTileList.size() > 0) {
270 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
273 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
278 * Perform a bilinear interpolation on the given altitude array
279 * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
280 * @param inX x coordinate
281 * @param inY y coordinate
282 * @return interpolated altitude
284 private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
286 double alpha = inX - (int) inX;
287 double beta = 1 - (inY - (int) inY);
288 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
289 + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
294 * Fix a single void in the given array by replacing it with the average of the others
295 * @param inAltitudes array of altitudes containing one void
296 * @return fixed array without voids
298 private static int[] fixVoid(int[] inAltitudes)
300 int[] fixed = new int[inAltitudes.length];
301 for (int i=0; i<inAltitudes.length; i++) {
302 if (inAltitudes[i] == VOID_VAL) {
303 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
306 fixed[i] = inAltitudes[i];
313 * Calculate the average of the non-void altitudes in the given array
314 * @param inAltitudes array of altitudes with one or more voids
315 * @return average of non-void altitudes
317 private static final double averageNonVoid(int[] inAltitudes)
319 double totalAltitude = 0.0;
321 for (int i=0; i<inAltitudes.length; i++) {
322 if (inAltitudes[i] != VOID_VAL) {
323 totalAltitude += inAltitudes[i];
327 if (numAlts < 1) {return VOID_VAL;}
328 return totalAltitude / numAlts;