// --------------------------------------------------------------------------- // Collision primitives — footprint-agnostic helpers over a scene's collider // list. A consuming game decides its own entity footprints; these just answer // "does this box hit anything" and "where's the nearest free spot". // --------------------------------------------------------------------------- import type { Rect } from './contract' /** The minimal shape {@link rectOverlapsAny} reads: a solid box that can be * switched off. The engine's {@link import('./scene').Collider} satisfies this * structurally, so collision stays a dependency leaf (no import of the scene). */ export interface ActiveBox { rect: { x: number; y: number; width: number; height: number } active: boolean } /** Whether an axis-aligned box (cell px) overlaps any *active* collider. * Inactive boxes (e.g. an opened gate) and an empty list are never blocking. */ export function rectOverlapsAny(box: Rect, colliders: readonly ActiveBox[]): boolean { for (const c of colliders) { if (!c.active) continue const r = c.rect if (box.x < r.x + r.width && box.x + box.w > r.x && box.y < r.y + r.height && box.y + box.h > r.y) { return true } } return false } export interface FindFreeSpotOptions { /** distance between successive rings (cell px). */ step?: number /** how many rings out to search before giving up. */ rings?: number /** angular sampling within a ring, in degrees. */ angleStep?: number } /** Search outward in rings from (x,y) for the nearest point `blocked` reports as * free, returning it — or null if nothing free is found within `rings`. The * caller supplies `blocked` so its own footprint math is used; the caller also * owns any fallback (e.g. warp to spawn) when this returns null. Returns the * start point unchanged if it is already free. */ export function findFreeSpot( x: number, y: number, blocked: (x: number, y: number) => boolean, { step = 16, rings = 64, angleStep = 15 }: FindFreeSpotOptions = {}, ): { x: number; y: number } | null { if (!blocked(x, y)) return { x, y } for (let r = 1; r <= rings; r++) { for (let a = 0; a < 360; a += angleStep) { const rad = (a * Math.PI) / 180 const nx = x + Math.cos(rad) * r * step const ny = y + Math.sin(rad) * r * step if (!blocked(nx, ny)) return { x: nx, y: ny } } } return null }