altosui: improve sitemap scrolling behaviour
[fw/altos] / ao-tools / altosui / AltosSiteMap.java
1 /*
2  * Copyright © 2010 Anthony Towns <aj@erisian.com.au>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package altosui;
19
20 import java.awt.*;
21 import java.awt.image.*;
22 import java.awt.event.*;
23 import javax.swing.*;
24 import javax.swing.event.MouseInputAdapter;
25 import javax.imageio.ImageIO;
26 import javax.swing.table.*;
27 import java.io.*;
28 import java.util.*;
29 import java.text.*;
30 import java.util.prefs.*;
31 import java.lang.Math;
32 import java.awt.geom.Point2D;
33 import java.awt.geom.Line2D;
34
35 public class AltosSiteMap extends JScrollPane implements AltosFlightDisplay {
36         // preferred vertical step in a tile in naut. miles
37         // will actually choose a step size between x and 2x, where this
38         // is 1.5x
39         static final double tile_size_nmi = 0.75;
40
41         static final int px_size = 512;
42
43         static final int MAX_TILE_DELTA = 100;
44
45         private static Point2D.Double translatePoint(Point2D.Double p,
46                         Point2D.Double d)
47         {
48                 return new Point2D.Double(p.x + d.x, p.y + d.y);
49         }
50
51         static class LatLng {
52                 public double lat, lng;
53                 public LatLng(double lat, double lng) {
54                         this.lat = lat;
55                         this.lng = lng;
56                 }
57         }
58
59         // based on google js
60         //  http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/10/main.js
61         // search for fromLatLngToPoint and fromPointToLatLng
62         private static Point2D.Double pt(LatLng latlng, int zoom) {
63                 double scale_x = 256/360.0 * Math.pow(2, zoom);
64                 double scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
65                 return pt(latlng, scale_x, scale_y);
66         }
67
68         private static Point2D.Double pt(LatLng latlng,
69                                          double scale_x, double scale_y)
70         {
71                 Point2D.Double res = new Point2D.Double();
72                 double e;
73
74                 res.x = latlng.lng * scale_x;
75
76                 e = Math.sin(Math.toRadians(latlng.lat));
77                 e = Math.max(e,-(1-1.0E-15));
78                 e = Math.min(e,  1-1.0E-15 );
79
80                 res.y = 0.5*Math.log((1+e)/(1-e))*-scale_y;
81                 return res;
82         }
83
84         static private LatLng latlng(Point2D.Double pt,
85                                      double scale_x, double scale_y)
86         {
87                 double lat, lng;
88                 double rads;
89
90                 lng = pt.x/scale_x;
91                 rads = 2 * Math.atan(Math.exp(-pt.y/scale_y));
92                 lat = Math.toDegrees(rads - Math.PI/2);
93
94                 return new LatLng(lat,lng);
95         }
96
97         int zoom;
98         double scale_x, scale_y;
99
100         private Point2D.Double pt(double lat, double lng) {
101                 return pt(new LatLng(lat, lng), scale_x, scale_y);
102         }
103
104         private LatLng latlng(double x, double y) {
105                 return latlng(new Point2D.Double(x,y), scale_x, scale_y);
106         }
107         private LatLng latlng(Point2D.Double pt) {
108                 return latlng(pt, scale_x, scale_y);
109         }
110
111         HashMap<Point,AltosSiteMapTile> mapTiles = new HashMap<Point,AltosSiteMapTile>();
112         Point2D.Double centre;
113
114         private Point2D.Double tileCoordOffset(Point p) {
115                 return new Point2D.Double(centre.x - p.x*px_size,
116                                           centre.y - p.y * px_size);
117         }
118
119         private Point tileOffset(Point2D.Double p) {
120                 return new Point((int)Math.floor((centre.x+p.x)/px_size),
121                                  (int)Math.floor((centre.y+p.y)/px_size));
122         }
123
124         private Point2D.Double getBaseLocation(double lat, double lng) {
125                 Point2D.Double locn, north_step;
126
127                 zoom = 2;
128                 // stupid loop structure to please Java's control flow analysis
129                 do {
130                         zoom++;
131                         scale_x = 256/360.0 * Math.pow(2, zoom);
132                         scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
133                         locn = pt(lat, lng);
134                         north_step = pt(lat+tile_size_nmi*4/3/60.0, lng);
135                         if (locn.y - north_step.y > px_size)
136                                 break;
137                 } while (zoom < 22);
138                 locn.x = -px_size * Math.floor(locn.x/px_size);
139                 locn.y = -px_size * Math.floor(locn.y/px_size);
140                 return locn;
141         }
142
143         public void reset() {
144                 // nothing
145         }
146
147         private void bgLoadMap(final AltosSiteMapTile tile,
148                                final File pngfile, final String pngurl)
149         {
150                 //System.out.printf("Loading/fetching map %s\n", pngfile);
151                 Thread thread = new Thread() {
152                         public void run() {
153                                 ImageIcon res;
154                                 res = AltosSiteMapCache.fetchAndLoadMap(pngfile, pngurl);
155                                 if (res != null) {
156                                         tile.loadMap(res);
157                                 } else {
158                                         System.out.printf("# Failed to fetch file %s\n", pngfile);
159                                         System.out.printf(" wget -O '%s' ''\n", pngfile, pngurl);
160                                 }
161                         }
162                 };
163                 thread.start();
164         }
165
166         public static void prefetchMaps(double lat, double lng, int w, int h) {
167                 AltosPreferences.init(null);
168
169                 AltosSiteMap asm = new AltosSiteMap(true);
170                 asm.centre = asm.getBaseLocation(lat, lng);
171
172                 Point2D.Double p = new Point2D.Double();
173                 Point2D.Double p2;
174                 int dx = -w/2, dy = -h/2;
175                 for (int y = dy; y < h+dy; y++) {
176                         for (int x = dx; x < w+dx; x++) {
177                                 LatLng map_latlng = asm.latlng(
178                                                             -asm.centre.x + x*px_size + px_size/2,
179                                                             -asm.centre.y + y*px_size + px_size/2);
180                                 File pngfile = asm.MapFile(map_latlng.lat, map_latlng.lng);
181                                 String pngurl = asm.MapURL(map_latlng.lat, map_latlng.lng);
182                                 if (pngfile.exists()) {
183                                         System.out.printf("Already have %s\n", pngfile);
184                                 } else if (AltosSiteMapCache.fetchMap(pngfile, pngurl)) {
185                                         System.out.printf("Fetched map %s\n", pngfile);
186                                 } else {
187                                         System.out.printf("# Failed to fetch file %s\n", pngfile);
188                                         System.out.printf(" wget -O '%s' ''\n", pngfile, pngurl);
189                                 }
190                         }
191                 }
192         }
193
194         private void initMap(AltosSiteMapTile tile, Point offset) {
195                 Point2D.Double coord = tileCoordOffset(offset);
196
197                 LatLng map_latlng = latlng(px_size/2-coord.x, px_size/2-coord.y);
198
199                 File pngfile = MapFile(map_latlng.lat, map_latlng.lng);
200                 String pngurl = MapURL(map_latlng.lat, map_latlng.lng);
201                 bgLoadMap(tile, pngfile, pngurl);
202         }
203
204         private void initMaps(double lat, double lng) {
205                 centre = getBaseLocation(lat, lng);
206
207                 for (Point k : mapTiles.keySet()) {
208                         initMap(mapTiles.get(k), k);
209                 }
210         }
211
212         private File MapFile(double lat, double lng) {
213                 char chlat = lat < 0 ? 'S' : 'N';
214                 char chlng = lng < 0 ? 'E' : 'W';
215                 if (lat < 0) lat = -lat;
216                 if (lng < 0) lng = -lng;
217                 return new File(AltosPreferences.logdir(),
218                                 String.format("map-%c%.6f,%c%.6f-%d.png",
219                                               chlat, lat, chlng, lng, zoom));
220         }
221
222         private String MapURL(double lat, double lng) {
223                 return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=hybrid&format=png32", lat, lng, zoom, px_size, px_size);
224         }
225
226         boolean initialised = false;
227         Point2D.Double last_pt = null;
228         int last_state = -1;
229         public void show(final AltosState state, final int crc_errors) {
230                 // if insufficient gps data, nothing to update
231                 if (state.gps == null)
232                         return;
233                 if (state.pad_lat == 0 && state.pad_lon == 0)
234                         return;
235                 if (!state.gps.locked) {
236                         if (state.gps.nsat < 4)
237                                 return;
238                 }
239
240                 if (!initialised) {
241                         initMaps(state.pad_lat, state.pad_lon);
242                         initialised = true;
243                 }
244
245                 final Point2D.Double pt = pt(state.gps.lat, state.gps.lon);
246                 if (last_pt == pt && last_state == state.state)
247                         return;
248
249                 if (last_pt == null) {
250                         last_pt = pt;
251                 }
252                 boolean in_any = false;
253                 for (Point offset : mapTiles.keySet()) {
254                         AltosSiteMapTile tile = mapTiles.get(offset);
255                         Point2D.Double ref, lref;
256                         ref = translatePoint(pt, tileCoordOffset(offset));
257                         lref = translatePoint(last_pt, tileCoordOffset(offset));
258                         tile.show(state, crc_errors, lref, ref);
259                         if (0 <= ref.x && ref.x < px_size)
260                                 if (0 <= ref.y && ref.y < px_size)
261                                         in_any = true;
262                 }
263
264                 Point offset = tileOffset(pt);
265                 if (!in_any) {
266                         Point2D.Double ref, lref;
267                         ref = translatePoint(pt, tileCoordOffset(offset));
268                         lref = translatePoint(last_pt, tileCoordOffset(offset));
269
270                         AltosSiteMapTile tile = createTile(offset);
271                         tile.show(state, crc_errors, lref, ref);
272                         initMap(tile, offset);
273                         finishTileLater(tile, offset);
274                 }
275
276                 scrollRocketToVisible(pt);
277
278                 if (offset != tileOffset(last_pt)) {
279                         ensureTilesAround(offset);
280                 }
281
282                 last_pt = pt;
283                 last_state = state.state;
284         }
285
286         private AltosSiteMapTile createTile(Point offset) {
287                 AltosSiteMapTile tile = new AltosSiteMapTile(px_size);
288                 mapTiles.put(offset, tile);
289                 return tile;
290         }
291         private void finishTileLater(final AltosSiteMapTile tile,
292                                      final Point offset)
293         {
294                 SwingUtilities.invokeLater( new Runnable() {
295                         public void run() {
296                                 addTileAt(tile, offset);
297                         }
298                 } );
299         }
300
301         private void ensureTilesAround(Point base_offset) {
302                 for (int x = -1; x <= 1; x++) {
303                         for (int y = -1; y <= 1; y++) {
304                                 Point offset = new Point(base_offset.x + x, base_offset.y + y);
305                                 if (mapTiles.containsKey(offset))
306                                         continue;
307                                 AltosSiteMapTile tile = createTile(offset);
308                                 initMap(tile, offset);
309                                 finishTileLater(tile, offset);
310                         }
311                 }
312         }
313
314         private Point topleft = new Point(0,0);
315         private void scrollRocketToVisible(Point2D.Double pt) {
316                 Rectangle r = comp.getVisibleRect();
317                 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
318                 int dx = (int)copt.x - r.width/2 - r.x;
319                 int dy = (int)copt.y - r.height/2 - r.y;
320                 if (Math.abs(dx) > r.width/3 || Math.abs(dy) > r.height/3) {
321                         r.x += dx;
322                         r.y += dy;
323                         comp.scrollRectToVisible(r);
324                 }
325         }
326
327         private void addTileAt(AltosSiteMapTile tile, Point offset) {
328                 if (Math.abs(offset.x) >= MAX_TILE_DELTA ||
329                                 Math.abs(offset.y) >= MAX_TILE_DELTA)
330                 {
331                         System.out.printf("Rocket too far away from pad (tile %d,%d)\n",
332                                           offset.x, offset.y);
333                         return;
334                 }
335
336                 boolean review = false;
337                 Rectangle r = comp.getVisibleRect();
338                 if (offset.x < topleft.x) {
339                         r.x += (topleft.x - offset.x) * px_size;
340                         topleft.x = offset.x;
341                         review = true;
342                 }
343                 if (offset.y < topleft.y) {
344                         r.y += (topleft.y - offset.y) * px_size;
345                         topleft.y = offset.y;
346                         review = true;
347                 }
348                 GridBagConstraints c = new GridBagConstraints();
349                 c.anchor = GridBagConstraints.CENTER;
350                 c.fill = GridBagConstraints.BOTH;
351                 // put some space between the map tiles, debugging only
352                 // c.insets = new Insets(5, 5, 5, 5);
353
354                 c.gridx = offset.x + MAX_TILE_DELTA;
355                 c.gridy = offset.y + MAX_TILE_DELTA;
356                 layout.setConstraints(tile, c);
357
358                 comp.add(tile);
359                 if (review) {
360                         comp.scrollRectToVisible(r);
361                 }
362         }
363
364         private AltosSiteMap(boolean knowWhatYouAreDoing) {
365                 if (!knowWhatYouAreDoing) {
366                         throw new RuntimeException("Arggh.");
367                 }
368         }
369
370         JComponent comp = new JComponent() { };
371         private GridBagLayout layout = new GridBagLayout();
372
373         public AltosSiteMap() {
374                 GrabNDrag scroller = new GrabNDrag(comp);
375
376                 comp.setLayout(layout);
377
378                 for (int x = -1; x <= 1; x++) {
379                         for (int y = -1; y <= 1; y++) {
380                                 Point offset = new Point(x, y);
381                                 AltosSiteMapTile t = createTile(offset);
382                                 addTileAt(t, offset);
383                         }
384                 }
385                 setViewportView(comp);
386                 setPreferredSize(new Dimension(500,200));
387         }
388 }