Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

GridPatternCache.ts

248 lines8.1 KB

1/**
2 * Cache for the tiled grid line pattern.
3 * Pre-renders multi-cell tiles at different scale levels for crisp rendering.
4 *
5 * Using a larger tile (4x4 cells) provides more variation in the wobbly
6 * edges before the pattern repeats, making it look more natural.
7 */
8​
9import { GRID_HEIGHT, GRID_WIDTH } from "../../../shared/game-config"
10import { drawWobblyLine } from "../../lib/hand-drawn"
11​
12// A solid Neon docs gray keeps cached grid lines crisp on the light board.
13const UNPLACED_COLOR = `#E4E5E7`
14​
15// Tile covers multiple grid cells for more variation
16const TILE_CELLS = 4
17​
18// Cache tiles at different cell sizes for crisp rendering at different zoom levels
19interface CacheEntry {
20 canvas: OffscreenCanvas
21 lastUsed: number
23const tileCache = new Map<string, CacheEntry>()
24​
25// Available cell sizes to cache (covers typical zoom range)
26// We'll pick the closest one that's >= the target size (scale down, not up)
27const CACHED_CELL_SIZES = [16, 32, 64, 128, 256]
28​
29// Dispose tiles not used within this time (in ms)
30const CACHE_TTL = 5_000 // 5 seconds
31​
32// Cleanup interval
33let cleanupTimer: ReturnType<typeof setInterval> | null = null
34​
35// Track the currently active tile size (never evict this one)
36let currentTileKey: string | null = null
37​
38function startCleanupTimer(): void {
39 if (cleanupTimer) return
40 cleanupTimer = setInterval(() => {
41 const now = Date.now()
42 for (const [key, entry] of tileCache) {
43 // Never evict the currently active tile
44 if (key === currentTileKey) continue
45 if (now - entry.lastUsed > CACHE_TTL) {
46 tileCache.delete(key)
47 }
48 }
49 // Stop timer if cache is empty
50 if (tileCache.size === 0 && cleanupTimer) {
51 clearInterval(cleanupTimer)
52 cleanupTimer = null
53 }
54 }, 10_000) // Check every 10 seconds
56​
57/**
58 * Get the best cached cell size for the given target size.
59 * Returns the smallest cached size that's >= target (to scale down, not up).
60 */
61function getBestCellSize(targetSize: number): number {
62 for (const size of CACHED_CELL_SIZES) {
63 if (size >= targetSize) return size
64 }
65 // If target is larger than our biggest, use the biggest
66 return CACHED_CELL_SIZES[CACHED_CELL_SIZES.length - 1]
68​
69/**
70 * Create a tile canvas at the specified cell size.
71 *
72 * The tile origin is offset by half a cell, so the tile covers grid positions
73 * from (-0.5, -0.5) to (TILE_CELLS - 0.5, TILE_CELLS - 0.5).
74 * This means edges at integer grid positions (0, 1, 2, 3) are fully inside
75 * the tile with their wobble, and tile seams fall at cell centers where
76 * there's nothing to render.
77 */
78function createTile(cellSize: number, pixelRatio: number): OffscreenCanvas | null {
79 const tileSize = TILE_CELLS * cellSize
80 // Render logical tile geometry into a Retina-sized texture. Use the actual
81 // rounded density so fractional display ratios cannot introduce tile seams.
82 const pixelSize = Math.ceil(tileSize * pixelRatio)
83 const canvas = new OffscreenCanvas(pixelSize, pixelSize)
84 const ctx = canvas.getContext(`2d`)
85 if (!ctx) return null
86 ctx.scale(pixelSize / tileSize, pixelSize / tileSize)
87​
88 // Setup style for grid lines - minimum 0.5px for very small sizes
89 const lineWidth = Math.max(0.5, cellSize * 0.1)
90 ctx.strokeStyle = UNPLACED_COLOR
91 ctx.lineWidth = lineWidth * 0.5
92 ctx.lineCap = `round`
93 ctx.setLineDash([2, 4])
94​
95 // Offset: tile position 0 = grid position -0.5
96 // So grid position 0 = tile position 0.5 * cellSize
97 const offset = cellSize / 2
98​
99 let seed = 0
100​
101 // Draw horizontal edges
102 // Grid rows 0, 1, 2, 3 are at tile positions offset, offset+cellSize, etc.
103 for (let row = 0; row < TILE_CELLS; row++) {
104 const y = offset + row * cellSize
105 for (let col = 0; col < TILE_CELLS; col++) {
106 // Each edge spans one cell width
107 const x1 = offset + col * cellSize - cellSize / 2
108 const x2 = offset + col * cellSize + cellSize / 2
109 drawWobblyLine(ctx, x1, y, x2, y, lineWidth * 0.5, seed++)
110 }
111 }
112​
113 // Draw vertical edges
114 for (let col = 0; col < TILE_CELLS; col++) {
115 const x = offset + col * cellSize
116 for (let row = 0; row < TILE_CELLS; row++) {
117 const y1 = offset + row * cellSize - cellSize / 2
118 const y2 = offset + row * cellSize + cellSize / 2
119 drawWobblyLine(ctx, x, y1, x, y2, lineWidth * 0.5, seed++)
120 }
121 }
122​
123 return canvas
125​
126/**
127 * Get or create a cached tile at the appropriate size.
128 */
129function getTile(
130 targetCellSize: number,
131 pixelRatio: number,
132): {
133 canvas: OffscreenCanvas
134 cellSize: number
135 pixelRatio: number
136} | null {
137 const cellSize = getBestCellSize(targetCellSize)
138​
139 // Track current tile size so it's never evicted
140 const key = `${cellSize}:${pixelRatio}`
141 currentTileKey = key
142​
143 let entry = tileCache.get(key)
144 if (entry) {
145 // Update last used time
146 entry.lastUsed = Date.now()
147 } else {
148 const canvas = createTile(cellSize, pixelRatio)
149 if (canvas) {
150 entry = { canvas, lastUsed: Date.now() }
151 tileCache.set(key, entry)
152 startCleanupTimer()
153 }
154 }
155​
156 if (!entry) return null
157 return {
158 canvas: entry.canvas,
159 cellSize,
160 pixelRatio: entry.canvas.width / (TILE_CELLS * cellSize),
161 }
163​
164/**
165 * Render the grid pattern across the visible area.
166 * Uses pattern.setTransform() to scale the pattern to match the current grid size.
167 * Clips to the playable area boundaries to prevent overflow.
168 */
169export function renderGridPattern(
170 ctx: CanvasRenderingContext2D,
171 gridSize: number,
172 viewCenterX: number,
173 viewCenterY: number,
174 canvasWidth: number,
175 canvasHeight: number,
176): void {
177 // Don't render grid at very small sizes
178 if (gridSize < 2) return
179​
180 // The canvas transform carries its backing-store density; gridSize remains
181 // in CSS pixels so dot sizes, dash lengths and the sketch stay unchanged.
182 const matrixScale = ctx.getTransform()
183 const density = Math.hypot(matrixScale.a, matrixScale.b) || 1
184 const tileData = getTile(gridSize, density)
185 if (!tileData) return
186​
187 const { canvas, cellSize, pixelRatio } = tileData
188​
189 const pattern = ctx.createPattern(canvas, `repeat`)
190 if (!pattern) return
191​
192 // Calculate scale factor to make each cell in the tile match the current grid size
193 // Since we pick a cellSize >= gridSize, this scale is usually <= 1 (scaling down)
194 const scale = gridSize / (cellSize * pixelRatio)
195​
196 // World (0,0) in screen coordinates
197 const worldOriginX = canvasWidth / 2 - viewCenterX * gridSize
198 const worldOriginY = canvasHeight / 2 - viewCenterY * gridSize
199​
200 // The tile is offset by half a cell (tile origin = grid position -0.5)
201 // So we need to shift the pattern by -0.5 cells to align grid position 0
202 // with tile position offset (which is cellSize/2)
203 const tileOffset = (cellSize * pixelRatio) / 2
204​
205 // Use pattern.setTransform to scale and position the pattern correctly
206 // This transforms the pattern itself, not the fill coordinates
207 const matrix = new DOMMatrix()
208 .translate(worldOriginX, worldOriginY)
209 .scale(scale, scale)
210 .translate(-tileOffset, -tileOffset)
211​
212 pattern.setTransform(matrix)
213​
214 // Calculate the playable area bounds in screen coordinates
215 // The grid lines exist from (0,0) to (W,H) in world coordinates
216 // Expand by a small margin (half dot radius) to show full line width at edges
217 // This is enough to show the line thickness without showing extra line segments
218 const lineMargin = 0.1 * gridSize
219 const boundsMinX = worldOriginX - lineMargin
220 const boundsMinY = worldOriginY - lineMargin
221 const boundsMaxX = worldOriginX + GRID_WIDTH * gridSize + lineMargin
222 const boundsMaxY = worldOriginY + GRID_HEIGHT * gridSize + lineMargin
223​
224 // Clip to visible canvas area
225 const fillX = Math.max(0, boundsMinX)
226 const fillY = Math.max(0, boundsMinY)
227 const fillMaxX = Math.min(canvasWidth, boundsMaxX)
228 const fillMaxY = Math.min(canvasHeight, boundsMaxY)
229 const fillW = fillMaxX - fillX
230 const fillH = fillMaxY - fillY
231​
232 // Only render if there's something visible
233 if (fillW > 0 && fillH > 0) {
234 ctx.fillStyle = pattern
235 ctx.fillRect(fillX, fillY, fillW, fillH)
236 }
238​
239/**
240 * Clear the tile cache (if needed for memory management).
241 */
242export function clearGridPatternCache(): void {
243 tileCache.clear()
244 if (cleanupTimer) {
245 clearInterval(cleanupTimer)
246 cleanupTimer = null
247 }