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.JPanel;
19 import javax.swing.JProgressBar;
22 import tim.prune.DataSubscriber;
23 import tim.prune.GenericFunction;
24 import tim.prune.I18nManager;
25 import tim.prune.UpdateMessageBroker;
26 import tim.prune.data.DataPoint;
27 import tim.prune.data.Field;
28 import tim.prune.data.Track;
29 import tim.prune.undo.UndoLookupSrtm;
32 * Class to provide a lookup function for point altitudes
33 * using the Space Shuttle's SRTM data files.
34 * HGT files are downloaded into memory via HTTP and point altitudes
35 * can then be interpolated from the 3m grid data.
37 public class LookupSrtmFunction extends GenericFunction implements Runnable
39 /** function dialog */
40 private JDialog _dialog = null;
41 /** Progress bar for function */
42 private JProgressBar _progressBar = null;
44 private boolean _cancelled = false;
46 /** Expected size of hgt file in bytes */
47 private static final long HGT_SIZE = 2884802L;
48 /** Altitude below which is considered void */
49 private static final int VOID_VAL = -32768;
53 * @param inApp App object
55 public LookupSrtmFunction(App inApp)
60 /** @return name key */
61 public String getNameKey() {
62 return "function.lookupsrtm";
72 _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), false);
73 _dialog.setLocationRelativeTo(_parentFrame);
74 _dialog.getContentPane().add(makeDialogComponents());
77 _progressBar.setMinimum(0);
78 _progressBar.setMaximum(100);
79 _progressBar.setValue(20);
81 // start new thread for time-consuming part
82 new Thread(this).start();
87 * Make the dialog components
88 * @return the GUI components for the dialog
90 private Component makeDialogComponents()
92 JPanel dialogPanel = new JPanel();
93 dialogPanel.setLayout(new BorderLayout());
94 dialogPanel.add(new JLabel(I18nManager.getText("confirm.running")), BorderLayout.NORTH);
95 _progressBar = new JProgressBar();
96 _progressBar.setPreferredSize(new Dimension(250, 30));
97 dialogPanel.add(_progressBar, BorderLayout.CENTER);
98 // Cancel button at the bottom
99 JPanel buttonPanel = new JPanel();
100 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
101 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
102 cancelButton.addActionListener(new ActionListener() {
103 public void actionPerformed(ActionEvent e) {
107 buttonPanel.add(cancelButton);
108 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
113 * Run method using separate thread
117 _dialog.setVisible(true);
118 // Compile list of tiles to get
119 Track track = _app.getTrackInfo().getTrack();
120 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
121 for (int i=0; i<track.getNumPoints(); i++)
123 // Only consider points which don't have altitudes already
124 if (!track.getPoint(i).hasAltitude())
126 SrtmTile tile = new SrtmTile(track.getPoint(i));
127 boolean alreadyGot = false;
128 for (int t=0; t<tileList.size(); t++) {
129 if (tileList.get(t).equals(tile)) {
133 if (!alreadyGot) {tileList.add(tile);}
136 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
137 int numAltitudesFound = 0;
138 // Update progress bar
139 _progressBar.setMaximum(tileList.size());
140 _progressBar.setIndeterminate(tileList.size() <= 1);
141 _progressBar.setValue(0);
142 // Get urls for each tile
143 URL[] urls = TileFinder.getUrls(tileList);
144 for (int t=0; t<tileList.size() && !_cancelled; t++)
148 SrtmTile tile = tileList.get(t);
149 // System.out.println("tile " + t + " of " + tileList.size() + " = " + urls[t].toString());
151 _progressBar.setValue(t);
152 final int ARRLENGTH = 1201*1201;
153 int[] heights = new int[ARRLENGTH];
154 // Open zipinputstream on url and check size
155 ZipInputStream inStream = new ZipInputStream(urls[t].openStream());
156 ZipEntry entry = inStream.getNextEntry();
157 boolean entryOk = (entry.getSize() == HGT_SIZE);
160 // Read entire file contents into one byte array
161 for (int i=0; i<ARRLENGTH; i++) {
162 heights[i] = inStream.read()*256 + inStream.read();
163 if (heights[i] >= 32768) {heights[i] -= 65536;}
167 // System.out.println("length not ok: " + entry.getSize());
169 // Close stream from url
174 // Loop over all points in track, try to apply altitude from array
175 for (int p=0; p<track.getNumPoints(); p++)
177 DataPoint point = track.getPoint(p);
178 if (!point.hasAltitude() || point.getAltitude().getValue() == 0) {
179 if (new SrtmTile(point).equals(tile))
181 double x = (point.getLongitude().getDouble() - tile.getLongitude()) * 1200;
182 double y = 1201 - (point.getLatitude().getDouble() - tile.getLatitude()) * 1200;
183 int idx1 = ((int)y)*1201 + (int)x;
185 int[] fouralts = {heights[idx1], heights[idx1+1], heights[idx1-1201], heights[idx1-1200]};
186 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
187 + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
188 // if (numVoids > 0) System.out.println(numVoids + " voids found");
189 double altitude = 0.0;
191 case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
192 case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
194 case 3: altitude = averageNonVoid(fouralts); break;
195 default: altitude = VOID_VAL;
197 if (altitude != VOID_VAL) {
198 point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
202 catch (ArrayIndexOutOfBoundsException obe) {
203 //System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
210 catch (IOException ioe) {
211 //System.err.println("eek - " + ioe.getMessage());
216 if (numAltitudesFound > 0)
218 // Inform app including undo information
219 track.requestRescale();
220 UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
221 _app.completeFunction(undo, I18nManager.getText("confirm.lookupsrtm1") + " " + numAltitudesFound
222 + " " + I18nManager.getText("confirm.lookupsrtm2"));
225 _app.showErrorMessage(getNameKey(), "error.lookupsrtm.none");
230 * Perform a bilinear interpolation on the given altitude array
231 * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
232 * @param inX x coordinate
233 * @param inY y coordinate
234 * @return interpolated altitude
236 private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
238 double alpha = inX - (int) inX;
239 double beta = 1 - (inY - (int) inY);
240 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
241 + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
246 * Fix a single void in the given array by replacing it with the average of the others
247 * @param inAltitudes array of altitudes containing one void
248 * @return fixed array without voids
250 private static int[] fixVoid(int[] inAltitudes)
252 int[] fixed = new int[inAltitudes.length];
253 for (int i=0; i<inAltitudes.length; i++) {
254 if (inAltitudes[i] == VOID_VAL) {
255 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
258 fixed[i] = inAltitudes[i];
265 * Calculate the average of the non-void altitudes in the given array
266 * @param inAltitudes array of altitudes with one or more voids
267 * @return average of non-void altitudes
269 private static final double averageNonVoid(int[] inAltitudes)
271 double totalAltitude = 0.0;
273 for (int i=0; i<inAltitudes.length; i++) {
274 if (inAltitudes[i] != VOID_VAL) {
275 totalAltitude += inAltitudes[i];
279 if (numAlts < 1) {return VOID_VAL;}
280 return totalAltitude / numAlts;