]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/function/srtm/LookupSrtmFunction.java
Version 10, May 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.JPanel;
19 import javax.swing.JProgressBar;
20
21 import tim.prune.App;
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;
30
31 /**
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.
36  */
37 public class LookupSrtmFunction extends GenericFunction implements Runnable
38 {
39         /** function dialog */
40         private JDialog _dialog = null;
41         /** Progress bar for function */
42         private JProgressBar _progressBar = null;
43         /** Cancel flag */
44         private boolean _cancelled = false;
45
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;
50
51         /**
52          * Constructor
53          * @param inApp App object
54          */
55         public LookupSrtmFunction(App inApp)
56         {
57                 super(inApp);
58         }
59
60         /** @return name key */
61         public String getNameKey() {
62                 return "function.lookupsrtm";
63         }
64
65         /**
66          * Begin the lookup
67          */
68         public void begin()
69         {
70                 if (_dialog == null)
71                 {
72                         _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), false);
73                         _dialog.setLocationRelativeTo(_parentFrame);
74                         _dialog.getContentPane().add(makeDialogComponents());
75                         _dialog.pack();
76                 }
77                 _progressBar.setMinimum(0);
78                 _progressBar.setMaximum(100);
79                 _progressBar.setValue(20);
80                 _cancelled = false;
81                 // start new thread for time-consuming part
82                 new Thread(this).start();
83         }
84
85
86         /**
87          * Make the dialog components
88          * @return the GUI components for the dialog
89          */
90         private Component makeDialogComponents()
91         {
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) {
104                                 _cancelled = true;
105                         }
106                 });
107                 buttonPanel.add(cancelButton);
108                 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
109                 return dialogPanel;
110         }
111
112         /**
113          * Run method using separate thread
114          */
115         public void run()
116         {
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++)
122                 {
123                         // Only consider points which don't have altitudes already
124                         if (!track.getPoint(i).hasAltitude())
125                         {
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)) {
130                                                 alreadyGot = true;
131                                         }
132                                 }
133                                 if (!alreadyGot) {tileList.add(tile);}
134                         }
135                 }
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++)
145                 {
146                         if (urls[t] != null)
147                         {
148                                 SrtmTile tile = tileList.get(t);
149                                 // System.out.println("tile " + t + " of " + tileList.size() + " = " + urls[t].toString());
150                                 try {
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);
158                                         if (entryOk)
159                                         {
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;}
164                                                 }
165                                         }
166                                         //else {
167                                         //      System.out.println("length not ok: " + entry.getSize());
168                                         //}
169                                         // Close stream from url
170                                         inStream.close();
171
172                                         if (entryOk)
173                                         {
174                                                 // Loop over all points in track, try to apply altitude from array
175                                                 for (int p=0; p<track.getNumPoints(); p++)
176                                                 {
177                                                         DataPoint point = track.getPoint(p);
178                                                         if (!point.hasAltitude() || point.getAltitude().getValue() == 0) {
179                                                                 if (new SrtmTile(point).equals(tile))
180                                                                 {
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;
184                                                                         try {
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;
190                                                                                 switch (numVoids) {
191                                                                                         case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
192                                                                                         case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
193                                                                                         case 2:
194                                                                                         case 3: altitude = averageNonVoid(fouralts); break;
195                                                                                         default: altitude = VOID_VAL;
196                                                                                 }
197                                                                                 if (altitude != VOID_VAL) {
198                                                                                         point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
199                                                                                         numAltitudesFound++;
200                                                                                 }
201                                                                         }
202                                                                         catch (ArrayIndexOutOfBoundsException obe) {
203                                                                                 //System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
204                                                                         }
205                                                                 }
206                                                         }
207                                                 }
208                                         }
209                                 }
210                                 catch (IOException ioe) {
211                                         //System.err.println("eek - " + ioe.getMessage());
212                                 }
213                         }
214                 }
215                 _dialog.dispose();
216                 if (numAltitudesFound > 0)
217                 {
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"));
223                 }
224                 else {
225                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.none");
226                 }
227         }
228
229         /**
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
235          */
236         private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
237         {
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];
242                 return alt;
243         }
244
245         /**
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
249          */
250         private static int[] fixVoid(int[] inAltitudes)
251         {
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));
256                         }
257                         else {
258                                 fixed[i] = inAltitudes[i];
259                         }
260                 }
261                 return fixed;
262         }
263
264         /**
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
268          */
269         private static final double averageNonVoid(int[] inAltitudes)
270         {
271                 double totalAltitude = 0.0;
272                 int numAlts = 0;
273                 for (int i=0; i<inAltitudes.length; i++) {
274                         if (inAltitudes[i] != VOID_VAL) {
275                                 totalAltitude += inAltitudes[i];
276                                 numAlts++;
277                         }
278                 }
279                 if (numAlts < 1) {return VOID_VAL;}
280                 return totalAltitude / numAlts;
281         }
282 }