Open History to see the last commit
1import { getScale, getVisibleBounds, worldToScreen } from "../../lib/view-transform"
2import type { ViewState } from "../../hooks/useViewState"
3import type { GameState } from "../../../shared/game-state"
4import type { BoxBitmap } from "../../lib/box-bitmap"
5
6/**
7 * Render all visible claimed boxes on the canvas.
8 * Always uses GPU-accelerated bitmap scaling for performance.
9 * Nearest-neighbor scaling when zoomed in gives crisp pixel edges.
10 */
11export function renderBoxes(
12 ctx: CanvasRenderingContext2D,
13 _gameState: GameState,
14 view: ViewState,
15 canvasWidth: number,
16 canvasHeight: number,
17 boxBitmap?: BoxBitmap,
18): void {
19 if (!boxBitmap) return
20
21 renderBitmapMode(ctx, view, canvasWidth, canvasHeight, boxBitmap)
22}
23
24// Opacity for box fills - gives a softer, watercolor-like appearance
25const BOX_FILL_OPACITY = 0.5
26// Higher opacity when edges are not rendered (very zoomed out)
27const BOX_FILL_OPACITY_NO_EDGES = 0.8
28// Threshold below which edges are not rendered
29const EDGE_RENDER_THRESHOLD = 2
30
31/**
32 * Bitmap rendering mode: Draw the visible portion of the BoxBitmap scaled to screen.
33 * Uses different scaling modes based on box size:
34 * - Boxes < 1px: Smooth scaling for proper color blending (many boxes → one pixel)
35 * - Boxes >= 1px: Crisp nearest-neighbor scaling for sharp pixels
36 */
37function renderBitmapMode(
38 ctx: CanvasRenderingContext2D,
39 view: ViewState,
40 canvasWidth: number,
41 canvasHeight: number,
42 boxBitmap: BoxBitmap,
43): void {
44 const bounds = getVisibleBounds(view, canvasWidth, canvasHeight)
45 const scale = getScale(view)
46
47 // Calculate source rectangle (in world/box coordinates)
48 const srcX = bounds.minX
49 const srcY = bounds.minY
50 const srcWidth = bounds.maxX - bounds.minX
51 const srcHeight = bounds.maxY - bounds.minY
52
53 // Calculate where this maps to on screen
54 const topLeft = worldToScreen(bounds.minX, bounds.minY, view, canvasWidth, canvasHeight)
55
56 // Use smooth scaling only when zoomed out (boxes < 1px)
57 // When boxes are >= 1px, use crisp nearest-neighbor for sharp pixels
58 const useSmooth = scale < 1
59
60 // Apply transparency for softer, watercolor-like appearance
61 // Use higher opacity when edges are not rendered (very zoomed out)
62 const prevAlpha = ctx.globalAlpha
63 ctx.globalAlpha = scale < EDGE_RENDER_THRESHOLD ? BOX_FILL_OPACITY_NO_EDGES : BOX_FILL_OPACITY
64
65 // Draw the visible portion scaled to fit
66 boxBitmap.drawViewport(
67 ctx,
68 srcX,
69 srcY,
70 srcWidth,
71 srcHeight,
72 topLeft.x,
73 topLeft.y,
74 srcWidth * scale,
75 srcHeight * scale,
76 useSmooth,
77 )
78
79 // Restore alpha
80 ctx.globalAlpha = prevAlpha
81}