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