Files
agentic-labs-challenge/underdepths/engine/fov.py
T
2026-08-14 09:46:04 +02:00

95 lines
2.9 KiB
Python

"""Recursive shadowcasting field of view over 8 octants."""
from __future__ import annotations
from typing import Any
from data.constants import FLOOR, SIGHT_RADIUS
# (xx, xy, yx, yy) transforms covering the 8 octants around the origin.
_OCTANTS: tuple[tuple[int, int, int, int], ...] = (
( 1, 0, 0, 1),
( 0, 1, 1, 0),
( 0, -1, 1, 0),
(-1, 0, 0, 1),
(-1, 0, 0, -1),
( 0, -1, -1, 0),
( 0, 1, -1, 0),
( 1, 0, 0, -1),
)
def compute_fov(
game_map: Any, origin: tuple[int, int], radius: int = SIGHT_RADIUS
) -> set[tuple[int, int]]:
"""Set of tiles visible from ``origin`` within ``radius``.
Walls block sight but a wall touched by the beam is itself reported
visible (so it renders as a seen wall when adjacent to lit floor).
"""
tiles = game_map.tiles
cx, cy = origin
r2 = radius * radius
visible: set[tuple[int, int]] = {(cx, cy)}
def blocks(x: int, y: int) -> bool:
if not game_map.in_bounds(x, y):
return True
return tiles[y][x] != FLOOR
def cast(row: int, start: float, end: float,
xx: int, xy: int, yx: int, yy: int) -> None:
if start < end:
return
for j in range(row, radius + 1):
dx = -j - 1
dy = -j
blocked = False
new_start = end
while dx <= 0:
dx += 1
mx = cx + dx * xx + dy * xy
my = cy + dx * yx + dy * yy
l_slope = (dx - 0.5) / (dy + 0.5)
r_slope = (dx + 0.5) / (dy - 0.5)
if start < r_slope:
continue
if end > l_slope:
break
if dx * dx + dy * dy <= r2 and game_map.in_bounds(mx, my):
visible.add((mx, my))
if blocked:
if blocks(mx, my):
new_start = r_slope
continue
blocked = False
start = new_start
elif blocks(mx, my) and j < radius:
blocked = True
cast(j + 1, start, l_slope, xx, xy, yx, yy)
new_start = r_slope
# Row ended inside a wall run: deeper rows are fully occluded.
if blocked:
break
for xx, xy, yx, yy in _OCTANTS:
cast(1, 1.0, 0.0, xx, xy, yx, yy)
return visible
if __name__ == "__main__":
import random
from engine.map_gen import generate_dungeon
gm = generate_dungeon(seed=1)[0]
sx, sy = gm.spawn or (gm.width // 2, gm.height // 2)
seen = compute_fov(gm, (sx, sy))
for y in range(gm.height):
print("".join(
"@" if (x, y) == (sx, sy) else
"o" if (x, y) in seen else
("." if gm.walkable(x, y) else "#")
for x in range(gm.width)
))
print(f"visible={len(seen)} (random seed used only by map_gen)", random.random())