Files
WT-Offline/apps/ai-lab/src/data.ts
T

57 lines
1.8 KiB
TypeScript

/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */
import {
decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle,
} from '@wto/ground-sim';
export interface LogEntry {
readonly name: string;
readonly size: number;
readonly mtime: number;
}
export interface MapEntry {
readonly level: string;
readonly pois: boolean;
/** The level's geometry is there, so it has a 3D map. */
readonly scene: boolean;
}
export interface MapData {
readonly pack: NavPack;
readonly pois: MapPois | undefined;
readonly scene: MapScene | undefined;
}
async function get(url: string): Promise<Response> {
const res = await fetch(url);
if (!res.ok) {
const body = await res.text();
throw new Error(`${url}: ${res.status} ${body}`);
}
return res;
}
export async function fetchMaps(): Promise<MapEntry[]> {
return (await (await get('/api/maps')).json()) as MapEntry[];
}
export async function fetchLogs(): Promise<LogEntry[]> {
return (await (await get('/api/logs')).json()) as LogEntry[];
}
export async function loadLog(name: string): Promise<TraceBattle[]> {
const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text();
return parseTraceLog(text);
}
export async function loadMap(entry: MapEntry): Promise<MapData> {
const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer());
const pois = entry.pois
? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text())
: undefined;
const scene = entry.scene
? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer()))
: undefined;
return { pack: readNavPack(bytes), pois, scene };
}