Files
OpenFrontIO/src/core/game/UnitGrid.ts
T
aa4b490e68 Simplify WebGL renderer integration: remove dead extension code, untangle GameView naming (#4240)
## Summary

The WebGL renderer was adapted from an external extension and carried a
lot of machinery this integration never uses (replay playback, its own
input/event system, a GL radial menu). This PR is two mechanical cleanup
passes with **no behavior change**: delete the dead code, then untangle
the `GameView` naming collision.

**78 files, +142 / −2,197.**

### Pass 1 — remove dead extension baggage

- **Replay/copy mode**: `FrameData.tileMode` was hard-coded `"live"`;
the copy branches in `frame/Upload.ts`, `UploadOptions` (never passed),
`applyFullFrame`/`applyFullTiles`/`applyDelta` on the facade and
`GPURenderer`, `HeatManager.resetForSeek`, and the seek-upload methods
on `TerritoryPass`/`TrailPass` were all unreachable. Also deletes
`types/Replay.ts`, `types/FrameSource.ts`, `types/GameUpdates.ts`,
`types/Game.ts` (imported only by the types barrel).
- **FrameEvents**: trimmed from 14 fields to the 3 actually populated
and read (`deadUnits`, `conquestEvents`, `bonusEvents`). The other 11
fed the extension's stats system and were never written or read here.
- **GL radial menu**: `RadialMenuPass`, its 4 shaders, and ~10 API
methods on facade + renderer had zero callers — the game uses the DOM/d3
radial menu in `hud/layers/RadialMenu.ts`. The pass was constructed and
drawn every frame for nothing.
- **Facade event system**: `GameViewEventMap` defined 10 event types
(`click`, `hover`, `scroll`, …) but only `contextrestored` was ever
emitted — input actually flows through `InputHandler` → EventBus →
controllers. Replaced the listener map with a single `onContextRestored`
callback and deleted `Events.ts`. Also fixed the stale header comment
claiming the facade handles user interaction.
- **Unused API surface**: removed ~20 facade/renderer methods with zero
callers (camera passthroughs like
`panTo`/`zoomTo`/`fitMap`/`screenToWorld`, hit-testing queries, SAM
replay setters, `setSelectedUnit`, `clearFx`/`setFxTimeFn`,
`onFrame`/`afterRender`/fps tracking).

Deliberately left alone: `Camera`'s pan/zoom primitives (building blocks
for a possible future camera unification) and the `timeFn` plumbing
inside the FX passes (deeply embedded as defaults; only the dead
renderer-level wrappers were removed).

### Pass 2 — untangle the three GameViews

- `render/gl/GameView.ts` → **`MapRenderer.ts`** (class `MapRenderer`).
Every importer was already aliasing it as `WebGLGameView` to dodge the
collision with the simulation-mirror `GameView` in `client/view/`, so
this removes aliasing rather than adding churn. `render/CLAUDE.md`
updated.
- Deleted the `src/core/game/GameView.ts` back-compat shim (its own TODO
asked for this). All 51 importers now import from `src/client/view/`
directly via a new 3-line barrel `view/index.ts`.

## Test plan

- `tsc --noEmit` clean, `eslint` clean
- Full test suite passes (1,385 + 65 server tests)
- Manual verification via headless Chromium: started a singleplayer game
and confirmed the renderer works end-to-end — terrain draws, spawn-phase
overlay shows, territories fill with borders after spawning, player
names/flags render, no renderer console errors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 14:21:24 -07:00

302 lines
9.0 KiB
TypeScript

import { UnitView } from "../../client/view";
import { PlayerID, Unit, UnitType } from "./Game";
import { GameMap, TileRef } from "./GameMap";
export type UnitPredicate = (value: {
unit: Unit | UnitView;
distSquared: number;
}) => boolean;
export class UnitGrid {
private grid: Map<UnitType, Set<Unit | UnitView>>[][];
private readonly cellSize = 100;
constructor(private gm: GameMap) {
this.grid = Array(Math.ceil(gm.height() / this.cellSize))
.fill(null)
.map(() =>
Array(Math.ceil(gm.width() / this.cellSize))
.fill(null)
.map(() => new Map<UnitType, Set<Unit | UnitView>>()),
);
}
// Get grid coordinates from pixel coordinates
private getGridCoords(x: number, y: number): [number, number] {
return [Math.floor(x / this.cellSize), Math.floor(y / this.cellSize)];
}
// Add a unit to the grid
addUnit(unit: Unit | UnitView) {
const tile = unit.tile();
const [gridX, gridY] = this.getGridCoords(this.gm.x(tile), this.gm.y(tile));
if (this.isValidCell(gridX, gridY)) {
const unitSet = this.grid[gridY][gridX].get(unit.type());
if (unitSet !== undefined) {
unitSet.add(unit);
} else {
this.grid[gridY][gridX].set(
unit.type(),
new Set<Unit | UnitView>([unit]),
);
}
}
}
// Remove a unit from the grid
removeUnit(unit: Unit | UnitView) {
const tile = unit.tile();
this.removeUnitByTile(unit, tile);
}
removeUnitByTile(unit: Unit | UnitView, tile: TileRef) {
const [gridX, gridY] = this.getGridCoords(this.gm.x(tile), this.gm.y(tile));
if (this.isValidCell(gridX, gridY)) {
const unitSet = this.grid[gridY][gridX].get(unit.type());
if (unitSet !== undefined) {
unitSet.delete(unit);
}
}
}
/**
* Move an unit to its new cell if it changed
*/
updateUnitCell(unit: Unit | UnitView) {
const newTile = unit.tile();
const oldTile = unit.lastTile();
const [gridX, gridY] = this.getGridCoords(
this.gm.x(oldTile),
this.gm.y(oldTile),
);
const [newGridX, newGridY] = this.getGridCoords(
this.gm.x(newTile),
this.gm.y(newTile),
);
if (gridX !== newGridX || gridY !== newGridY) {
this.removeUnitByTile(unit, oldTile);
this.addUnit(unit);
}
}
private isValidCell(gridX: number, gridY: number): boolean {
return (
gridX >= 0 &&
gridX < this.grid[0].length &&
gridY >= 0 &&
gridY < this.grid.length
);
}
// Compute the exact cells in range of tile
private getCellsInRange(tile: TileRef, range: number) {
const x = this.gm.x(tile);
const y = this.gm.y(tile);
const cellSize = this.cellSize;
const [gridX, gridY] = this.getGridCoords(x, y);
const startGridX = Math.max(
0,
gridX - Math.ceil((range - (x % cellSize)) / cellSize),
);
const endGridX = Math.min(
this.grid[0].length - 1,
gridX + Math.ceil((range - (cellSize - (x % cellSize))) / cellSize),
);
const startGridY = Math.max(
0,
gridY - Math.ceil((range - (y % cellSize)) / cellSize),
);
const endGridY = Math.min(
this.grid.length - 1,
gridY + Math.ceil((range - (cellSize - (y % cellSize))) / cellSize),
);
return { startGridX, endGridX, startGridY, endGridY };
}
private squaredDistanceFromTile(
unit: Unit | UnitView,
tile: TileRef,
): number {
const x = this.gm.x(tile);
const y = this.gm.y(tile);
const tileX = this.gm.x(unit.tile());
const tileY = this.gm.y(unit.tile());
const dx = tileX - x;
const dy = tileY - y;
const distSquared = dx * dx + dy * dy;
return distSquared;
}
// Get all units within range of a point
// Returns [unit, distanceSquared] pairs for efficient filtering
nearbyUnits(
tile: TileRef,
searchRange: number,
types: readonly UnitType[] | UnitType,
predicate?: UnitPredicate,
includeUnderConstruction: boolean = false,
): Array<{ unit: Unit | UnitView; distSquared: number }> {
const nearby: Array<{ unit: Unit | UnitView; distSquared: number }> = [];
const gm = this.gm;
const x = gm.x(tile);
const y = gm.y(tile);
const { startGridX, endGridX, startGridY, endGridY } = this.getCellsInRange(
tile,
searchRange,
);
const rangeSquared = searchRange * searchRange;
if (Array.isArray(types)) {
for (let cy = startGridY; cy <= endGridY; cy++) {
for (let cx = startGridX; cx <= endGridX; cx++) {
const cell = this.grid[cy][cx];
for (const type of types) {
const unitSet = cell.get(type);
if (unitSet === undefined) continue;
for (const unit of unitSet) {
if (!unit.isActive()) continue;
// Exclude units under construction by default (e.g., defense posts being built)
// But include them for spacing checks
if (!includeUnderConstruction && unit.isUnderConstruction())
continue;
const unitTile = unit.tile();
const dx = gm.x(unitTile) - x;
const dy = gm.y(unitTile) - y;
const distSquared = dx * dx + dy * dy;
if (distSquared > rangeSquared) continue;
const value = { unit, distSquared };
if (predicate !== undefined && !predicate(value)) continue;
nearby.push(value);
}
}
}
}
return nearby;
}
const type = types;
for (let cy = startGridY; cy <= endGridY; cy++) {
for (let cx = startGridX; cx <= endGridX; cx++) {
const unitSet = this.grid[cy][cx].get(type as UnitType);
if (unitSet === undefined) continue;
for (const unit of unitSet) {
if (!unit.isActive()) continue;
// Exclude units under construction by default (e.g., defense posts being built)
// But include them for spacing checks
if (!includeUnderConstruction && unit.isUnderConstruction()) continue;
const unitTile = unit.tile();
const dx = gm.x(unitTile) - x;
const dy = gm.y(unitTile) - y;
const distSquared = dx * dx + dy * dy;
if (distSquared > rangeSquared) continue;
const value = { unit, distSquared };
if (predicate !== undefined && !predicate(value)) continue;
nearby.push(value);
}
}
}
return nearby;
}
private unitIsInRange(
unit: Unit | UnitView,
tile: TileRef,
rangeSquared: number,
playerId?: PlayerID,
includeUnderConstruction: boolean = false,
): boolean {
if (!unit.isActive()) {
return false;
}
// Exclude units under construction by default (e.g., defense posts being built)
// But include them for spacing checks
if (!includeUnderConstruction && unit.isUnderConstruction()) {
return false;
}
if (playerId !== undefined && unit.owner().id() !== playerId) {
return false;
}
const distSquared = this.squaredDistanceFromTile(unit, tile);
return distSquared <= rangeSquared;
}
// Return true if it finds an owned specific unit in range
hasUnitNearby(
tile: TileRef,
searchRange: number,
type: UnitType,
playerId?: PlayerID,
includeUnderConstruction: boolean = false,
): boolean {
const { startGridX, endGridX, startGridY, endGridY } = this.getCellsInRange(
tile,
searchRange,
);
const rangeSquared = searchRange * searchRange;
for (let cy = startGridY; cy <= endGridY; cy++) {
for (let cx = startGridX; cx <= endGridX; cx++) {
const unitSet = this.grid[cy][cx].get(type);
if (unitSet === undefined) continue;
for (const unit of unitSet) {
if (
this.unitIsInRange(
unit,
tile,
rangeSquared,
playerId,
includeUnderConstruction,
)
) {
return true;
}
}
}
}
return false;
}
// Return true if any unit of the given types matches the predicate
anyUnitNearby(
tile: TileRef,
searchRange: number,
types: readonly UnitType[],
predicate: (unit: Unit | UnitView) => boolean,
playerId?: PlayerID,
includeUnderConstruction: boolean = false,
): boolean {
const { startGridX, endGridX, startGridY, endGridY } = this.getCellsInRange(
tile,
searchRange,
);
const rangeSquared = searchRange * searchRange;
for (let cy = startGridY; cy <= endGridY; cy++) {
for (let cx = startGridX; cx <= endGridX; cx++) {
for (const type of types) {
const unitSet = this.grid[cy][cx].get(type);
if (unitSet === undefined) continue;
for (const unit of unitSet) {
if (
!this.unitIsInRange(
unit,
tile,
rangeSquared,
playerId,
includeUnderConstruction,
)
) {
continue;
}
if (predicate(unit)) {
return true;
}
}
}
}
}
return false;
}
}