]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/gui/map/MapTileCacher.java
Version 6, October 2008
[GpsPrune.git] / tim / prune / gui / map / MapTileCacher.java
1 package tim.prune.gui.map;
2
3 import java.awt.Image;
4 import java.awt.Toolkit;
5 import java.awt.image.ImageObserver;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8
9
10 /**
11  * Class to handle the caching of map tiles from openstreetmap
12  */
13 public class MapTileCacher implements ImageObserver
14 {
15         /** Parent to be informed of updates */
16         private MapCanvas _parent = null;
17         /** Default grid size */
18         private static final int GRID_SIZE = 11;
19         /** Array of images to hold tiles */
20         private Image[] _tiles = new Image[GRID_SIZE * GRID_SIZE];
21         /** Current zoom level */
22         private int _zoom = -1;
23         /** X coordinate of central tile */
24         private int _tileX = -1;
25         /** Y coordinate of central tile */
26         private int _tileY = -1;
27         /** X coord of grid centre */
28         private int _gridCentreX = 0;
29         /** Y coord of grid centre */
30         private int _gridCentreY = 0;
31
32
33         /**
34          * Constructor
35          * @param inParent parent canvas to be informed of updates
36          */
37         public MapTileCacher(MapCanvas inParent)
38         {
39                 _parent = inParent;
40         }
41
42         /**
43          * Recentre the map and clear the cache
44          * @param inZoom zoom level
45          * @param inTileX x coord of central tile
46          * @param inTileY y coord of central tile
47          */
48         public void centreMap(int inZoom, int inTileX, int inTileY)
49         {
50                 if (inZoom != _zoom)
51                 {
52                         _zoom = inZoom;
53                         clearAll();
54                 }
55                 _gridCentreX = getCacheCoordinate(_gridCentreX + inTileX - _tileX);
56                 _gridCentreY = getCacheCoordinate(_gridCentreY + inTileY - _tileY);
57                 _tileX = inTileX;
58                 _tileY = inTileY;
59                 // Mark boundaries as invalid
60                 for (int i=0; i<GRID_SIZE; i++)
61                 {
62                         _tiles[getArrayIndex(_tileX + GRID_SIZE/2 + 1, _tileY + i - GRID_SIZE/2)] = null;
63                         _tiles[getArrayIndex(_tileX + i - GRID_SIZE/2, _tileY + GRID_SIZE/2 + 1)] = null;
64                 }
65         }
66
67         /**
68          * Clear all the cached images
69          */
70         public void clearAll()
71         {
72                 // Clear all images if zoom changed
73                 for (int i=0; i<_tiles.length; i++) {
74                         _tiles[i] = null;
75                 }
76         }
77
78         /**
79          * @param inX x index of tile
80          * @param inY y index of tile
81          * @return selected tile if already loaded, or null otherwise
82          */
83         public Image getTile(int inX, int inY)
84         {
85                 int arrayIndex = getArrayIndex(inX, inY);
86                 Image image = _tiles[arrayIndex];
87                 if (image != null)
88                 {
89                         // image already finished loading so return it
90                         return image;
91                 }
92
93                 // Trigger load if not already triggered
94                 // Work out tile coords for URL
95                 int urlX = getUrlCoordinate(inX, _zoom);
96                 int urlY = getUrlCoordinate(inY, _zoom);
97                 try
98                 {
99                         String url = "http://tile.openstreetmap.org/" + _zoom + "/" + urlX + "/" + urlY + ".png";
100                         // Load image asynchronously, using observer
101                         image = Toolkit.getDefaultToolkit().createImage(new URL(url));
102                         _tiles[arrayIndex] = image;
103                         if (image.getWidth(this) > 0) {return image;}
104                 }
105                 catch (MalformedURLException urle) {} // ignore
106                 return null;
107         }
108
109
110         /**
111          * Get the array index for the given coordinates
112          * @param inX x coord of tile
113          * @param inY y coord of tile
114          * @return array index
115          */
116         private int getArrayIndex(int inX, int inY)
117         {
118                 //System.out.println("Getting array index for (" + inX + ", " + inY + ") where the centre is at ("  + _tileX + ", " + _tileY
119                 //      + ") and grid coords (" + _gridCentreX + ", " + _gridCentreY + ")");
120                 int x = getCacheCoordinate(inX - _tileX + _gridCentreX);
121                 int y = getCacheCoordinate(inY - _tileY + _gridCentreY);
122                 //System.out.println("Transformed to (" + x + ", " + y + ")");
123                 return (x + y * GRID_SIZE);
124         }
125
126         /**
127          * Transform a coordinate from map tiles to array coordinates
128          * @param inTile coordinate of tile
129          * @return coordinate in array (wrapping around cache grid)
130          */
131         private static int getCacheCoordinate(int inTile)
132         {
133                 int tile = inTile;
134                 while (tile >= GRID_SIZE) {tile -= GRID_SIZE;}
135                 while (tile < 0) {tile += GRID_SIZE;}
136                 return tile;
137         }
138
139         /**
140          * Make sure a url coordinate is within range
141          * @param inTile coordinate of tile in map system
142          * @param inZoom zoom factor
143          * @return coordinate for url (either vertical or horizontal)
144          */
145         private static int getUrlCoordinate(int inTile, int inZoom)
146         {
147                 int mapSize = 1 << inZoom;
148                 int coord = inTile;
149                 while (coord >= mapSize) {coord -= mapSize;}
150                 while (coord < 0) {coord += mapSize;}
151                 // coord is now between 0 and mapsize
152                 return coord;
153         }
154
155         /**
156          * Convert to string for debug
157          * @see java.lang.Object#toString()
158          */
159         public String toString()
160         {
161                 StringBuffer result = new StringBuffer("Grid centre (" + _gridCentreX + "," + _gridCentreY + ") - (" + _tileX + "," + _tileY + ")\n");
162                 for (int i=0; i<GRID_SIZE; i++)
163                 {
164                         for (int j=0; j<GRID_SIZE; j++) {
165                                 if (i == _gridCentreY && j == _gridCentreX) {
166                                         result.append(_tiles[j + i*GRID_SIZE] == null?"c":"C");
167                                 }
168                                 else {
169                                         result.append(_tiles[j + i*GRID_SIZE] == null?".":"*");
170                                 }
171                         }
172                         result.append("\n");
173                 }
174                 return result.toString();
175         }
176
177         /**
178          * Method called by image loader to inform of updates to the tiles
179          * @param img the image
180          * @param infoflags flags describing how much of the image is known
181          * @param x ignored
182          * @param y ignored
183          * @param width ignored
184          * @param height ignored
185          * @return false to carry on loading, true to stop
186          */
187         public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
188         {
189                 boolean loaded = (infoflags & ImageObserver.ALLBITS) > 0;
190                 boolean error = (infoflags & ImageObserver.ERROR) > 0;
191                 if (loaded || error) {
192                         _parent.tilesUpdated(loaded);
193                 }
194                 return !loaded;
195         }
196 }