1 package tim.prune.gui.map;
6 * Class to act as a memory-based map tile cache
7 * For caching of tiles on disk, see the DiskTileCacher class.
9 public class MemTileCacher
11 /** Array of images to hold tiles */
12 private Image[] _tiles = new Image[GRID_SIZE * GRID_SIZE];
13 /** Current zoom level */
14 private int _zoom = -1;
15 /** X coordinate of central tile */
16 private int _tileX = -1;
17 /** Y coordinate of central tile */
18 private int _tileY = -1;
19 /** X coord of grid centre */
20 private int _gridCentreX = 0;
21 /** Y coord of grid centre */
22 private int _gridCentreY = 0;
25 private static final int GRID_SIZE = 15;
28 * Recentre the map and clear the cache
29 * @param inZoom zoom level
30 * @param inTileX x coord of central tile
31 * @param inTileY y coord of central tile
33 public void centreMap(int inZoom, int inTileX, int inTileY)
35 int shift = Math.max(Math.abs(inTileX-_tileX), Math.abs(inTileY - _tileY));
36 if (shift == 0) {return;}
37 // Clear cache if either zoom has changed or map has jumped too far
38 if (inZoom != _zoom || shift > GRID_SIZE/2)
43 _gridCentreX = getCacheCoordinate(_gridCentreX + inTileX - _tileX);
44 _gridCentreY = getCacheCoordinate(_gridCentreY + inTileY - _tileY);
47 // Mark boundaries as invalid
48 for (int i=0; i<GRID_SIZE; i++)
50 _tiles[getArrayIndex(_tileX + GRID_SIZE/2 + 1, _tileY + i - GRID_SIZE/2)] = null;
51 _tiles[getArrayIndex(_tileX + i - GRID_SIZE/2, _tileY + GRID_SIZE/2 + 1)] = null;
56 * Transform a coordinate from map tiles to array coordinates
57 * @param inTile coordinate of tile
58 * @return coordinate in array (wrapping around cache grid)
60 private static int getCacheCoordinate(int inTile)
63 while (tile >= GRID_SIZE) {tile -= GRID_SIZE;}
64 while (tile < 0) {tile += GRID_SIZE;}
69 * Get the array index for the given coordinates
70 * @param inX x coord of tile
71 * @param inY y coord of tile
74 private int getArrayIndex(int inX, int inY)
76 //System.out.println("Getting array index for (" + inX + ", " + inY + ") where the centre is at (" + _tileX + ", " + _tileY
77 // + ") and grid coords (" + _gridCentreX + ", " + _gridCentreY + ")");
78 int x = getCacheCoordinate(inX - _tileX + _gridCentreX);
79 int y = getCacheCoordinate(inY - _tileY + _gridCentreY);
80 //System.out.println("Transformed to (" + x + ", " + y + ")");
81 return (x + y * GRID_SIZE);
85 * Clear all the cached images
87 public void clearAll()
89 // Clear all images if zoom changed
90 for (int i=0; i<_tiles.length; i++) {
96 * @param inX x index of tile
97 * @param inY y index of tile
98 * @return selected tile if already loaded, or null otherwise
100 public Image getTile(int inX, int inY)
102 return _tiles[getArrayIndex(inX, inY)];
106 * Save the specified tile at the given coordinates
107 * @param inTile image to save
108 * @param inX x coordinate of tile
109 * @param inY y coordinate of tile
111 public void setTile(Image inTile, int inX, int inY)
113 _tiles[getArrayIndex(inX, inY)] = inTile;