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

box-bitmap.ts

237 lines7.3 KB

1import { GRID_HEIGHT, GRID_WIDTH } from "./config"
2​
3/**
4 * RGB color values for each team.
5 * Matches the primary colors from teams.ts but in RGB format.
6 */
7const TEAM_COLORS_RGB: Array<{ r: number; g: number; b: number }> = [
8 { r: 229, g: 57, b: 53 }, // RED: #E53935
9 { r: 30, g: 136, b: 229 }, // BLUE: #1E88E5
10 { r: 67, g: 160, b: 71 }, // GREEN: #43A047
11 { r: 253, g: 216, b: 53 }, // YELLOW: #FDD835
13​
14// Background color for unclaimed boxes
15const BG_COLOR = { r: 250, g: 250, b: 250 } // Match the main canvas and --color-bg
16​
17/**
18 * BoxBitmap maintains a 1000x1000 pixel ImageData buffer where each pixel
19 * represents one box in the game. This provides:
20 *
21 * 1. Incremental updates - only changed pixels are updated
22 * 2. Shared rendering source - used by both minimap and main canvas
23 * 3. Efficient scaling - canvas drawImage handles GPU-accelerated scaling
24 */
25export class BoxBitmap {
26 private imageData: ImageData
27 private offscreenCanvas: OffscreenCanvas | HTMLCanvasElement
28 private ctx: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D
29​
30 constructor() {
31 // Create ImageData at full game resolution (1px per box)
32 this.imageData = new ImageData(GRID_WIDTH, GRID_HEIGHT)
33​
34 // Fill with background color
35 const data = this.imageData.data
36 for (let i = 0; i < GRID_WIDTH * GRID_HEIGHT; i++) {
37 const idx = i * 4
38 data[idx] = BG_COLOR.r
39 data[idx + 1] = BG_COLOR.g
40 data[idx + 2] = BG_COLOR.b
41 data[idx + 3] = 255
42 }
43​
44 // Create offscreen canvas for efficient drawImage operations
45 if (typeof OffscreenCanvas !== `undefined`) {
46 this.offscreenCanvas = new OffscreenCanvas(GRID_WIDTH, GRID_HEIGHT)
47 this.ctx = this.offscreenCanvas.getContext(`2d`)!
48 } else {
49 // Fallback for browsers without OffscreenCanvas
50 this.offscreenCanvas = document.createElement(`canvas`)
51 this.offscreenCanvas.width = GRID_WIDTH
52 this.offscreenCanvas.height = GRID_HEIGHT
53 this.ctx = this.offscreenCanvas.getContext(`2d`)!
54 }
55​
56 // Put initial image data
57 this.ctx.putImageData(this.imageData, 0, 0)
58 }
59​
60 /**
61 * Update a single box pixel. Called when a box is claimed.
62 * @param boxId The box ID (0 to 999,999)
63 * @param teamId The team ID (0-3) that claimed the box
64 */
65 updateBox(boxId: number, teamId: number): void {
66 const color = TEAM_COLORS_RGB[teamId] ?? BG_COLOR
67 const idx = boxId * 4
68 const data = this.imageData.data
69​
70 data[idx] = color.r
71 data[idx + 1] = color.g
72 data[idx + 2] = color.b
73 // Alpha is already 255
74 }
75​
76 /**
77 * Batch update multiple boxes at once.
78 * More efficient than calling updateBox repeatedly.
79 */
80 updateBoxes(boxes: Array<{ boxId: number; teamId: number }>): void {
81 const data = this.imageData.data
82​
83 for (const { boxId, teamId } of boxes) {
84 const color = TEAM_COLORS_RGB[teamId]
85 const idx = boxId * 4
86 data[idx] = color.r
87 data[idx + 1] = color.g
88 data[idx + 2] = color.b
89 }
90 }
91​
92 /**
93 * Commit pending changes to the offscreen canvas.
94 * Call this after a batch of updateBox/updateBoxes calls.
95 */
96 commit(): void {
97 this.ctx.putImageData(this.imageData, 0, 0)
98 }
99​
100 /**
101 * Rebuild the entire bitmap from a GameState.
102 * Used when installing a complete board snapshot.
103 */
104 rebuildFromState(gameState: { getBoxOwner: (boxId: number) => number }): void {
105 const data = this.imageData.data
106 const totalBoxes = GRID_WIDTH * GRID_HEIGHT
107​
108 for (let boxId = 0; boxId < totalBoxes; boxId++) {
109 const owner = gameState.getBoxOwner(boxId)
110 const idx = boxId * 4
111​
112 if (owner > 0) {
113 const color = TEAM_COLORS_RGB[owner - 1]
114 data[idx] = color.r
115 data[idx + 1] = color.g
116 data[idx + 2] = color.b
117 } else {
118 data[idx] = BG_COLOR.r
119 data[idx + 1] = BG_COLOR.g
120 data[idx + 2] = BG_COLOR.b
121 }
122 data[idx + 3] = 255
123 }
124​
125 this.commit()
126 }
127​
128 /**
129 * Get the canvas source for drawing.
130 * Use this with ctx.drawImage() for efficient scaled rendering.
131 */
132 getCanvas(): OffscreenCanvas | HTMLCanvasElement {
133 return this.offscreenCanvas
134 }
135​
136 /**
137 * Get the raw ImageData for direct pixel access.
138 */
139 getImageData(): ImageData {
140 return this.imageData
141 }
142​
143 /**
144 * Draw the full bitmap to a destination canvas, scaled to fit.
145 * @param destCtx Destination canvas context
146 * @param destX Destination X position
147 * @param destY Destination Y position
148 * @param destWidth Destination width
149 * @param destHeight Destination height
150 * @param smooth Whether to use image smoothing (true for minimap, depends on zoom for main)
151 */
152 drawScaled(
153 destCtx: CanvasRenderingContext2D,
154 destX: number,
155 destY: number,
156 destWidth: number,
157 destHeight: number,
158 smooth: boolean = true,
159 ): void {
160 // Nearest-neighbour sampling belongs only to the box bitmap. Restore the
161 // caller's sampling so cached grid/dot textures remain antialiased.
162 destCtx.save()
163 destCtx.imageSmoothingEnabled = smooth
164 destCtx.imageSmoothingQuality = smooth ? `high` : `low`
165 destCtx.drawImage(
166 this.offscreenCanvas,
167 0,
168 0,
169 GRID_WIDTH,
170 GRID_HEIGHT,
171 destX,
172 destY,
173 destWidth,
174 destHeight,
175 )
176 destCtx.restore()
177 }
178​
179 /**
180 * Draw a portion of the bitmap to a destination canvas.
181 * Used for main canvas viewport rendering.
182 * @param destCtx Destination canvas context
183 * @param srcX Source X in world/box coordinates
184 * @param srcY Source Y in world/box coordinates
185 * @param srcWidth Source width in world/box coordinates
186 * @param srcHeight Source height in world/box coordinates
187 * @param destX Destination X position
188 * @param destY Destination Y position
189 * @param destWidth Destination width
190 * @param destHeight Destination height
191 * @param smooth Whether to use image smoothing
192 */
193 drawViewport(
194 destCtx: CanvasRenderingContext2D,
195 srcX: number,
196 srcY: number,
197 srcWidth: number,
198 srcHeight: number,
199 destX: number,
200 destY: number,
201 destWidth: number,
202 destHeight: number,
203 smooth: boolean = true,
204 ): void {
205 // Clamp source coordinates to valid range
206 const clampedSrcX = Math.max(0, Math.min(GRID_WIDTH, srcX))
207 const clampedSrcY = Math.max(0, Math.min(GRID_HEIGHT, srcY))
208 const clampedSrcWidth = Math.min(srcWidth, GRID_WIDTH - clampedSrcX)
209 const clampedSrcHeight = Math.min(srcHeight, GRID_HEIGHT - clampedSrcY)
210​
211 if (clampedSrcWidth <= 0 || clampedSrcHeight <= 0) return
212​
213 // Adjust destination if source was clamped
214 const offsetX = ((clampedSrcX - srcX) / srcWidth) * destWidth
215 const offsetY = ((clampedSrcY - srcY) / srcHeight) * destHeight
216 const adjustedDestWidth = (clampedSrcWidth / srcWidth) * destWidth
217 const adjustedDestHeight = (clampedSrcHeight / srcHeight) * destHeight
218​
219 // Nearest-neighbour sampling belongs only to the box bitmap. Restore the
220 // caller's sampling so cached grid/dot textures remain antialiased.
221 destCtx.save()
222 destCtx.imageSmoothingEnabled = smooth
223 destCtx.imageSmoothingQuality = smooth ? `high` : `low`
224 destCtx.drawImage(
225 this.offscreenCanvas,
226 clampedSrcX,
227 clampedSrcY,
228 clampedSrcWidth,
229 clampedSrcHeight,
230 destX + offsetX,
231 destY + offsetY,
232 adjustedDestWidth,
233 adjustedDestHeight,
234 )
235 destCtx.restore()
236 }