altosui: remove un-used imports
[fw/altos] / 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 javax.swing.*;
22 import java.io.*;
23 import java.lang.Math;
24 import java.awt.geom.Point2D;
25 import java.util.concurrent.*;
26 import org.altusmetrum.AltosLib.*;
27
28 public class AltosSiteMap extends JScrollPane implements AltosFlightDisplay {
29         // preferred vertical step in a tile in naut. miles
30         // will actually choose a step size between x and 2x, where this
31         // is 1.5x
32         static final double tile_size_nmi = 0.75;
33
34         static final int px_size = 512;
35
36         static final int MAX_TILE_DELTA = 100;
37
38         private static Point2D.Double translatePoint(Point2D.Double p,
39                         Point2D.Double d)
40         {
41                 return new Point2D.Double(p.x + d.x, p.y + d.y);
42         }
43
44         static class LatLng {
45                 public double lat, lng;
46                 public LatLng(double lat, double lng) {
47                         this.lat = lat;
48                         this.lng = lng;
49                 }
50         }
51
52         // based on google js
53         //  http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/10/main.js
54         // search for fromLatLngToPoint and fromPointToLatLng
55         private static Point2D.Double pt(LatLng latlng, int zoom) {
56                 double scale_x = 256/360.0 * Math.pow(2, zoom);
57                 double scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
58                 return pt(latlng, scale_x, scale_y);
59         }
60
61         private static Point2D.Double pt(LatLng latlng,
62                                          double scale_x, double scale_y)
63         {
64                 Point2D.Double res = new Point2D.Double();
65                 double e;
66
67                 res.x = latlng.lng * scale_x;
68
69                 e = Math.sin(Math.toRadians(latlng.lat));
70                 e = Math.max(e,-(1-1.0E-15));
71                 e = Math.min(e,  1-1.0E-15 );
72
73                 res.y = 0.5*Math.log((1+e)/(1-e))*-scale_y;
74                 return res;
75         }
76
77         static private LatLng latlng(Point2D.Double pt,
78                                      double scale_x, double scale_y)
79         {
80                 double lat, lng;
81                 double rads;
82
83                 lng = pt.x/scale_x;
84                 rads = 2 * Math.atan(Math.exp(-pt.y/scale_y));
85                 lat = Math.toDegrees(rads - Math.PI/2);
86
87                 return new LatLng(lat,lng);
88         }
89
90         int zoom;
91         double scale_x, scale_y;
92
93         int radius;     /* half width/height of tiles to load */
94
95         private Point2D.Double pt(double lat, double lng) {
96                 return pt(new LatLng(lat, lng), scale_x, scale_y);
97         }
98
99         private LatLng latlng(double x, double y) {
100                 return latlng(new Point2D.Double(x,y), scale_x, scale_y);
101         }
102         private LatLng latlng(Point2D.Double pt) {
103                 return latlng(pt, scale_x, scale_y);
104         }
105
106         ConcurrentHashMap<Point,AltosSiteMapTile> mapTiles = new ConcurrentHashMap<Point,AltosSiteMapTile>();
107         Point2D.Double centre;
108
109         private Point2D.Double tileCoordOffset(Point p) {
110                 return new Point2D.Double(centre.x - p.x*px_size,
111                                           centre.y - p.y * px_size);
112         }
113
114         private Point tileOffset(Point2D.Double p) {
115                 return new Point((int)Math.floor((centre.x+p.x)/px_size),
116                                  (int)Math.floor((centre.y+p.y)/px_size));
117         }
118
119         private Point2D.Double getBaseLocation(double lat, double lng) {
120                 Point2D.Double locn, north_step;
121
122                 zoom = 2;
123                 // stupid loop structure to please Java's control flow analysis
124                 do {
125                         zoom++;
126                         scale_x = 256/360.0 * Math.pow(2, zoom);
127                         scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
128                         locn = pt(lat, lng);
129                         north_step = pt(lat+tile_size_nmi*4/3/60.0, lng);
130                         if (locn.y - north_step.y > px_size)
131                                 break;
132                 } while (zoom < 22);
133                 locn.x = -px_size * Math.floor(locn.x/px_size);
134                 locn.y = -px_size * Math.floor(locn.y/px_size);
135                 return locn;
136         }
137
138         public void reset() {
139                 // nothing
140         }
141
142         public void set_font() {
143                 // nothing
144         }
145
146         private void loadMap(final AltosSiteMapTile tile,
147                              File pngfile, String pngurl)
148         {
149                 final ImageIcon res = AltosSiteMapCache.fetchAndLoadMap(pngfile, pngurl);
150                 if (res != null) {
151                         SwingUtilities.invokeLater(new Runnable() {
152                                         public void run() {
153                                                 tile.loadMap(res);
154                                         }
155                                 });
156                 } else {
157                         System.out.printf("# Failed to fetch file %s\n", pngfile);
158                         System.out.printf(" wget -O '%s' '%s'\n", pngfile, pngurl);
159                 }
160         }
161
162         File pngfile;
163         String pngurl;
164
165         public int prefetchMap(int x, int y) {
166                 LatLng map_latlng = latlng(
167                         -centre.x + x*px_size + px_size/2,
168                         -centre.y + y*px_size + px_size/2);
169                 pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom);
170                 pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom);
171                 if (pngfile.exists()) {
172                         return 1;
173                 } else if (AltosSiteMapCache.fetchMap(pngfile, pngurl)) {
174                         return 0;
175                 } else {
176                         return -1;
177                 }
178         }
179
180         public static void prefetchMaps(double lat, double lng, int w, int h) {
181                 AltosSiteMap asm = new AltosSiteMap(true);
182                 asm.centre = asm.getBaseLocation(lat, lng);
183
184                 Point2D.Double p = new Point2D.Double();
185                 Point2D.Double p2;
186                 int dx = -w/2, dy = -h/2;
187                 for (int y = dy; y < h+dy; y++) {
188                         for (int x = dx; x < w+dx; x++) {
189                                 int r = asm.prefetchMap(x, y);
190                                 switch (r) {
191                                 case 1:
192                                         System.out.printf("Already have %s\n", asm.pngfile);
193                                         break;
194                                 case 0:
195                                         System.out.printf("Fetched map %s\n", asm.pngfile);
196                                         break;
197                                 case -1:
198                                         System.out.printf("# Failed to fetch file %s\n", asm.pngfile);
199                                         System.out.printf(" wget -O '%s' ''\n", asm.pngfile, asm.pngurl);
200                                         break;
201                                 }
202                         }
203                 }
204         }
205
206         public String initMap(Point offset) {
207                 AltosSiteMapTile tile = mapTiles.get(offset);
208                 Point2D.Double coord = tileCoordOffset(offset);
209
210                 LatLng map_latlng = latlng(px_size/2-coord.x, px_size/2-coord.y);
211
212                 File pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom);
213                 String pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom);
214                 loadMap(tile, pngfile, pngurl);
215                 return pngfile.toString();
216         }
217
218         public void setBaseLocation(double lat, double lng) {
219                 for (Point k : mapTiles.keySet()) {
220                         AltosSiteMapTile tile = mapTiles.get(k);
221                         tile.clearMap();
222                 }
223                         
224                 centre = getBaseLocation(lat, lng);
225                 scrollRocketToVisible(pt(lat,lng));
226         }
227
228         private void initMaps(double lat, double lng) {
229                 setBaseLocation(lat, lng);
230
231                 Thread thread = new Thread() {
232                                 public void run() {
233                                         for (Point k : mapTiles.keySet())
234                                                 initMap(k);
235                                 }
236                         };
237                 thread.start();
238         }
239
240         private static File MapFile(double lat, double lng, int zoom) {
241                 char chlat = lat < 0 ? 'S' : 'N';
242                 char chlng = lng < 0 ? 'W' : 'E';
243                 if (lat < 0) lat = -lat;
244                 if (lng < 0) lng = -lng;
245                 return new File(AltosUIPreferences.mapdir(),
246                                 String.format("map-%c%.6f,%c%.6f-%d.png",
247                                               chlat, lat, chlng, lng, zoom));
248         }
249
250         private static String MapURL(double lat, double lng, int zoom) {
251                 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);
252         }
253
254         boolean initialised = false;
255         Point2D.Double last_pt = null;
256         int last_state = -1;
257
258         public void show(double lat, double lon) {
259                 initMaps(lat, lon);
260                 scrollRocketToVisible(pt(lat, lon));
261         }
262         public void show(final AltosState state, final int crc_errors) {
263                 // if insufficient gps data, nothing to update
264                 if (!state.gps.locked && state.gps.nsat < 4)
265                         return;
266
267                 if (!initialised) {
268                         if (state.pad_lat != 0 || state.pad_lon != 0) {
269                                 initMaps(state.pad_lat, state.pad_lon);
270                                 initialised = true;
271                         } else if (state.gps.lat != 0 || state.gps.lon != 0) {
272                                 initMaps(state.gps.lat, state.gps.lon);
273                                 initialised = true;
274                         } else {
275                                 return;
276                         }
277                 }
278
279                 final Point2D.Double pt = pt(state.gps.lat, state.gps.lon);
280                 if (last_pt == pt && last_state == state.state)
281                         return;
282
283                 if (last_pt == null) {
284                         last_pt = pt;
285                 }
286                 boolean in_any = false;
287                 for (Point offset : mapTiles.keySet()) {
288                         AltosSiteMapTile tile = mapTiles.get(offset);
289                         Point2D.Double ref, lref;
290                         ref = translatePoint(pt, tileCoordOffset(offset));
291                         lref = translatePoint(last_pt, tileCoordOffset(offset));
292                         tile.show(state, crc_errors, lref, ref);
293                         if (0 <= ref.x && ref.x < px_size)
294                                 if (0 <= ref.y && ref.y < px_size)
295                                         in_any = true;
296                 }
297
298                 Point offset = tileOffset(pt);
299                 if (!in_any) {
300                         Point2D.Double ref, lref;
301                         ref = translatePoint(pt, tileCoordOffset(offset));
302                         lref = translatePoint(last_pt, tileCoordOffset(offset));
303
304                         AltosSiteMapTile tile = createTile(offset);
305                         tile.show(state, crc_errors, lref, ref);
306                         initMap(offset);
307                         finishTileLater(tile, offset);
308                 }
309
310                 scrollRocketToVisible(pt);
311
312                 if (offset != tileOffset(last_pt)) {
313                         ensureTilesAround(offset);
314                 }
315
316                 last_pt = pt;
317                 last_state = state.state;
318         }
319
320         public void draw_circle(double lat, double lon) {
321                 final Point2D.Double pt = pt(lat, lon);
322
323                 for (Point offset : mapTiles.keySet()) {
324                         AltosSiteMapTile tile = mapTiles.get(offset);
325                         Point2D.Double ref = translatePoint(pt, tileCoordOffset(offset));
326                         tile.draw_circle(ref);
327                 }
328         }
329
330         private AltosSiteMapTile createTile(Point offset) {
331                 AltosSiteMapTile tile = new AltosSiteMapTile(px_size);
332                 mapTiles.put(offset, tile);
333                 return tile;
334         }
335         private void finishTileLater(final AltosSiteMapTile tile,
336                                      final Point offset)
337         {
338                 SwingUtilities.invokeLater( new Runnable() {
339                         public void run() {
340                                 addTileAt(tile, offset);
341                         }
342                 } );
343         }
344
345         private void ensureTilesAround(Point base_offset) {
346                 for (int x = -radius; x <= radius; x++) {
347                         for (int y = -radius; y <= radius; y++) {
348                                 Point offset = new Point(base_offset.x + x, base_offset.y + y);
349                                 if (mapTiles.containsKey(offset))
350                                         continue;
351                                 AltosSiteMapTile tile = createTile(offset);
352                                 initMap(offset);
353                                 finishTileLater(tile, offset);
354                         }
355                 }
356         }
357
358         private Point topleft = new Point(0,0);
359         private void scrollRocketToVisible(Point2D.Double pt) {
360                 Rectangle r = comp.getVisibleRect();
361                 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
362                 int dx = (int)copt.x - r.width/2 - r.x;
363                 int dy = (int)copt.y - r.height/2 - r.y;
364                 if (Math.abs(dx) > r.width/4 || Math.abs(dy) > r.height/4) {
365                         r.x += dx;
366                         r.y += dy;
367                         comp.scrollRectToVisible(r);
368                 }
369         }
370
371         private void addTileAt(AltosSiteMapTile tile, Point offset) {
372                 if (Math.abs(offset.x) >= MAX_TILE_DELTA ||
373                                 Math.abs(offset.y) >= MAX_TILE_DELTA)
374                 {
375                         System.out.printf("Rocket too far away from pad (tile %d,%d)\n",
376                                           offset.x, offset.y);
377                         return;
378                 }
379
380                 boolean review = false;
381                 Rectangle r = comp.getVisibleRect();
382                 if (offset.x < topleft.x) {
383                         r.x += (topleft.x - offset.x) * px_size;
384                         topleft.x = offset.x;
385                         review = true;
386                 }
387                 if (offset.y < topleft.y) {
388                         r.y += (topleft.y - offset.y) * px_size;
389                         topleft.y = offset.y;
390                         review = true;
391                 }
392                 GridBagConstraints c = new GridBagConstraints();
393                 c.anchor = GridBagConstraints.CENTER;
394                 c.fill = GridBagConstraints.BOTH;
395                 // put some space between the map tiles, debugging only
396                 // c.insets = new Insets(5, 5, 5, 5);
397
398                 c.gridx = offset.x + MAX_TILE_DELTA;
399                 c.gridy = offset.y + MAX_TILE_DELTA;
400                 layout.setConstraints(tile, c);
401
402                 comp.add(tile);
403                 if (review) {
404                         comp.scrollRectToVisible(r);
405                 }
406         }
407
408         private AltosSiteMap(boolean knowWhatYouAreDoing) {
409                 if (!knowWhatYouAreDoing) {
410                         throw new RuntimeException("Arggh.");
411                 }
412         }
413
414         JComponent comp = new JComponent() { };
415         private GridBagLayout layout = new GridBagLayout();
416
417         public AltosSiteMap(int in_radius) {
418                 radius = in_radius;
419
420                 GrabNDrag scroller = new GrabNDrag(comp);
421
422                 comp.setLayout(layout);
423
424                 for (int x = -radius; x <= radius; x++) {
425                         for (int y = -radius; y <= radius; y++) {
426                                 Point offset = new Point(x, y);
427                                 AltosSiteMapTile t = createTile(offset);
428                                 addTileAt(t, offset);
429                         }
430                 }
431                 setViewportView(comp);
432                 setPreferredSize(new Dimension(500,500));
433         }
434
435         public AltosSiteMap() {
436                 this(1);
437         }
438 }