Files
FFF_vtt_frozen/client/src/tiles.ts
T
SirStone 9c05bb1f46 fix(client): make data-tiles ready when the pass completes
A transient tile load error is terminal for the current window (retried only on
a new window or a reconnect), but data-tiles treated it as never settled, so one
host hiccup left it at 'loading' forever and every e2e readiness wait hung
(audit.test.mjs timed out under a parallel lane). TileScheduler.isPending() now
reports loading only for queued/in-flight tiles; ready means the pass is done.
Proven by aborting one tile request: the wait timed out before, passes after.
Unit-tested at the scheduler seam.
2026-11-21 18:19:47 +01:00

195 lines
7.2 KiB
TypeScript

// The tile scheduler (#69, spec #63 decision 12). Pure: the loader is injected, so the concurrency,
// cache and denial rules are unit-tested without a browser or a GPU.
//
// Rules encoded here:
// - at most TILE_CONCURRENCY (8) requests in flight;
// - the wanted list is the viewport plus one tile of margin, in viewport order;
// - a tile is never fetched twice (a decoded texture is cached by the tile module across a
// reconnect; this scheduler remembers settled URLs too);
// - a `403`/`404` is a permanent `denied` answer: never retried in a loop (the server said no);
// - a transient `error` is retried only when a later viewport sync asks for the tile again;
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
// prefetches beyond the margin;
// - a denied tile is asked again only when the fog says its cells just became explored (#70):
// the gate's answer changed, so the old "no" is stale.
import type { SceneInfo } from './protocol.ts'
import { tileUrl } from './viewport.ts'
export const TILE_CONCURRENCY = 8
export type TileLoadResult = 'ok' | 'denied' | 'error'
export type TileStatus = 'queued' | 'loading' | 'ok' | 'denied' | 'error'
export interface TileSchedulerOptions {
load(url: string): Promise<TileLoadResult>
onSettled?(url: string, result: TileLoadResult): void
onIdle?(): void
concurrency?: number
}
function sameList(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
return true
}
/**
* The tile urls touched by a set of explored cells (fog slice indices, row-major). v1 has
* `cell == tile_size` (DESIGN 8), but the maths keeps a cell-to-tile mapping general.
*/
export function tilesForCells(
scene: Pick<SceneInfo, 'id' | 'art_version' | 'tile_size'>,
grid: { cols: number; cell: number },
cells: Iterable<number>,
): string[] {
const tileSize = scene.tile_size
if (!(tileSize > 0) || grid.cell <= 0 || grid.cols <= 0) return []
const urls = new Set<string>()
for (const index of cells) {
const cx = index % grid.cols
const cy = (index / grid.cols) | 0
const tx = Math.floor((cx * grid.cell) / tileSize)
const ty = Math.floor((cy * grid.cell) / tileSize)
urls.add(tileUrl(scene, tx, ty))
}
return [...urls]
}
export class TileScheduler {
readonly #load: (url: string) => Promise<TileLoadResult>
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
readonly #onIdle: (() => void) | undefined
readonly #concurrency: number
#states = new Map<string, TileStatus>()
#queue: string[] = []
#desired = new Set<string>()
#lastDesired: readonly string[] = []
#active = 0
#idle = true
constructor(options: TileSchedulerOptions) {
this.#load = options.load
this.#onSettled = options.onSettled
this.#onIdle = options.onIdle
this.#concurrency = Math.max(1, options.concurrency ?? TILE_CONCURRENCY)
}
status(url: string): TileStatus | undefined {
return this.#states.get(url)
}
get active(): number {
return this.#active
}
/** What the viewport wants now. `urls` is already in viewport order. */
setDesired(urls: readonly string[]): void {
// A settle calls back into the renderer, which syncs again with the same window; skip the
// O(n) rebuild in that common case. It still pumps, which is what opens the next slot.
if (sameList(urls, this.#lastDesired)) {
this.#pump()
return
}
this.#lastDesired = [...urls]
this.#desired = new Set(urls)
// Keep queued entries that are still wanted, in the new viewport order; forget the rest so a
// later viewport that asks for the tile again can queue it fresh.
const order = new Map(urls.map((url, index) => [url, index]))
const dropped = this.#queue.filter(url => !this.#desired.has(url))
for (const url of dropped) this.#states.delete(url)
this.#queue = this.#queue
.filter(url => this.#desired.has(url))
.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))
for (const url of urls) {
const existing = this.#states.get(url)
if (existing === 'error') this.#states.delete(url)
else if (existing !== undefined) continue
this.#states.set(url, 'queued')
this.#queue.push(url)
}
this.#pump()
}
/** A texture already in the cache (e.g. a renderer remount) needs no request. */
markLoaded(url: string): void {
if (!this.#states.has(url)) this.#states.set(url, 'ok')
}
/** Forget transient failures: the next sync (e.g. after a reconnect) may ask again. */
retryFailed(): void {
for (const [url, status] of this.#states) if (status === 'error') this.#states.delete(url)
this.#lastDesired = []
}
/**
* A `403` is permanent *for the explored set the server had then*. When the fog slice reports
* newly explored cells (#70), the tiles those cells touch may have become allowed, so those
* denied urls are forgotten and the next `setDesired` asks for them exactly once more. Nothing
* else is retried: an unexplored 403 stays denied (no retry loop).
*/
retryDenied(urls: Iterable<string>): void {
let changed = false
for (const url of urls) {
if (this.#states.get(url) !== 'denied') continue
this.#states.delete(url)
changed = true
}
// The next setDesired rebuilds the queue, which re-queues the forgotten urls as `queued`.
if (changed) this.#lastDesired = []
}
/**
* True while any wanted tile still has to settle on this pass (queued, loading, or not yet
* asked). A stored `error` is *terminal for this pass*: it is only retried on a new window or
* after `retryFailed()`, so it must not keep a readiness probe waiting forever.
*/
isPending(urls: readonly string[]): boolean {
return urls.some(url => {
const status = this.#states.get(url)
return status === undefined || status === 'queued' || status === 'loading'
})
}
/** True when every wanted tile settled with an `ok` or `denied` answer. */
isComplete(urls: readonly string[]): boolean {
return urls.every(url => {
const status = this.#states.get(url)
return status === 'ok' || status === 'denied'
})
}
#pump(): void {
while (this.#active < this.#concurrency && this.#queue.length > 0) {
const url = this.#queue.shift()
if (url === undefined) break
if (!this.#desired.has(url) || this.#states.get(url) !== 'queued') continue
this.#states.set(url, 'loading')
this.#active += 1
this.#idle = false
void this.#load(url).then(
result => this.#settle(url, result),
() => this.#settle(url, 'error'),
)
}
if (this.#active === 0 && this.#queue.length === 0 && !this.#idle) {
this.#idle = true
this.#onIdle?.()
}
}
#settle(url: string, result: TileLoadResult): void {
this.#active -= 1
if (result === 'ok' || result === 'denied') {
this.#states.set(url, result)
} else {
// Transient: remember the failure, but never retry it on the same viewport; only a new
// window or `retryFailed()` (reconnect) asks again. A denied 403 is never retried at all.
this.#states.set(url, 'error')
}
this.#onSettled?.(url, result)
this.#pump()
}
}