import type { AxialCoord, HexCell } from "./hex.ts"; import { hexDistance, hexLine } from "./hex.ts"; import type { TopologyGridCellState, TopologyGridCellStateKind, } from "./renderPipeline.ts"; import { getActivationEnvelope, interpolate, smootherstep, } from "./motion.ts"; export type GridCellAnimationStateKind = TopologyGridCellStateKind; export interface GridCellAnimationState extends TopologyGridCellState {} export interface GridActivityCell extends AxialCoord { id: string; edgeFactor?: number; } export interface GridActivitySelectionOptions { cells: GridActivityCell[]; occupied?: AxialCoord[]; previous?: AxialCoord | null; fallback?: GridActivityCell | null; minDistance?: number; minEdgeFactor?: number; random?: () => number; } export interface CenterBloomFrameOptions { cells: HexCell[]; origin: AxialCoord; frame: number; maxRadius: number; trail?: number; wrap?: boolean; } export interface DiagonalSweepFrameOptions { cells: HexCell[]; frame: number; width?: number; trail?: number; wrap?: boolean; } export type NavigationTransitionPhase = "out" | "in"; export type NavigationTransitionDirection = "forward" | "backward"; export interface NavigationFlowFrameOptions { cells: HexCell[]; frame: number; phase: NavigationTransitionPhase; direction?: NavigationTransitionDirection; duration?: number; intensity?: number; trail?: number; axis?: AxialProjectionAxis; reducedMotion?: boolean; } export interface MoodConversionFrameOptions { cells: HexCell[]; progress: number; seed?: string | number; } export interface BreathingFieldFrameOptions { cells: HexCell[]; frame: number; seed?: string | number; baseIntensity?: number; amplitude?: number; spatialScale?: number; speed?: number; excludedCellIds?: readonly string[] | ReadonlySet; } export interface ConstellationFrameOptions { cells: HexCell[]; frame: number; seed?: string | number; minClusterSize?: number; maxClusterSize?: number; interval?: number; attack?: number; hold?: number; release?: number; stagger?: number; minEdgeFactor?: number; minSourceDistance?: number; excludedCellIds?: readonly string[] | ReadonlySet; } export interface OrbitalCurrentFrameOptions { cells: HexCell[]; frame: number; origin?: AxialCoord; seed?: string | number; minRadius?: number; maxRadius?: number; ringStep?: number; signalsPerRing?: number; speed?: number; trail?: number; minEdgeFactor?: number; excludedCellIds?: readonly string[] | ReadonlySet; } export interface EdgeCurrentFrameOptions { cells: HexCell[]; frame: number; seed?: string | number; signals?: number; speed?: number; trail?: number; minEdgeFactor?: number; excludedCellIds?: readonly string[] | ReadonlySet; } export interface RandomTelemetryFrameOptions { cells: HexCell[]; frame: number; seed?: string | number; interval?: number; attack?: number; hold?: number; release?: number; maxConcurrent?: number; minEdgeFactor?: number; minSourceDistance?: number; excludedCellIds?: readonly string[] | ReadonlySet; } export interface SignalDriftFrameOptions { cells: HexCell[]; frame: number; seed?: string | number; drifts?: number; minLength?: number; maxLength?: number; quiet?: number; trail?: number; minEdgeFactor?: number; } export interface NetworkPulseFrameOptions { cells: HexCell[]; frame: number; seed?: string | number; /** @deprecated Use maxConcurrent to describe the scheduler capacity. */ pulses?: number; maxConcurrent?: number; interval?: number; maxRadius?: number; quiet?: number; trail?: number; minEdgeFactor?: number; minSourceDistance?: number; sourceHold?: number; excludedCellIds?: readonly string[] | ReadonlySet; } export type AxialProjectionAxis = "q" | "r" | "q+r"; export interface FaultLineFrameOptions { cells: HexCell[]; progress: number; axis?: AxialProjectionAxis; direction?: 1 | -1; trail?: number; mode?: "incoming" | "outgoing"; } export type HexAxialDirectionIndex = 0 | 1 | 2 | 3 | 4 | 5; export interface SixWayBurstFrameOptions { cells: HexCell[]; origin: AxialCoord; frame: number; maxDistance?: number; trail?: number; directionIndexes?: readonly HexAxialDirectionIndex[]; wrap?: boolean; excludedCellIds?: readonly string[] | ReadonlySet; } export interface NetworkConvergeFrameOptions { cells: HexCell[]; origin: AxialCoord; progress: number; maxDistance?: number; trail?: number; directionIndexes?: readonly HexAxialDirectionIndex[]; excludedCellIds?: readonly string[] | ReadonlySet; } export interface HexIrisFrameOptions { cells: HexCell[]; origin: AxialCoord; frame: number; maxRadius?: number; trail?: number; wrap?: boolean; mode?: "open" | "close"; } export interface RadialSignalEndpoint { index: number; sequenceNumber: number; cell: HexCell; path: AxialCoord[]; inner: boolean; } export interface RadialSignalFrameOptions { cells: HexCell[]; origin: AxialCoord; frame: number; innerRadius?: number; outerRadius?: number; endpointCount?: number; sequence?: "ascending" | "random"; seed?: string | number; synchronizedPulse?: boolean; returnToCenter?: boolean; settle?: boolean; loop?: boolean; centerActivation?: number; construction?: number; endpointSignal?: number; sequenceGap?: number; confirmationPause?: number; synchronizedPulseDuration?: number; returnDuration?: number; centerConfirmation?: number; settleDuration?: number; } export interface ShockwaveFrameOptions { cells: HexCell[]; frame: number; origin?: AxialCoord; seed?: string | number; maxRadius?: number; impactRadius?: number; trail?: number; wrap?: boolean; flash?: number; settle?: number; } interface PathPulseOptions { intensity: number; idleIntensity: number; activeState: GridCellAnimationStateKind; trailState: GridCellAnimationStateKind; trail?: number; type?: string; } interface RadialPulseOptions { intensity: number; idleNearIntensity: number; idleFarIntensity: number; activeState: GridCellAnimationStateKind; trailState: GridCellAnimationStateKind; trail?: number; attack?: number; hold?: number; release?: number; } export const HEX_AXIAL_DIRECTIONS: readonly AxialCoord[] = [ { q: 1, r: 0 }, { q: 1, r: -1 }, { q: 0, r: -1 }, { q: -1, r: 0 }, { q: -1, r: 1 }, { q: 0, r: 1 }, ] as const; const AXIAL_DIRECTIONS = HEX_AXIAL_DIRECTIONS; function clamp(value: number, min = 0, max = 1) { return Math.min(max, Math.max(min, value)); } function hashString(input: string) { let hash = 2166136261; for (let i = 0; i < input.length; i += 1) { hash ^= input.charCodeAt(i); hash = Math.imul(hash, 16777619); } return hash >>> 0; } function seededValue(seed: string | number | undefined, value: string) { return hashString(`${seed ?? "topology"}:${value}`) / 4294967295; } function stateForIntensity( state: GridCellAnimationStateKind, intensity: number, id: string, type?: string, ): GridCellAnimationState { return { id, state, intensity: clamp(intensity, 0, 1), ...(type ? { type } : {}), }; } function gridStatePriority(state: GridCellAnimationStateKind) { const order: Record = { idle: 0, trail: 1, converted: 2, active: 3, }; return order[state] ?? 0; } function applyGridState( states: Map, next: GridCellAnimationState, ) { const current = states.get(next.id); if (!current) { states.set(next.id, next); return; } const currentPriority = gridStatePriority(current.state); const nextPriority = gridStatePriority(next.state); if (nextPriority > currentPriority || (nextPriority === currentPriority && next.intensity > current.intensity)) { states.set(next.id, next); } } function coordinateKey({ q, r }: AxialCoord) { return `${q}:${r}`; } function buildIdleStateMap(cells: HexCell[], intensity = 0.08) { return new Map( cells.map((cell) => [ cell.id, stateForIntensity("idle", intensity, cell.id), ]), ); } function toStateList(states: Map) { return [...states.values()]; } const cellIndexCache = new WeakMap>(); function createCellIndex(cells: HexCell[]) { const cached = cellIndexCache.get(cells); if (cached) return cached; const index = new Map(); for (const cell of cells) { index.set(cell.id, cell); index.set(coordinateKey(cell), cell); } cellIndexCache.set(cells, index); return index; } function chooseSeededCell( cells: HexCell[], seed: string | number | undefined, salt: string, minEdgeFactor = 0.35, ) { const eligible = cells.filter((cell) => (cell.edgeFactor ?? 1) >= minEdgeFactor); const pool = eligible.length ? eligible : cells; if (!pool.length) return null; let best = pool[0]; let bestScore = -1; for (const cell of pool) { const score = seededValue(seed, `${salt}:${cell.id}`); if (score > bestScore) { bestScore = score; best = cell; } } return best; } function chooseDistributedSeededCell( cells: HexCell[], seed: string | number | undefined, salt: string, slot: number, minEdgeFactor = 0.1, ) { const eligible = cells.filter((cell) => (cell.edgeFactor ?? 1) >= minEdgeFactor); const pool = eligible.length ? eligible : cells; if (!pool.length) return null; const ranked = pool .map((cell) => { const randomness = seededValue(seed, `${salt}:${cell.id}`); const visibilityBias = (cell.edgeFactor ?? 1) * 0.28; return { cell, score: randomness * 0.72 + visibilityBias, }; }) .sort((a, b) => a.score - b.score); const offset = Math.floor(seededValue(seed, `${salt}:offset`) * ranked.length); const step = Math.max(1, Math.floor(ranked.length / 5)); return ranked[(offset + slot * step) % ranked.length]?.cell ?? null; } interface BreathingFieldSample { id: string; sinA: number; cosA: number; sinB: number; cosB: number; sinC: number; cosC: number; bias: number; } const breathingFieldSampleCache = new WeakMap>(); function getBreathingFieldSamples( cells: HexCell[], seed: string | number | undefined, spatialScale: number, ) { const cacheKey = `${seed ?? "topology"}|${spatialScale.toFixed(4)}`; const cachedByOptions = breathingFieldSampleCache.get(cells); const cached = cachedByOptions?.get(cacheKey); if (cached) return cached; const phaseA = seededValue(seed, "breathing-field:phase-a") * Math.PI * 2; const phaseB = seededValue(seed, "breathing-field:phase-b") * Math.PI * 2; const phaseC = seededValue(seed, "breathing-field:phase-c") * Math.PI * 2; const scaleA = spatialScale * (0.88 + seededValue(seed, "breathing-field:scale-a") * 0.24); const scaleB = spatialScale * (0.74 + seededValue(seed, "breathing-field:scale-b") * 0.2); const scaleC = spatialScale * (0.48 + seededValue(seed, "breathing-field:scale-c") * 0.18); const samples = cells.map((cell) => { const cellPhaseA = cell.q * scaleA + phaseA; const cellPhaseB = cell.r * scaleB + phaseB; const cellPhaseC = (cell.q + cell.r) * scaleC + phaseC; return { id: cell.id, sinA: Math.sin(cellPhaseA), cosA: Math.cos(cellPhaseA), sinB: Math.sin(cellPhaseB), cosB: Math.cos(cellPhaseB), sinC: Math.sin(cellPhaseC), cosC: Math.cos(cellPhaseC), bias: (seededValue(seed, `breathing-field:bias:${cell.id}`) - 0.5) * 0.08, }; }); const nextCache = cachedByOptions ?? new Map(); nextCache.set(cacheKey, samples); if (!cachedByOptions) breathingFieldSampleCache.set(cells, nextCache); return samples; } interface OrbitalCurrentRing { radius: number; cells: HexCell[]; } const orbitalCurrentRingCache = new WeakMap>(); function getOrbitalCurrentRings( cells: HexCell[], origin: AxialCoord, minRadius: number, maxRadius: number, ringStep: number, minEdgeFactor: number, excludedCellIds: ReadonlySet, ) { const excludedKey = [...excludedCellIds].sort().join(","); const cacheKey = [ origin.q, origin.r, minRadius, maxRadius, ringStep, minEdgeFactor.toFixed(3), excludedKey, ].join("|"); const cachedByOptions = orbitalCurrentRingCache.get(cells); const cached = cachedByOptions?.get(cacheKey); if (cached) return cached; const rings: OrbitalCurrentRing[] = []; for (let radius = minRadius; radius <= maxRadius; radius += ringStep) { const ringCells = cells .filter((cell) => ( hexDistance(origin, cell) === radius && (cell.edgeFactor ?? 1) >= minEdgeFactor && !excludedCellIds.has(cell.id) )) .sort((left, right) => { const leftQ = left.q - origin.q; const leftR = left.r - origin.r; const rightQ = right.q - origin.q; const rightR = right.r - origin.r; const leftAngle = Math.atan2(leftR * 1.5, Math.sqrt(3) * (leftQ + leftR / 2)); const rightAngle = Math.atan2(rightR * 1.5, Math.sqrt(3) * (rightQ + rightR / 2)); return leftAngle - rightAngle; }); if (ringCells.length >= Math.max(4, radius * 3)) { rings.push({ radius, cells: ringCells }); } } const nextCache = cachedByOptions ?? new Map(); nextCache.set(cacheKey, rings); if (!cachedByOptions) orbitalCurrentRingCache.set(cells, nextCache); return rings; } const edgeCurrentBoundaryCache = new WeakMap>(); function getEdgeCurrentBoundary( cells: HexCell[], minEdgeFactor: number, excludedCellIds: ReadonlySet, ) { const excludedKey = [...excludedCellIds].sort().join(","); const cacheKey = `${minEdgeFactor.toFixed(3)}|${excludedKey}`; const cachedByOptions = edgeCurrentBoundaryCache.get(cells); const cached = cachedByOptions?.get(cacheKey); if (cached) return cached; const index = createCellIndex(cells); const boundary = cells.filter((cell) => { if ((cell.edgeFactor ?? 1) < minEdgeFactor || excludedCellIds.has(cell.id)) { return false; } return AXIAL_DIRECTIONS.some((direction) => { const neighbor = index.get(coordinateKey({ q: cell.q + direction.q, r: cell.r + direction.r, })); return !neighbor || (neighbor.edgeFactor ?? 1) < minEdgeFactor; }); }); if (boundary.length > 1) { const center = boundary.reduce( (sum, cell) => ({ x: sum.x + cell.center.x, y: sum.y + cell.center.y }), { x: 0, y: 0 }, ); center.x /= boundary.length; center.y /= boundary.length; boundary.sort((left, right) => ( Math.atan2(left.center.y - center.y, left.center.x - center.x) - Math.atan2(right.center.y - center.y, right.center.x - center.x) )); } const nextCache = cachedByOptions ?? new Map(); nextCache.set(cacheKey, boundary); if (!cachedByOptions) edgeCurrentBoundaryCache.set(cells, nextCache); return boundary; } const distributedOriginSequenceCache = new WeakMap>(); function getDistributedOriginSequence( cells: HexCell[], seed: string | number | undefined, salt: string, minEdgeFactor: number, minSourceDistance: number, excludedCellIds: ReadonlySet, ) { const excludedKey = [...excludedCellIds].sort().join(","); const cacheKey = [ seed ?? "topology", salt, minEdgeFactor.toFixed(3), minSourceDistance.toFixed(3), excludedKey, ].join("|"); const cachedByOptions = distributedOriginSequenceCache.get(cells); const cached = cachedByOptions?.get(cacheKey); if (cached) return cached; const eligible = cells.filter((cell) => ( (cell.edgeFactor ?? 1) >= minEdgeFactor && !excludedCellIds.has(cell.id) )); const pool = eligible.length ? eligible : cells.filter((cell) => !excludedCellIds.has(cell.id)); if (!pool.length) return []; const sequenceLength = pool.length === 1 ? 1 : Math.max(24, Math.min(96, pool.length * 2)); const sequence: HexCell[] = []; for (let slot = 0; slot < sequenceLength; slot += 1) { const previous = sequence.at(-1); const first = sequence[0]; let candidates = pool.filter((cell) => ( cell.id !== previous?.id && (!previous || hexDistance(previous, cell) >= minSourceDistance) )); if (slot === sequenceLength - 1 && first && candidates.length > 1) { const closingCandidates = candidates.filter((cell) => ( hexDistance(cell, first) >= minSourceDistance )); if (closingCandidates.length) candidates = closingCandidates; } if (!candidates.length) { candidates = pool.filter((cell) => cell.id !== previous?.id); } if (!candidates.length) candidates = pool; const next = candidates.reduce((best, cell) => { const distanceScore = previous ? clamp(hexDistance(previous, cell) / Math.max(1, minSourceDistance * 2), 0, 1) : 1; const score = ( seededValue(seed, `${salt}:${slot}:${cell.id}`) * 0.72 + distanceScore * 0.2 + (cell.edgeFactor ?? 1) * 0.08 ); return !best || score > best.score ? { cell, score } : best; }, null as { cell: HexCell; score: number } | null)?.cell; if (next) sequence.push(next); } const nextCache = cachedByOptions ?? new Map(); nextCache.set(cacheKey, sequence); if (!cachedByOptions) distributedOriginSequenceCache.set(cells, nextCache); return sequence; } function getConstellationCluster( cells: HexCell[], center: HexCell, eventSeed: string, clusterSize: number, minEdgeFactor: number, excludedCellIds: ReadonlySet, ) { const index = createCellIndex(cells); const neighbors = AXIAL_DIRECTIONS .map((direction) => index.get(coordinateKey({ q: center.q + direction.q, r: center.r + direction.r, }))) .filter((cell): cell is HexCell => Boolean( cell && (cell.edgeFactor ?? 1) >= minEdgeFactor && !excludedCellIds.has(cell.id), )) .sort((left, right) => ( seededValue(eventSeed, `cluster:${left.id}`) - seededValue(eventSeed, `cluster:${right.id}`) )); return [center, ...neighbors].slice(0, clusterSize); } function chooseReachablePath( cells: HexCell[], source: HexCell, seed: string | number | undefined, salt: string, minLength: number, maxLength: number, minEdgeFactor = 0.35, ) { const index = createCellIndex(cells); const directionOffset = Math.floor(seededValue(seed, `${salt}:direction`) * AXIAL_DIRECTIONS.length); const orderedDirections = AXIAL_DIRECTIONS.map((_, idx) => AXIAL_DIRECTIONS[(directionOffset + idx) % AXIAL_DIRECTIONS.length]); const candidates: Array<{ cell: HexCell; score: number }> = []; for (let dirIndex = 0; dirIndex < orderedDirections.length; dirIndex += 1) { const direction = orderedDirections[dirIndex]; for (let length = minLength; length <= maxLength; length += 1) { const target = { q: source.q + direction.q * (length - 1), r: source.r + direction.r * (length - 1), }; const cell = index.get(`hex-${target.q}-${target.r}`); if (!cell || (cell.edgeFactor ?? 1) < minEdgeFactor) continue; candidates.push({ cell, score: seededValue(seed, `${salt}:${dirIndex}:${length}:${cell.id}`), }); } } if (!candidates.length) return null; candidates.sort((a, b) => b.score - a.score); const target = candidates[0].cell; const path = hexLine(source, target); return path.length >= 2 ? path : null; } function chooseAxiallyRelativeTarget( cells: HexCell[], source: HexCell, seed: string | number | undefined, salt: string, minLength: number, maxLength: number, minEdgeFactor = 0.35, ) { const index = createCellIndex(cells); const axisOrder = seededValue(seed, `${salt}:axis`) < 0.5 ? ["q", "r"] as const : ["r", "q"] as const; const preferredLength = Math.max(1, Math.min(maxLength, minLength + Math.floor(seededValue(seed, `${salt}:length`) * Math.max(1, Math.min(3, maxLength - minLength + 1))))); const lengthCandidates = [preferredLength, preferredLength + 1, preferredLength - 1, minLength, maxLength] .filter((value, index, values) => value >= minLength && value <= maxLength && values.indexOf(value) === index); const directionCandidates = seededValue(seed, `${salt}:direction`) < 0.5 ? [-1, 1] : [1, -1]; for (const axis of axisOrder) { for (const direction of directionCandidates) { for (const length of lengthCandidates) { const target = axis === "q" ? { q: source.q + direction * length, r: source.r } : { q: source.q, r: source.r + direction * length }; const cell = index.get(`hex-${target.q}-${target.r}`); if (!cell || (cell.edgeFactor ?? 1) < minEdgeFactor) continue; return cell; } } } return null; } function buildPathPulseStates( cells: HexCell[], path: AxialCoord[], position: number, options: PathPulseOptions, ) { const states = buildIdleStateMap(cells, options.idleIntensity); applyPathPulseStates(states, path, position, options); return states; } function applyPathPulseStates( states: Map, path: readonly (AxialCoord & { id?: string })[], position: number, options: PathPulseOptions, ) { if (!path.length) return states; const headPosition = Math.max(0, position); const headIndex = Math.floor(headPosition); const headFraction = headPosition - headIndex; const trailWidth = Math.max(1, options.trail ?? 1); path.forEach((coord, index) => { const id = coord.id ?? `hex-${coord.q}-${coord.r}`; const distance = headPosition - index; if (distance < 0 || distance > trailWidth + 1.35) return; if (index === headIndex) { applyGridState(states, stateForIntensity( options.activeState, options.intensity * (0.82 + headFraction * 0.18), id, options.type ?? "path", )); return; } const falloff = getActivationEnvelope(distance, { attack: 0.5, hold: 0.08, release: trailWidth + 0.65, }); if (falloff <= 0.015) return; applyGridState(states, stateForIntensity( options.trailState, Math.max(options.idleIntensity, options.intensity * (0.2 + falloff * 0.42)), id, options.type ?? "path", )); }); return states; } function buildRadialWaveStates( cells: HexCell[], origin: AxialCoord, position: number, maxRadius: number, options: RadialPulseOptions, ) { const states = buildIdleStateMap(cells, options.idleNearIntensity); const trailWidth = Math.max(1, options.trail ?? 2); const attack = options.attack ?? 0.68; const hold = options.hold ?? 0.08; const release = options.release ?? trailWidth + 0.8; for (const cell of cells) { const distance = hexDistance(origin, cell); if (distance > maxRadius) continue; const offset = position - distance; const envelope = getActivationEnvelope(offset, { attack, hold, release, }); if (envelope <= 0.015) { applyGridState(states, stateForIntensity( "idle", offset < 0 ? options.idleNearIntensity : options.idleFarIntensity, cell.id, )); continue; } if (offset >= -attack && offset <= 0.36) { applyGridState(states, stateForIntensity( options.activeState, Math.max(options.idleFarIntensity, envelope * options.intensity), cell.id, "wave", )); continue; } applyGridState(states, stateForIntensity( options.trailState, Math.max(options.idleNearIntensity, envelope * (options.intensity * 0.72)), cell.id, "wave", )); } return states; } function buildIrisStates( cells: HexCell[], origin: AxialCoord, progress: number, maxRadius: number, options: { mode: "open" | "close"; trail: number }, ) { const states = buildIdleStateMap(cells, 0.06); const trail = Math.max(1, options.trail); const boundary = maxRadius * (1 - clamp(progress, 0, 1)); for (const cell of cells) { const distance = hexDistance(origin, cell); if (distance > maxRadius) continue; const isActive = options.mode === "open" ? distance >= boundary : distance <= boundary; const nearBoundary = options.mode === "open" ? distance < boundary && distance >= boundary - trail : distance > boundary && distance <= boundary + trail; if (nearBoundary) { const fade = 1 - Math.min(1, Math.abs(distance - boundary) / Math.max(1, trail)); applyGridState(states, stateForIntensity( "trail", 0.24 + fade * 0.24, cell.id, )); continue; } if (!isActive) { applyGridState(states, stateForIntensity( "idle", 0.06 + (1 - distance / Math.max(1, maxRadius)) * 0.03, cell.id, )); continue; } const directionBias = options.mode === "open" ? distance / Math.max(1, maxRadius) : 1 - distance / Math.max(1, maxRadius); applyGridState(states, stateForIntensity( "active", 0.12 + directionBias * 0.12, cell.id, )); } return states; } export function toGridCellStateMap(states: GridCellAnimationState[]) { return Object.fromEntries(states.map((state) => [state.id, state])); } export function getCenterBloomFrame(options: CenterBloomFrameOptions): GridCellAnimationState[] { const { cells, origin, frame, maxRadius, trail = 2, wrap = true } = options; const cycle = Math.max(1, maxRadius + trail + 1); const position = wrap ? ((frame % cycle) + cycle) % cycle : Math.max(0, frame); const attack = 0.72; return cells.map((cell) => { const distance = hexDistance(origin, cell); const offset = position - distance; const intensity = getActivationEnvelope(offset, { attack, hold: 0.08, release: trail + 0.8, }); if (intensity <= 0.015) { return stateForIntensity("idle", offset < 0 ? 0.18 : 0.12, cell.id); } if (offset >= -attack && offset <= 0.36) { return stateForIntensity("active", intensity, cell.id); } return stateForIntensity("trail", Math.max(0.12, intensity * 0.82), cell.id); }); } export function getAxialRayCells( cells: HexCell[], origin: AxialCoord, direction: AxialCoord, maxDistance: number, excludedCellIds: readonly string[] | ReadonlySet = [], ): HexCell[] { const excluded = excludedCellIds instanceof Set ? excludedCellIds : new Set(excludedCellIds); const index = createCellIndex(cells); const ray: HexCell[] = []; for (let distance = 0; distance <= Math.max(0, Math.floor(maxDistance)); distance += 1) { const cell = index.get(coordinateKey({ q: origin.q + direction.q * distance, r: origin.r + direction.r * distance, })); if (!cell || excluded.has(cell.id)) break; ray.push(cell); } return ray; } export function getSixWayBurstFrame(options: SixWayBurstFrameOptions): GridCellAnimationState[] { const { cells, origin, frame, maxDistance = 6, trail = 2, directionIndexes = [0, 1, 2, 3, 4, 5], wrap = true, excludedCellIds = [], } = options; const resolvedDistance = Math.max(0, Math.floor(maxDistance)); const resolvedTrail = Math.max(1, trail); const cycle = Math.max(1, resolvedDistance + resolvedTrail + 1); const position = wrap ? ((frame % cycle) + cycle) % cycle : Math.max(0, frame); const states = buildIdleStateMap(cells, 0.05); const selectedDirections = [...new Set(directionIndexes)] .filter((index): index is HexAxialDirectionIndex => ( Number.isInteger(index) && index >= 0 && index < HEX_AXIAL_DIRECTIONS.length )); for (const directionIndex of selectedDirections) { const path = getAxialRayCells( cells, origin, HEX_AXIAL_DIRECTIONS[directionIndex], resolvedDistance, excludedCellIds, ); applyPathPulseStates(states, path, position, { intensity: 0.76, idleIntensity: 0.05, activeState: "active", trailState: "trail", trail: resolvedTrail, type: "six-way-burst", }); } return toStateList(states); } export function getNetworkConvergeFrame(options: NetworkConvergeFrameOptions): GridCellAnimationState[] { const { cells, origin, progress, maxDistance = 8, trail = 2, directionIndexes = [0, 1, 2, 3, 4, 5], excludedCellIds = [], } = options; const states = buildIdleStateMap(cells, 0.04); const resolvedDistance = Math.max(1, Math.floor(maxDistance)); const resolvedTrail = Math.max(1, trail); const motionProgress = smootherstep(0, 1, clamp(progress)); const selectedDirections = [...new Set(directionIndexes)] .filter((index): index is HexAxialDirectionIndex => ( Number.isInteger(index) && index >= 0 && index < HEX_AXIAL_DIRECTIONS.length )); for (const directionIndex of selectedDirections) { const path = getAxialRayCells( cells, origin, HEX_AXIAL_DIRECTIONS[directionIndex], resolvedDistance, excludedCellIds, ).reverse(); if (path.length < 2) continue; applyPathPulseStates(states, path, motionProgress * (path.length - 1), { intensity: 0.82, idleIntensity: 0.04, activeState: "active", trailState: "trail", trail: resolvedTrail, type: "network-converge", }); } return toStateList(states); } export function projectAxialCoordinate( coordinate: AxialCoord, axis: AxialProjectionAxis = "q+r", ) { if (axis === "q") return coordinate.q; if (axis === "r") return coordinate.r; return coordinate.q + coordinate.r; } export function getFaultLineFrame(options: FaultLineFrameOptions): GridCellAnimationState[] { const { cells, progress, axis = "q+r", direction = 1, trail = 0.75, mode = "incoming", } = options; if (!cells.length) return []; const projections = cells.map((cell) => ( projectAxialCoordinate(cell, axis) * direction )); const minProjection = Math.min(...projections); const maxProjection = Math.max(...projections); const resolvedTrail = Math.max(0.05, trail); const boundary = interpolate( minProjection - resolvedTrail, maxProjection + resolvedTrail, clamp(progress), ); return cells.map((cell, index) => { const incomingVisibility = 1 - smootherstep( boundary - resolvedTrail, boundary + resolvedTrail, projections[index], ); const visibility = mode === "incoming" ? incomingVisibility : 1 - incomingVisibility; const state = visibility >= 0.66 ? "active" : visibility > 0.015 ? "trail" : "idle"; return stateForIntensity(state, visibility, cell.id, "fault-line"); }); } export function getNavigationFlowFrame(options: NavigationFlowFrameOptions): GridCellAnimationState[] { const { cells, frame, phase, direction = "forward", duration = phase === "out" ? 240 : 280, intensity = 0.3, trail = 2, axis = "q+r", reducedMotion = false, } = options; if (!cells.length) return []; if (reducedMotion) { return cells.map((cell) => stateForIntensity("idle", 0.12, cell.id, "navigation-flow")); } const sign = direction === "backward" ? -1 : 1; const projections = cells.map((cell) => projectAxialCoordinate(cell, axis) * sign); const minimum = Math.min(...projections); const maximum = Math.max(...projections); const span = Math.max(1, maximum - minimum); const normalizedFrame = clamp(frame / Math.max(1, duration), 0, 1); const position = minimum - trail + normalizedFrame * (span + trail * 2); const wake = Math.max(0.5, trail); return cells.map((cell, index) => { const offset = position - projections[index]; const activity = getActivationEnvelope(offset, { attack: 0.7, hold: 0.14, release: wake, }); if (activity <= 0.015) { return stateForIntensity("idle", 0.1, cell.id, "navigation-flow"); } if (offset >= -0.7 && offset <= 0.35) { return stateForIntensity("active", Math.min(1, intensity * (0.72 + activity * 0.28)), cell.id, "navigation-flow"); } return stateForIntensity("trail", Math.min(1, intensity * activity * 0.72), cell.id, "navigation-flow"); }); } export function getDiagonalSweepFrame(options: DiagonalSweepFrameOptions): GridCellAnimationState[] { const { cells, frame, width, trail = 3, wrap = true } = options; const bands = cells.map((cell) => projectAxialCoordinate(cell)); const minBand = Math.min(...bands); const maxBand = Math.max(...bands); const totalBands = Math.max(1, maxBand - minBand + 1); const span = Math.max(1, width ?? totalBands); const position = wrap ? ((frame % span) + span) % span : Math.max(0, frame); const currentBand = minBand + position; const attack = 0.68; return cells.map((cell) => { const band = projectAxialCoordinate(cell); const offset = currentBand - band; const intensity = getActivationEnvelope(offset, { attack, hold: 0.05, release: trail + 0.8, }); if (intensity <= 0.015) { return stateForIntensity("idle", offset < 0 ? 0.14 : 0.1, cell.id); } if (offset >= -attack && offset <= 0.34) { return stateForIntensity("active", intensity, cell.id); } return stateForIntensity("trail", Math.max(0.1, intensity * 0.78), cell.id); }); } export function getMoodConversionFrame(options: MoodConversionFrameOptions): GridCellAnimationState[] { const { cells, progress, seed } = options; const normalizedProgress = clamp(progress, 0, 1); const fadeWidth = 0.12; return cells.map((cell) => { const threshold = seededValue(seed, cell.id); const idleIntensity = 0.16 + threshold * 0.16; if (normalizedProgress >= threshold) { const fadeEnd = Math.min(1, threshold + fadeWidth); const localProgress = smootherstep(threshold, fadeEnd, normalizedProgress); return stateForIntensity( "converted", interpolate(idleIntensity, 1, localProgress), cell.id, ); } return stateForIntensity("idle", idleIntensity, cell.id); }); } export function getBreathingFieldFrame(options: BreathingFieldFrameOptions): GridCellAnimationState[] { const { cells, frame, seed, baseIntensity = 0.07, amplitude = 0.025, spatialScale = 0.42, speed = 0.55, excludedCellIds = [], } = options; const excludedIds = excludedCellIds instanceof Set ? excludedCellIds : new Set(excludedCellIds); const resolvedBaseIntensity = clamp(baseIntensity, 0, 1); const resolvedAmplitude = Math.max(0, Math.min(amplitude, 0.12)); const samples = getBreathingFieldSamples(cells, seed, Math.max(0.05, spatialScale)); const time = frame * speed; const timeB = -time * 0.73; const timeC = time * 0.41; const sinTime = Math.sin(time); const cosTime = Math.cos(time); const sinTimeB = Math.sin(timeB); const cosTimeB = Math.cos(timeB); const sinTimeC = Math.sin(timeC); const cosTimeC = Math.cos(timeC); return samples.map((sample) => { if (excludedIds?.has(sample.id)) { return stateForIntensity( "idle", Math.max(0.02, resolvedBaseIntensity - resolvedAmplitude), sample.id, ); } const field = clamp( (sample.sinA * cosTime + sample.cosA * sinTime) * 0.46 + (sample.sinB * cosTimeB + sample.cosB * sinTimeB) * 0.34 + (sample.sinC * cosTimeC + sample.cosC * sinTimeC) * 0.2 + sample.bias, -1, 1, ); return stateForIntensity( "idle", resolvedBaseIntensity + field * resolvedAmplitude, sample.id, "field", ); }); } export function getOrbitalCurrentFrame(options: OrbitalCurrentFrameOptions): GridCellAnimationState[] { const { cells, frame, origin = { q: 0, r: 0 }, seed, minRadius = 2, maxRadius = 4, signalsPerRing = 1, ringStep = 2, speed = 0.9, trail = 2, minEdgeFactor = 0.4, excludedCellIds = [], } = options; const states = buildIdleStateMap(cells, 0.04); const excludedIds = excludedCellIds instanceof Set ? excludedCellIds : new Set(excludedCellIds); const resolvedMinRadius = Math.max(1, Math.round(minRadius)); const resolvedMaxRadius = Math.max(resolvedMinRadius, Math.round(maxRadius)); const resolvedSignalCount = Math.max(1, Math.min(2, Math.round(signalsPerRing))); const resolvedRingStep = Math.max(1, Math.round(ringStep)); const resolvedTrail = Math.max(0, Math.round(trail)); const resolvedSpeed = Math.max(0.05, speed); const rings = getOrbitalCurrentRings( cells, origin, resolvedMinRadius, resolvedMaxRadius, resolvedRingStep, minEdgeFactor, excludedIds, ); const directionOffset = Math.floor(seededValue(seed, "orbital-current:direction") * 2); for (const [ringIndex, ring] of rings.entries()) { for (const cell of ring.cells) { applyGridState(states, stateForIntensity("idle", 0.09, cell.id, "orbital")); } const ringLength = ring.cells.length; const direction = (ringIndex + directionOffset) % 2 === 0 ? 1 : -1; const ringSpeed = resolvedSpeed * Math.max( 0.55, 1 - (ring.radius - resolvedMinRadius) * 0.12, ); const phase = seededValue(seed, `orbital-current:phase:${ring.radius}`) * ringLength; for (let slot = 0; slot < resolvedSignalCount; slot += 1) { const position = ( ( phase + slot * ringLength / resolvedSignalCount + direction * frame * ringSpeed ) % ringLength + ringLength ) % ringLength; for (let index = 0; index < ringLength; index += 1) { const ahead = ((direction * (index - position)) % ringLength + ringLength) % ringLength; const behind = ((direction * (position - index)) % ringLength + ringLength) % ringLength; const nearestHeadDistance = Math.min(ahead, behind); const cell = ring.cells[index]; if (nearestHeadDistance < 1) { applyGridState(states, stateForIntensity( "active", interpolate(0.38, 0.7, 1 - nearestHeadDistance), cell.id, "orbital", )); } else if (resolvedTrail > 0 && behind <= resolvedTrail + 1) { const trailProgress = 1 - (behind - 1) / resolvedTrail; applyGridState(states, stateForIntensity( "trail", interpolate(0.1, 0.3, clamp(trailProgress)), cell.id, "orbital", )); } } } } return toStateList(states); } export function getEdgeCurrentFrame(options: EdgeCurrentFrameOptions): GridCellAnimationState[] { const { cells, frame, seed, signals = 2, speed = 1.1, trail = 3, minEdgeFactor = 0.4, excludedCellIds = [], } = options; const states = buildIdleStateMap(cells, 0.04); const excludedIds = excludedCellIds instanceof Set ? excludedCellIds : new Set(excludedCellIds); const boundary = getEdgeCurrentBoundary( cells, Math.max(0, minEdgeFactor), excludedIds, ); if (!boundary.length) return toStateList(states); const signalCount = Math.max(1, Math.min(3, Math.round(signals))); const trailLength = Math.max(0, Math.round(trail)); const direction = seededValue(seed, "edge-current:direction") < 0.5 ? -1 : 1; const phase = seededValue(seed, "edge-current:phase") * boundary.length; for (const cell of boundary) { applyGridState(states, stateForIntensity("idle", 0.075, cell.id, "edge-current")); } for (let slot = 0; slot < signalCount; slot += 1) { const position = ( phase + slot * boundary.length / signalCount + direction * frame * Math.max(0.05, speed) ); const wrappedPosition = ((position % boundary.length) + boundary.length) % boundary.length; for (let offset = 0; offset <= trailLength; offset += 1) { const boundaryPosition = wrappedPosition - direction * offset; const index = Math.round( ((boundaryPosition % boundary.length) + boundary.length) % boundary.length, ) % boundary.length; const cell = boundary[index]; const intensity = offset === 0 ? 0.62 : interpolate(0.11, 0.34, 1 - offset / Math.max(1, trailLength)); applyGridState(states, stateForIntensity( offset === 0 ? "active" : "trail", intensity, cell.id, "edge-current", )); } } return toStateList(states); } export function getRandomTelemetryFrame(options: RandomTelemetryFrameOptions): GridCellAnimationState[] { const { cells, frame, seed, interval = 0.9, attack = 0.18, hold = 0.16, release = 0.56, maxConcurrent = 2, minEdgeFactor = 0.4, minSourceDistance = 4, excludedCellIds = [], } = options; const states = buildIdleStateMap(cells, 0.04); const excludedIds = excludedCellIds instanceof Set ? excludedCellIds : new Set(excludedCellIds); const resolvedInterval = Math.max(0.2, interval); const resolvedAttack = Math.max(0.05, attack); const resolvedHold = Math.max(0, hold); const resolvedRelease = Math.max(0.1, release); const eventDuration = resolvedAttack + resolvedHold + resolvedRelease; const concurrency = Math.max(1, Math.min(4, Math.round(maxConcurrent))); const eventIndex = Math.floor(frame / resolvedInterval); const origins = getDistributedOriginSequence( cells, `${seed ?? "topology"}:random-telemetry`, "random-telemetry-origin", minEdgeFactor, Math.max(0, minSourceDistance), excludedIds, ); if (!origins.length) return toStateList(states); for (let offset = 0; offset < concurrency; offset += 1) { const currentEvent = eventIndex - offset; if (currentEvent < 0) continue; const eventFrame = frame - currentEvent * resolvedInterval; if (eventFrame < 0 || eventFrame > eventDuration) continue; const cell = origins[currentEvent % origins.length]; const envelope = getActivationEnvelope(eventFrame - resolvedAttack, { attack: resolvedAttack, hold: resolvedHold, release: resolvedRelease, }); if (envelope <= 0.015) continue; const active = eventFrame >= resolvedAttack && eventFrame <= resolvedAttack + resolvedHold; const peak = 0.52 + seededValue(seed, `random-telemetry:intensity:${currentEvent}`) * 0.16; applyGridState(states, stateForIntensity( active ? "active" : "trail", interpolate(0.07, peak, envelope), cell.id, "telemetry", )); } return toStateList(states); } export function getConstellationFrame(options: ConstellationFrameOptions): GridCellAnimationState[] { const { cells, frame, seed, minClusterSize = 2, maxClusterSize = 5, interval = 5.8, attack = 0.7, hold = 1.4, release = 1.2, stagger = 0.1, minEdgeFactor = 0.45, minSourceDistance = 6, excludedCellIds = [], } = options; const states = buildIdleStateMap(cells, 0.04); const excludedIds = excludedCellIds instanceof Set ? excludedCellIds : new Set(excludedCellIds); const resolvedMinSize = Math.max(2, Math.min(5, Math.round(minClusterSize))); const resolvedMaxSize = Math.max( resolvedMinSize, Math.min(5, Math.round(maxClusterSize)), ); const resolvedAttack = Math.max(0.2, attack); const resolvedHold = Math.max(0, hold); const resolvedRelease = Math.max(0.2, release); const resolvedStagger = Math.max(0, stagger); const activeDuration = ( resolvedAttack + (resolvedMaxSize - 1) * resolvedStagger + resolvedHold + resolvedRelease ); const eventInterval = Math.max(activeDuration + 0.8, interval); const eventIndex = Math.floor(frame / eventInterval); const eventFrame = frame - eventIndex * eventInterval; if (eventFrame > activeDuration) return toStateList(states); const originSequence = getDistributedOriginSequence( cells, `${seed ?? "topology"}:constellation`, "constellation-origin", minEdgeFactor, Math.max(0, minSourceDistance), excludedIds, ); if (!originSequence.length) return toStateList(states); const eventSeed = `${seed ?? "topology"}:constellation-event:${eventIndex}`; const clusterSize = resolvedMinSize + Math.floor( seededValue(eventSeed, "cluster-size") * (resolvedMaxSize - resolvedMinSize + 1), ); let cluster: HexCell[] = []; for (let offset = 0; offset < originSequence.length; offset += 1) { const sequenceIndex = ( (eventIndex + offset) % originSequence.length + originSequence.length ) % originSequence.length; const center = originSequence[sequenceIndex]; const candidate = getConstellationCluster( cells, center, eventSeed, clusterSize, minEdgeFactor, excludedIds, ); if (candidate.length >= resolvedMinSize) { cluster = candidate; break; } } for (let index = 0; index < cluster.length; index += 1) { const cell = cluster[index]; const offset = eventFrame - resolvedAttack - index * resolvedStagger; const envelope = getActivationEnvelope(offset, { attack: resolvedAttack, hold: resolvedHold, release: resolvedRelease, }); if (envelope <= 0) continue; const peakIntensity = index === 0 ? 0.72 : 0.5 + seededValue(eventSeed, `intensity:${cell.id}`) * 0.12; applyGridState(states, stateForIntensity( envelope < 0.24 ? "trail" : "active", interpolate(0.06, peakIntensity, envelope), cell.id, "constellation", )); } return toStateList(states); } export function getSignalDriftFrame(options: SignalDriftFrameOptions): GridCellAnimationState[] { const { cells, frame, seed, drifts, minLength = 3, maxLength = 8, quiet = 5, trail = 1, minEdgeFactor = 0.45, } = options; const states = buildIdleStateMap(cells, 0.05); const pairWindow = Math.max(24, maxLength * 2 + quiet + 6); const pairIndex = Math.floor(frame / pairWindow); const pairSeed = `${seed ?? "topology"}:signal-drift:${pairIndex}:${drifts ?? "auto"}`; const sourceSequenceSeed = `${seed ?? "topology"}:signal-drift:${drifts ?? "auto"}`; const source = chooseDistributedSeededCell( cells, sourceSequenceSeed, "source-sequence", pairIndex, Math.max(0.08, minEdgeFactor - 0.28), ); if (!source) return toStateList(states); const target = chooseAxiallyRelativeTarget( cells, source, pairSeed, `target:${pairIndex}`, minLength, maxLength, minEdgeFactor, ); if (!target) return toStateList(states); const path = hexLine(source, target); if (!path || path.length < 2) return toStateList(states); const cyclePosition = ((frame % pairWindow) + pairWindow) % pairWindow; const sourceHold = 1.15 + seededValue(pairSeed, "source-hold") * 0.5; const travelDuration = Math.max(2.25, (path.length - 1) + seededValue(pairSeed, "travel") * 0.7); const targetHold = 0.95 + seededValue(pairSeed, "target-hold") * 0.45; const activeWindow = sourceHold + travelDuration + targetHold; if (cyclePosition >= activeWindow) { return toStateList(states); } if (cyclePosition < sourceHold) { const holdProgress = cyclePosition / Math.max(1, sourceHold); applyGridState(states, stateForIntensity( "active", interpolate(0.46, 0.84, smootherstep(0, 1, holdProgress)), source.id, "path", )); if (holdProgress > 0.46) { applyGridState(states, stateForIntensity( "trail", interpolate(0.08, 0.26, smootherstep(0.46, 1, holdProgress)), target.id, "receiving", )); } return toStateList(states); } if (cyclePosition < sourceHold + travelDuration) { const travelProgress = (cyclePosition - sourceHold) / Math.max(1, travelDuration); const pathPosition = travelProgress * Math.max(1, path.length - 1); const pathStates = buildPathPulseStates(cells, path, pathPosition, { intensity: 0.58 + seededValue(pairSeed, "intensity") * 0.1, idleIntensity: 0.05, activeState: "active", trailState: "trail", trail: Math.max(1, trail), }); for (const next of pathStates.values()) { applyGridState(states, next); } applyGridState(states, stateForIntensity( travelProgress < 0.16 ? "active" : "trail", interpolate(0.34, 0.84, smootherstep(0.12, 1, travelProgress)), source.id, "path", )); if (travelProgress > 0.22) { applyGridState(states, stateForIntensity( travelProgress > 0.84 ? "active" : "trail", interpolate(0.18, 0.78, smootherstep(0.22, 1, travelProgress)), target.id, travelProgress > 0.84 ? "path" : "receiving", )); } return toStateList(states); } const settleProgress = (cyclePosition - sourceHold - travelDuration) / Math.max(1, targetHold); applyGridState(states, stateForIntensity( "trail", interpolate(0.12, 0.24, smootherstep(0, 1, settleProgress)), source.id, "path", )); applyGridState(states, stateForIntensity( "active", interpolate(0.64, 0.9, smootherstep(0, 1, settleProgress)), target.id, "path", )); return toStateList(states); } export function getNetworkPulseFrame(options: NetworkPulseFrameOptions): GridCellAnimationState[] { const { cells, frame, seed, pulses, maxConcurrent, interval, maxRadius = 4, quiet = 6, trail = 1, minEdgeFactor = 0.4, minSourceDistance = Math.max(3, maxRadius * 1.5), sourceHold = 1.25, excludedCellIds = [], } = options; const states = buildIdleStateMap(cells, 0.042); const excludedIds = excludedCellIds instanceof Set ? excludedCellIds : new Set(excludedCellIds); const resolvedMaxRadius = Math.max(2, maxRadius); const eventCapacity = Math.max( 1, Math.round(maxConcurrent ?? pulses ?? Math.max(1, Math.min(3, Math.round(cells.length / 240)))), ); const eventInterval = Math.max( 1.5, interval ?? (resolvedMaxRadius + Math.max(0, quiet) + Math.max(1, trail) + 1) / eventCapacity, ); const originSequence = getDistributedOriginSequence( cells, `${seed ?? "topology"}:network-pulse`, "network-pulse-origin", minEdgeFactor, Math.max(0, minSourceDistance), excludedIds, ); if (!originSequence.length) return toStateList(states); const currentEventIndex = Math.floor(frame / eventInterval); const waveLead = 0.32; const resolvedSourceHold = Math.max(0.4, sourceHold); const sourceFade = 0.9; for (let eventOffset = 0; eventOffset < eventCapacity; eventOffset += 1) { const eventIndex = currentEventIndex - eventOffset; const eventFrame = frame - eventIndex * eventInterval; const pulseSeed = `${seed ?? "topology"}:network-pulse-event:${eventIndex}`; const sequenceIndex = ((eventIndex % originSequence.length) + originSequence.length) % originSequence.length; const origin = originSequence[sequenceIndex]; if (!origin) continue; const pulseRadius = Math.max(2, Math.min( resolvedMaxRadius, 2 + Math.floor(seededValue(pulseSeed, "radius") * Math.max(1, resolvedMaxRadius - 1)), )); const eventDuration = waveLead + pulseRadius + Math.max(1, trail) + 0.5; if (eventFrame < 0 || eventFrame > eventDuration) continue; const waveStates = buildRadialWaveStates( cells, origin, Math.max(0, eventFrame - waveLead), pulseRadius, { intensity: 0.5 + seededValue(pulseSeed, "intensity") * 0.12, idleNearIntensity: 0.04, idleFarIntensity: 0.03, activeState: "active", trailState: "trail", trail, attack: 0.6, hold: 0.05, release: trail + 0.5, }, ); for (const next of waveStates.values()) { applyGridState(states, next); } if (eventFrame <= resolvedSourceHold + sourceFade) { const sourceIntensity = eventFrame <= resolvedSourceHold ? interpolate(0.64, 0.76, smootherstep(0, Math.min(0.34, resolvedSourceHold), eventFrame)) : interpolate( 0.76, 0.1, smootherstep(resolvedSourceHold, resolvedSourceHold + sourceFade, eventFrame), ); applyGridState(states, stateForIntensity( eventFrame <= resolvedSourceHold ? "active" : "trail", sourceIntensity, origin.id, "pulse-source", )); } } for (const id of excludedIds) { if (states.has(id)) { states.set(id, stateForIntensity("idle", 0.042, id)); } } return toStateList(states); } export function getHexIrisFrame(options: HexIrisFrameOptions): GridCellAnimationState[] { const { cells, origin, frame, maxRadius, trail = 2, wrap = true, mode = "open", } = options; const radius = maxRadius ?? Math.max(...cells.map((cell) => hexDistance(origin, cell))); const cycle = Math.max(1, radius + trail + 1); const position = wrap ? ((frame % cycle) + cycle) % cycle : Math.max(0, Math.min(frame, radius)); const progress = clamp(position / Math.max(1, radius), 0, 1); return toStateList(buildIrisStates(cells, origin, progress, radius, { mode, trail, })); } export function getShockwaveFrame(options: ShockwaveFrameOptions): GridCellAnimationState[] { const { cells, frame, origin, seed, maxRadius, impactRadius, trail = 1, wrap = true, flash = 0.8, settle = 1.5, } = options; const states = buildIdleStateMap(cells, 0.05); const cycleSeed = seed ?? "topology"; const resolvedOrigin = origin ?? chooseSeededCell(cells, `${cycleSeed}:${Math.floor(frame / 8)}`, "shockwave-origin", 0.3) ?? cells[0]; if (!resolvedOrigin) return toStateList(states); const originId = `hex-${resolvedOrigin.q}-${resolvedOrigin.r}`; const radius = maxRadius ?? Math.max(3, Math.min(7, Math.ceil(Math.max(...cells.map((cell) => hexDistance(resolvedOrigin, cell))) * 0.62))); const impact = impactRadius ?? Math.max(2, Math.round(radius * 0.5)); const flashDuration = Math.max(0.35, flash); const waveDuration = Math.max(1.2, radius + 0.85); const echoDuration = Math.max(0.9, radius * 0.45 + 0.65); const settleDuration = Math.max(0.8, settle); const cycle = flashDuration + waveDuration + echoDuration + settleDuration; const cyclePosition = wrap ? ((frame % cycle) + cycle) % cycle : Math.max(0, Math.min(frame, cycle)); const flashEnd = flashDuration; const waveEnd = flashEnd + waveDuration; const echoEnd = waveEnd + echoDuration; if (cyclePosition < flashEnd) { const flashProgress = cyclePosition / flashEnd; const localFront = Math.min(1.25, flashProgress * 1.25); const flashStates = buildRadialWaveStates( cells, resolvedOrigin, localFront, Math.max(2, impact), { intensity: 0.82 + flashProgress * 0.1, idleNearIntensity: 0.06, idleFarIntensity: 0.04, activeState: "active", trailState: "trail", trail: 1, attack: 0.42, hold: 0, release: 1.05, }, ); for (const next of flashStates.values()) { applyGridState(states, next); } applyGridState(states, stateForIntensity("active", 1, originId)); return toStateList(states); } if (cyclePosition < waveEnd) { const waveProgress = (cyclePosition - flashEnd) / waveDuration; const primaryFront = waveProgress * radius; const primaryStates = buildRadialWaveStates( cells, resolvedOrigin, primaryFront, radius, { intensity: 0.9, idleNearIntensity: 0.045, idleFarIntensity: 0.035, activeState: "active", trailState: "trail", trail, attack: 0.46, hold: 0.04, release: trail + 0.45, }, ); for (const next of primaryStates.values()) { applyGridState(states, next); } const echoFront = Math.max(0, primaryFront - 1.15); const echoStates = buildRadialWaveStates( cells, resolvedOrigin, echoFront, radius, { intensity: 0.38, idleNearIntensity: 0.04, idleFarIntensity: 0.03, activeState: "active", trailState: "trail", trail: 1, attack: 0.42, hold: 0.02, release: 1.2, }, ); for (const next of echoStates.values()) { applyGridState(states, next); } return toStateList(states); } const settleProgress = (cyclePosition - waveEnd) / settleDuration; for (const cell of cells) { const distance = hexDistance(resolvedOrigin, cell); if (distance > impact) continue; const normalized = 1 - distance / Math.max(1, impact); const fade = smootherstep(0, 1, clamp(settleProgress, 0, 1)); const intensity = interpolate(0.12 + normalized * 0.12, 0.26 + normalized * 0.16, fade); applyGridState(states, stateForIntensity("converted", intensity, cell.id)); } return toStateList(states); } export function selectGridActivityCell({ cells, occupied = [], previous = null, fallback = null, minDistance = 5, minEdgeFactor = 0.5, random = Math.random, }: GridActivitySelectionOptions): GridActivityCell | null { const occupiedIds = new Set(occupied.map(coordinateKey)); const eligible = cells.filter((cell) => ( !occupiedIds.has(coordinateKey(cell)) && (cell.edgeFactor ?? 1) >= minEdgeFactor )); if (!eligible.length) return fallback; const distant = previous ? eligible.filter((cell) => hexDistance(cell, previous) >= minDistance) : eligible; const pool = distant.length ? distant : eligible; const randomValue = Math.min(0.999999, Math.max(0, random())); return pool[Math.floor(randomValue * pool.length)] ?? pool[0] ?? fallback; } const radialSignalEndpointCache = new WeakMap>(); export function getRadialSignalEndpoints(cells: HexCell[], origin: AxialCoord, innerRadius = 4, outerRadius = 8, endpointCount = 12): RadialSignalEndpoint[] { const count = Math.max(2, Math.floor(endpointCount)); const key = [origin.q, origin.r, innerRadius, outerRadius, count].join("|"); const byGrid = radialSignalEndpointCache.get(cells); const cached = byGrid?.get(key); if (cached) return cached; const originCell = cells.find((cell) => cell.q === origin.q && cell.r === origin.r); if (!originCell) return []; const neighbor = cells.find((cell) => hexDistance(origin, cell) === 1); const unit = neighbor ? Math.max(1, Math.hypot(neighbor.center.x - originCell.center.x, neighbor.center.y - originCell.center.y)) : 1; const endpoints: RadialSignalEndpoint[] = []; for (let index = 0; index < count; index += 1) { const inner = index % 2 === 1; const desired = inner ? innerRadius : outerRadius; const angle = -Math.PI / 2 + index * Math.PI * 2 / count; const target = { x: originCell.center.x + Math.cos(angle) * desired * unit, y: originCell.center.y + Math.sin(angle) * desired * unit }; const pool = cells.filter((cell) => "hex-" + cell.q + "-" + cell.r !== originCell.id && (cell.edgeFactor ?? 1) >= 0.35); const endpoint = (pool.length ? pool : cells.filter((cell) => "hex-" + cell.q + "-" + cell.r !== originCell.id)).reduce((best, cell) => { const score = Math.hypot(cell.center.x - target.x, cell.center.y - target.y) + Math.abs(hexDistance(origin, cell) - desired) * unit * 0.65; return !best || score < best.score ? { cell, score } : best; }, null as { cell: HexCell; score: number } | null)?.cell; if (endpoint) endpoints.push({ index, sequenceNumber: index + 1, cell: endpoint, path: hexLine(origin, endpoint), inner }); } const next = byGrid ?? new Map(); next.set(key, endpoints); if (!byGrid) radialSignalEndpointCache.set(cells, next); return endpoints; } export function getRadialSignalFrame(options: RadialSignalFrameOptions): GridCellAnimationState[] { const centerActivation = options.centerActivation ?? 380, construction = options.construction ?? 680, endpointSignal = options.endpointSignal ?? 140, sequenceGap = options.sequenceGap ?? 70, pause = options.confirmationPause ?? 200, pulseDuration = options.synchronizedPulseDuration ?? 320, returnDuration = options.returnDuration ?? 520, centerDuration = options.centerConfirmation ?? 240, settleDuration = options.settleDuration ?? 400; const endpoints = getRadialSignalEndpoints(options.cells, options.origin, options.innerRadius ?? 4, options.outerRadius ?? 8, options.endpointCount ?? 12); if (!endpoints.length) return []; const sequenceOrder = [...endpoints].sort((left, right) => seededValue(options.seed ?? "radial-signal", `sequence:${left.sequenceNumber}`) - seededValue(options.seed ?? "radial-signal", `sequence:${right.sequenceNumber}`)); const sequenceRank = new Map(sequenceOrder.map((endpoint, rank) => [endpoint.index, rank])); const sequenceStart = centerActivation + construction, sequenceDuration = endpoints.length * (endpointSignal + sequenceGap), pulseStart = sequenceStart + sequenceDuration + pause, returnStart = pulseStart + pulseDuration, centerStart = returnStart + returnDuration, settleStart = centerStart + centerDuration, total = settleStart + settleDuration; let elapsed = Math.max(0, options.frame); if (options.loop) elapsed %= total; const states = new Map(); const add = (state: GridCellAnimationState) => applyGridState(states, state); const centerId = "hex-" + options.origin.q + "-" + options.origin.r; const centerIntensity = elapsed >= centerStart && elapsed < settleStart ? 0.55 + smootherstep(0, centerDuration, elapsed - centerStart) * 0.45 : elapsed < centerActivation ? 0.18 + smootherstep(0, centerActivation, elapsed) * 0.72 : 0.28; add(stateForIntensity("active", centerIntensity, centerId, "radial-signal-center")); const addPath = (path: AxialCoord[], position: number, type: string, intensity: number) => { const head = Math.floor(position); path.forEach((cell, index) => { const distance = position - index; if (distance < -0.01 || distance > 2.4) return; add(stateForIntensity(index === head ? "active" : "trail", intensity * clamp(1 - Math.max(0, distance) / 2.8, 0.18, 1), "hex-" + cell.q + "-" + cell.r, type)); }); }; if (elapsed >= centerActivation && elapsed < sequenceStart) { const progress = smootherstep(0, construction, elapsed - centerActivation); for (const endpoint of endpoints) addPath(endpoint.path, progress * (endpoint.path.length - 1), "radial-signal-construction", 0.78); } else if (elapsed >= sequenceStart && elapsed < returnStart) { const sequenceElapsed = elapsed - sequenceStart; const lastSequenceStart = (endpoints.length - 1) * (endpointSignal + sequenceGap); if (sequenceElapsed >= lastSequenceStart && sequenceElapsed < lastSequenceStart + endpointSignal) { for (const endpoint of endpoints) add(stateForIntensity("active", 0.68, endpoint.cell.id, "radial-signal-final-fill")); } for (const endpoint of endpoints) { for (const cell of endpoint.path) add(stateForIntensity("idle", 0.2, "hex-" + cell.q + "-" + cell.r, "radial-signal-path")); const rank = options.sequence === "ascending" ? endpoint.index : sequenceRank.get(endpoint.index) ?? endpoint.index; const start = rank * (endpointSignal + sequenceGap); const progress = clamp((sequenceElapsed - start) / endpointSignal); if (progress > 0 && progress < 1.15) add(stateForIntensity("active", 0.78 + Math.sin(progress * Math.PI) * 0.22, endpoint.cell.id, "radial-signal-sequence")); else if (sequenceElapsed >= start + endpointSignal) add(stateForIntensity("trail", 0.42, endpoint.cell.id, "radial-signal-afterglow")); } if (elapsed >= pulseStart && options.synchronizedPulse !== false) { const pulse = Math.sin(clamp((elapsed - pulseStart) / pulseDuration) * Math.PI); for (const endpoint of endpoints) add(stateForIntensity("active", 0.62 + pulse * 0.38, endpoint.cell.id, "radial-signal-confirmation")); } } else if (elapsed >= returnStart && elapsed < settleStart && options.returnToCenter !== false) { const progress = smootherstep(0, returnDuration, elapsed - returnStart); for (const endpoint of endpoints) { const position = (endpoint.path.length - 1) * (1 - progress); addPath([...endpoint.path].reverse(), position, "radial-signal-return", 0.72); } } else if (elapsed >= settleStart && options.settle !== false) { for (const endpoint of endpoints) { add(stateForIntensity("idle", 0.16, endpoint.cell.id, "radial-signal-settled")); for (const cell of endpoint.path) add(stateForIntensity("idle", 0.08, "hex-" + cell.q + "-" + cell.r, "radial-signal-settled")); } } return toStateList(states); }