fertig-classic-games/tools/verifyWolfenstein.js

294 lines
15 KiB
JavaScript

#!/usr/bin/env node
// Verifies the Wolfenstein engine end to end, headlessly.
//
// node tools/verifyWolfenstein.js [--quick]
//
// WolfensteinRules/WolfensteinRaycaster/WolfensteinLogic import no Phaser. Sections 1-5 use a
// small hand-built synthetic test map so raycaster distances and swept-bullet-collision
// outcomes can be asserted against hand-computed expected values. Sections 6+ (added once the
// authoring pipeline exists) validate the actual shipped level/campaign JSON.
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { compileRules } from '../src/games/wolfenstein/WolfensteinRules.js';
import { castRay, hasLineOfSight, makeCamera, castColumns } from '../src/games/wolfenstein/WolfensteinRaycaster.js';
import * as L from '../src/games/wolfenstein/WolfensteinLogic.js';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const QUICK = process.argv.includes('--quick');
const rulesJson = JSON.parse(readFileSync(join(ROOT, 'data/wolfenstein-rules.json'), 'utf8'));
const rules = compileRules(rulesJson);
let pass = 0; const failures = [];
function check(name, cond, detail) {
if (cond) { pass++; return true; }
failures.push(detail ? `${name}${detail}` : name);
return false;
}
function section(title) { console.log(`\n── ${title}`); }
function near(a, b, eps = 1e-3) { return Math.abs(a - b) < eps; }
// ---------------------------------------------------------------------------
section('1. Rules integrity');
// ---------------------------------------------------------------------------
{
check('fists weapon defined', !!rules.weaponById.fists);
check('pistol weapon defined', !!rules.weaponById.pistol);
check('guard enemy defined', !!rules.enemyById.guard);
for (const w of rules.weapons) {
check(`${w.id} has positive damage`, w.damage > 0);
check(`${w.id} has positive cooldown`, w.cooldownMs > 0);
}
for (const e of rules.enemies) {
check(`${e.id} has positive health`, e.health > 0);
check(`${e.id} detectRange >= fireRange`, e.detectRange >= e.fireRange);
}
check('tickHz positive', rules.constants.tickHz > 0);
check('stepMs matches tickHz', near(rules.stepMs, 1000 / rules.constants.tickHz));
}
// ---------------------------------------------------------------------------
// A small synthetic 8x8 test map, hand-computable:
// row0: border row3: internal wall at columns 3-4 (a 2-cell-thick wall)
// rows1-6: open interior except row3's columns 3-4
// row7: border
// ---------------------------------------------------------------------------
function makeTestMap() {
const W = 8, H = 8;
const walls = [];
for (let y = 0; y < H; y++) {
const row = [];
for (let x = 0; x < W; x++) {
const border = x === 0 || y === 0 || x === W - 1 || y === H - 1;
const internal = y === 3 && (x === 3 || x === 4);
row.push(border || internal ? 1 : 0);
}
walls.push(row);
}
return { width: W, height: H, walls };
}
// ---------------------------------------------------------------------------
section('2. Raycaster correctness (hand-computed distances)');
// ---------------------------------------------------------------------------
{
const map = makeTestMap();
const east = castRay(map, 1.5, 1.5, 1, 0);
check('east ray hits east boundary', east && east.mapX === 7 && east.mapY === 1, JSON.stringify(east));
check('east ray perpDist matches hand calc', east && near(east.perpDist, 5.5), east?.perpDist);
check('east ray is an X-side hit', east && east.side === 0);
const south = castRay(map, 1.5, 1.5, 0, 1);
check('south ray hits south boundary', south && south.mapX === 1 && south.mapY === 7, JSON.stringify(south));
check('south ray perpDist matches hand calc', south && near(south.perpDist, 5.5), south?.perpDist);
check('south ray is a Y-side hit', south && south.side === 1);
const internal = castRay(map, 1.5, 3.5, 1, 0);
check('ray hits internal wall, not the far boundary', internal && internal.mapX === 3 && internal.mapY === 3, JSON.stringify(internal));
check('internal wall perpDist matches hand calc', internal && near(internal.perpDist, 1.5), internal?.perpDist);
// No ray fired from inside a closed room should ever escape the map.
let escapes = 0;
const angleSamples = QUICK ? 16 : 180;
const points = [[1.5, 1.5], [4.5, 4.5], [2.5, 5.5]];
for (const [px, py] of points) {
for (let i = 0; i < angleSamples; i++) {
const a = (i / angleSamples) * Math.PI * 2;
const hit = castRay(map, px, py, Math.cos(a), Math.sin(a));
if (!hit) escapes++;
}
}
check('no ray escapes the closed test room', escapes === 0, `${escapes} escaped`);
// castColumns / makeCamera smoke test — every column should return a hit.
const cam = makeCamera(1.5, 1.5, 0, rules.fov);
const cols = castColumns(map, cam, 64);
check('castColumns returns one entry per column', cols.length === 64);
check('every column hits a wall', cols.every((c) => c !== null));
// Line of sight: clear along an open row, blocked through the internal wall.
check('LOS clear along open row', hasLineOfSight(map, 1.5, 1.5, 6.5, 1.5));
check('LOS blocked by internal wall', !hasLineOfSight(map, 1.5, 3.5, 6.5, 3.5));
}
// ---------------------------------------------------------------------------
section('3. Bullet swept-collision correctness');
// ---------------------------------------------------------------------------
{
const level = {
id: 'test', name: 'Test', width: 8, height: 8, cellSize: 64,
walls: makeTestMap().walls,
playerStart: { x: 1.5, y: 1.5, angle: 0 },
doors: [], enemies: [], items: [],
exit: { x: 6.5, y: 6.5, radius: 0.6 },
};
// A target far enough from the projectile's start AND end position that a
// point-sample test would miss it entirely, but the swept segment between
// them passes right through it.
{
const state = L.createState(level, rules);
state.enemies.push({ id: 0, defId: 'guard', x: 5.0, y: 1.5, angle: 0, health: rules.enemyById.guard.health, state: 'idle', cooldownMs: 0, dead: false, radius: rules.enemyById.guard.radius });
const startX = 4.3, endGuessX = 5.7; // both >0.53 from the target — a point-sample test would see a miss at either end
const vx = (endGuessX - startX) * rules.constants.tickHz;
state.projectiles.push({ id: 99, ownerId: 'player', weapon: 'pistol', friendly: true, x: startX, y: 1.5, px: startX, py: 1.5, vx, vy: 0, damage: 20, hitRadius: rules.weaponById.pistol.hitRadius, ttl: 60 });
L.tick(state, rules);
check('fast bullet whose endpoints both miss still registers via the swept segment', state.enemies[0].health < rules.enemyById.guard.health, `health=${state.enemies[0].health}`);
}
// A bullet fast enough to fully cross a 1-cell-thick wall within one tick —
// point-sampling only the tick's end position would see open floor on the
// far side and miss the wall entirely.
{
const W = 10, H = 3;
const row = new Array(W).fill(0);
row[4] = 1; // single-cell wall
const thinWallMap = { width: W, height: H, walls: [new Array(W).fill(1), row, new Array(W).fill(1)] };
const state = L.createState({ ...level, width: W, height: H, walls: thinWallMap.walls, playerStart: { x: 1.5, y: 1.5, angle: 0 }, exit: { x: 8.5, y: 1.5, radius: 0.6 } }, rules);
const startX = 2.0, endGuessX = 5.0; // crosses the wall at x=4..5 entirely within one tick
const vx = (endGuessX - startX) * rules.constants.tickHz;
state.projectiles.push({ id: 1, ownerId: 'player', weapon: 'pistol', friendly: true, x: startX, y: 1.5, px: startX, py: 1.5, vx, vy: 0, damage: 20, hitRadius: rules.weaponById.pistol.hitRadius, ttl: 60 });
const events = L.tick(state, rules);
const impact = events.find((e) => e.t === 'impact');
check('fast bullet detonates on a thin wall it crosses mid-tick', !!impact, JSON.stringify(events));
check('impact lands at the wall face, not past it', impact && impact.x < 4.5 && impact.x >= 4, impact?.x);
check('projectile is removed after the wall hit', state.projectiles.length === 0);
}
// A clean miss must not falsely register a hit.
{
const state = L.createState(level, rules);
state.enemies.push({ id: 0, defId: 'guard', x: 5.0, y: 5.5, angle: 0, health: rules.enemyById.guard.health, state: 'idle', cooldownMs: 0, dead: false, radius: rules.enemyById.guard.radius });
state.projectiles.push({ id: 1, ownerId: 'player', weapon: 'pistol', friendly: true, x: 1.5, y: 1.5, px: 1.5, py: 1.5, vx: 11, vy: 0, damage: 20, hitRadius: rules.weaponById.pistol.hitRadius, ttl: 60 });
L.tick(state, rules);
check('a deliberately wide shot does not falsely register a hit', state.enemies[0].health === rules.enemyById.guard.health);
check('a surviving projectile is kept, not detonated', state.projectiles.length === 1);
}
}
// ---------------------------------------------------------------------------
section('4. Enemy AI');
// ---------------------------------------------------------------------------
{
const baseLevel = {
id: 'test', name: 'Test', width: 8, height: 8, cellSize: 64,
walls: makeTestMap().walls, doors: [], items: [],
exit: { x: 6.5, y: 6.5, radius: 0.6 },
};
// No line of sight (blocked by the row-3 internal wall) — should never alert.
{
const level = { ...baseLevel, playerStart: { x: 1.5, y: 3.5, angle: 0 }, enemies: [{ type: 'guard', x: 6.5, y: 3.5, facing: 180 }] };
const state = L.createState(level, rules);
for (let i = 0; i < 300; i++) L.tick(state, rules);
check('guard with no line of sight stays idle', state.enemies[0].state === 'idle', state.enemies[0].state);
}
// Clear line of sight within detectRange — should alert within a bounded number of ticks.
{
const level = { ...baseLevel, playerStart: { x: 1.5, y: 1.5, angle: 0 }, enemies: [{ type: 'guard', x: 5.5, y: 1.5, facing: 180 }] };
const state = L.createState(level, rules);
let alerted = false;
for (let i = 0; i < 10 && !alerted; i++) { L.tick(state, rules); alerted = state.enemies[0].state !== 'idle'; }
check('guard with clear line of sight alerts promptly', alerted);
}
// A dead guard stops acting and can't be hit/killed twice.
{
const level = { ...baseLevel, playerStart: { x: 1.5, y: 1.5, angle: 0 }, enemies: [{ type: 'guard', x: 3.5, y: 1.5, facing: 180 }] };
const state = L.createState(level, rules);
L.setFireHeld(state, true);
L.switchWeapon(state, 'pistol');
let deaths = 0;
for (let i = 0; i < 600 && state.enemies[0].health > 0; i++) {
const events = L.tick(state, rules);
deaths += events.filter((e) => e.t === 'enemyDied').length;
}
check('guard actually dies within the simulated window', state.enemies[0].dead, `health=${state.enemies[0].health}`);
check('enemyDied fires exactly once', deaths === 1, `fired ${deaths} times`);
const healthAtDeath = state.enemies[0].health;
for (let i = 0; i < 60; i++) L.tick(state, rules);
check('dead guard takes no further actions/damage', state.enemies[0].health === healthAtDeath && state.enemies[0].state === 'dead');
}
}
// ---------------------------------------------------------------------------
section('5. Save/load round-trip');
// ---------------------------------------------------------------------------
{
const level = {
id: 'test', name: 'Test', width: 8, height: 8, cellSize: 64,
walls: makeTestMap().walls,
playerStart: { x: 1.5, y: 1.5, angle: 0.3 },
doors: [{ x: 2, y: 5, orientation: 'vertical' }],
enemies: [{ type: 'guard', x: 5.5, y: 5.5, facing: 90 }],
items: [{ type: 'health', x: 4.5, y: 4.5 }],
exit: { x: 6.5, y: 6.5, radius: 0.6 },
};
const state = L.createState(level, rules);
L.setMoveIntent(state, 1, 0.3);
for (let i = 0; i < 30; i++) L.tick(state, rules);
const raw = L.serialize(state);
const restored = L.deserialize(rules, raw);
check('deserialize succeeds', !!restored);
check('player position round-trips', restored && near(restored.player.x, state.player.x) && near(restored.player.y, state.player.y));
check('player health round-trips', restored && restored.player.health === state.player.health);
check('enemy state round-trips', restored && restored.enemies[0].x === state.enemies[0].x && restored.enemies[0].health === state.enemies[0].health);
check('wall grid RLE round-trips byte-identical', restored && JSON.stringify(restored.map.walls) === JSON.stringify(state.map.walls));
check('tick count round-trips', restored && restored.tick === state.tick);
const badVersion = JSON.stringify({ ...JSON.parse(raw), v: 999 });
check('a save stamped with a future version is rejected, not thrown', L.deserialize(rules, badVersion) === null);
check('garbage input is rejected, not thrown', L.deserialize(rules, '{not json') === null);
}
// ---------------------------------------------------------------------------
// Sections 6+: shipped level/campaign data (present once the authoring
// pipeline — tools/genWolfenstein.js + data/wolfenstein-campaigns.json —
// exists; skipped gracefully before then so this script is runnable from
// step 1 of the build, per the plan's phasing).
// ---------------------------------------------------------------------------
import { existsSync } from 'fs';
const campaignPath = join(ROOT, 'data/wolfenstein-campaigns.json');
if (existsSync(campaignPath)) {
section('6. Level solvability + campaign/editor schema parity');
const campaigns = JSON.parse(readFileSync(campaignPath, 'utf8'));
for (const camp of campaigns.campaigns) {
let cleared = 0;
for (const m of camp.missions) {
const levelPath = join(ROOT, 'assets/gamedata/wolfenstein', m.levelFile);
const levelJson = JSON.parse(readFileSync(levelPath, 'utf8'));
const model = L.buildLevelModel(levelJson);
const result = L.validateLevel(model);
check(`${camp.id}/${m.id} (${m.levelFile}) validates`, result.valid, result.issues.join('; '));
check(`${camp.id}/${m.id} exit is reachable from playerStart`, result.reachable);
cleared++;
}
check(`${camp.id} mission count matches its data`, cleared === camp.missions.length);
}
section('7. Campaign progress gating (boundary values)');
for (const camp of campaigns.campaigns) {
const n = camp.missions.length;
for (const cleared of [0, 1, n]) {
const unlocked = camp.missions.map((_, i) => i <= cleared);
const expectedUnlocked = Math.min(cleared + 1, n);
const actualUnlocked = unlocked.filter(Boolean).length;
check(`${camp.id} cleared=${cleared} unlocks exactly ${expectedUnlocked} mission(s)`, actualUnlocked === expectedUnlocked, `got ${actualUnlocked}`);
}
}
} else {
console.log('\n(skipping level/campaign sections — data/wolfenstein-campaigns.json not present yet)');
}
// ---------------------------------------------------------------------------
console.log(`\n${pass} checks passed, ${failures.length} failed.`);
if (failures.length) {
console.log('\nFailures:');
for (const f of failures) console.log(` - ${f}`);
process.exit(1);
}