Open History to see the last commit
1import { DOT_SPACING } from "./config"
2import type { ViewState } from "../hooks/useViewState"
3
4/**
5 * Get the effective scale factor (pixels per grid unit).
6 * At zoom=1, each grid cell is DOT_SPACING pixels.
7 */
8export function getScale(view: ViewState): number {
9 return view.zoom * DOT_SPACING
10}
11
12/**
13 * Convert world coordinates to screen coordinates.
14 */
15export function worldToScreen(
16 wx: number,
17 wy: number,
18 view: ViewState,
19 canvasWidth: number,
20 canvasHeight: number,
21): { x: number; y: number } {
22 const cx = canvasWidth / 2
23 const cy = canvasHeight / 2
24 const scale = getScale(view)
25 return {
26 x: cx + (wx - view.centerX) * scale,
27 y: cy + (wy - view.centerY) * scale,
28 }
29}
30
31/**
32 * Convert screen coordinates to world coordinates.
33 */
34export function screenToWorld(
35 sx: number,
36 sy: number,
37 view: ViewState,
38 canvasWidth: number,
39 canvasHeight: number,
40): { x: number; y: number } {
41 const cx = canvasWidth / 2
42 const cy = canvasHeight / 2
43 const scale = getScale(view)
44 return {
45 x: view.centerX + (sx - cx) / scale,
46 y: view.centerY + (sy - cy) / scale,
47 }
48}
49
50/**
51 * Get the visible world bounds for the current view.
52 */
53export function getVisibleBounds(
54 view: ViewState,
55 canvasWidth: number,
56 canvasHeight: number,
57): { minX: number; minY: number; maxX: number; maxY: number } {
58 const scale = getScale(view)
59 const halfW = canvasWidth / scale / 2
60 const halfH = canvasHeight / scale / 2
61
62 return {
63 minX: Math.floor(view.centerX - halfW),
64 minY: Math.floor(view.centerY - halfH),
65 maxX: Math.ceil(view.centerX + halfW),
66 maxY: Math.ceil(view.centerY + halfH),
67 }
68}
69
70/**
71 * Convert a screen-space rectangle to world bounds.
72 */
73export function screenRectToWorldBounds(
74 view: ViewState,
75 canvasWidth: number,
76 canvasHeight: number,
77 x: number,
78 y: number,
79 width: number,
80 height: number,
81): { minX: number; minY: number; maxX: number; maxY: number } {
82 const topLeft = screenToWorld(x, y, view, canvasWidth, canvasHeight)
83 const bottomRight = screenToWorld(x + width, y + height, view, canvasWidth, canvasHeight)
84
85 const minX = Math.floor(Math.min(topLeft.x, bottomRight.x))
86 const minY = Math.floor(Math.min(topLeft.y, bottomRight.y))
87 const maxX = Math.ceil(Math.max(topLeft.x, bottomRight.x))
88 const maxY = Math.ceil(Math.max(topLeft.y, bottomRight.y))
89
90 return { minX, minY, maxX, maxY }
91}