Interactive 2D orbital flight simulator (HTML/CSS/JS, no dependencies). Newtonian gravity with RK4 integration, three scenarios (Surface Launch, Low Orbit, Station Rendezvous), trajectory prediction, camera/zoom, keyboard + touch controls, and automated unit + smoke tests.
269 lines
11 KiB
JavaScript
269 lines
11 KiB
JavaScript
/*
|
|
* Orbital Flight Simulator - unit tests (plain Node, no dependencies).
|
|
* Run: node tests/test.js
|
|
*/
|
|
'use strict';
|
|
|
|
var P = require('../js/physics.js');
|
|
|
|
var passed = 0;
|
|
var failed = 0;
|
|
|
|
function isInf(x) { return x === Infinity || x === -Infinity; }
|
|
|
|
function approx(a, b, tol) {
|
|
if (a !== a && b !== b) return true; // both NaN
|
|
if (isInf(a) && isInf(b) && (a > 0) === (b > 0)) return true;
|
|
var d = Math.abs(a - b);
|
|
var m = Math.max(Math.abs(a), Math.abs(b), 1);
|
|
return d <= tol * m;
|
|
}
|
|
|
|
function vecClose(a, b, tol) {
|
|
return approx(a.x, b.x, tol) && approx(a.y, b.y, tol);
|
|
}
|
|
|
|
function test(name, fn) {
|
|
try {
|
|
fn();
|
|
passed++;
|
|
console.log(' PASS ' + name);
|
|
} catch (e) {
|
|
failed++;
|
|
console.log(' FAIL ' + name);
|
|
console.log(' ' + (e && e.message ? e.message : e));
|
|
}
|
|
}
|
|
|
|
function assert(cond, msg) {
|
|
if (!cond) throw new Error(msg || 'assertion failed');
|
|
}
|
|
|
|
function assertClose(a, b, tol, msg) {
|
|
if (!approx(a, b, tol)) {
|
|
throw new Error((msg || 'close') + ': got ' + a + ', want ' + b + ' (tol ' + tol + ')');
|
|
}
|
|
}
|
|
|
|
var world = P.createWorld({}); // mu=3e8, R=1000
|
|
|
|
console.log('Orbital physics unit tests');
|
|
|
|
// ---- gravity ----
|
|
test('gravity magnitude at r=1000 is mu/r^2', function () {
|
|
var g = P.gravityAt(world, { x: 1000, y: 0 });
|
|
assertClose(Math.sqrt(g.x * g.x + g.y * g.y), world.mu / 1e6, 1e-12, '|g|');
|
|
});
|
|
|
|
test('gravity points toward the planet center', function () {
|
|
var g = P.gravityAt(world, { x: 1000, y: 0 });
|
|
assert(g.x < 0 && g.y === 0, 'should point -x');
|
|
var g2 = P.gravityAt(world, { x: 0, y: -2000 });
|
|
assert(g2.y > 0 && g2.x === 0, 'should point +y');
|
|
});
|
|
|
|
// ---- energy conservation (RK4, circular orbit, 10 orbits) ----
|
|
test('RK4 conserves orbital energy over 10 orbits', function () {
|
|
var r = 1500;
|
|
var v = Math.sqrt(world.mu / r);
|
|
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 1000 });
|
|
var e0 = P.orbitInfo(world, ship.pos, ship.vel).energy;
|
|
var dt = world.fixedDt;
|
|
var period = P.TAU * Math.sqrt((r * r * r) / world.mu);
|
|
var steps = Math.round((10 * period) / dt);
|
|
for (var i = 0; i < steps; i++) P.stepShip(world, ship, { thrust: 0, torque: 0 }, dt);
|
|
var e1 = P.orbitInfo(world, ship.pos, ship.vel).energy;
|
|
assertClose(e1, e0, 1e-4, 'energy drift over 10 orbits');
|
|
});
|
|
|
|
// ---- frame-rate independence ----
|
|
test('fixed-timestep accumulator is frame-rate independent', function () {
|
|
// Mirrors Game.frameImpl: each frame adds its real dt to an accumulator and
|
|
// runs as many fixed-dt steps as fit. The same real duration simulated at two
|
|
// different frame rates must produce (nearly) identical physics — the result
|
|
// depends only on total simulated time, not on the display refresh rate.
|
|
function runLoop(frameRate, realSeconds) {
|
|
var r = 1500;
|
|
var v = Math.sqrt(world.mu / r);
|
|
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 1000 });
|
|
var dt = world.fixedDt;
|
|
var frameDt = 1 / frameRate;
|
|
var accumulator = 0;
|
|
var elapsed = 0;
|
|
var steps = 0;
|
|
while (elapsed < realSeconds - 1e-12) {
|
|
var step = Math.min(frameDt, realSeconds - elapsed);
|
|
elapsed += step;
|
|
accumulator += step;
|
|
while (accumulator >= dt - 1e-12) {
|
|
P.stepShip(world, ship, { thrust: 0, torque: 0 }, dt);
|
|
accumulator -= dt;
|
|
steps++;
|
|
}
|
|
}
|
|
return { ship: ship, steps: steps };
|
|
}
|
|
var a = runLoop(60, 5);
|
|
var b = runLoop(144, 5);
|
|
// ~5 s of sim time => ~600 fixed steps; allow +/-1 for accumulator rounding
|
|
assert(Math.abs(a.steps - b.steps) <= 1, 'step counts differ: ' + a.steps + ' vs ' + b.steps);
|
|
assert(vecClose(a.ship.pos, b.ship.pos, 1e-3), 'positions differ: ' + JSON.stringify(a.ship.pos) + ' vs ' + JSON.stringify(b.ship.pos));
|
|
assert(vecClose(a.ship.vel, b.ship.vel, 1e-3), 'velocities differ');
|
|
});
|
|
|
|
test('different substep sizes stay close (tolerance)', function () {
|
|
function run(dt) {
|
|
var r = 1500;
|
|
var v = Math.sqrt(world.mu / r);
|
|
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 1000 });
|
|
var total = 60;
|
|
var steps = Math.round(total / dt);
|
|
for (var i = 0; i < steps; i++) P.stepShip(world, ship, { thrust: 0, torque: 0 }, dt);
|
|
return ship;
|
|
}
|
|
var a = run(1 / 120);
|
|
var b = run(1 / 60);
|
|
assert(vecClose(a.pos, b.pos, 1e-3), 'positions diverge: ' + JSON.stringify(a.pos) + ' vs ' + JSON.stringify(b.pos));
|
|
assert(vecClose(a.vel, b.vel, 1e-3), 'velocities diverge');
|
|
});
|
|
|
|
// ---- fuel ----
|
|
test('thrust consumes fuel at fuelRate per second', function () {
|
|
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500), fuel: 100, angle: 0 });
|
|
var f0 = ship.fuel;
|
|
var dt = world.fixedDt;
|
|
var n = Math.round(5 / dt); // 5 seconds of full thrust
|
|
for (var i = 0; i < n; i++) P.stepShip(world, ship, { thrust: 1, torque: 0 }, dt);
|
|
assertClose(f0 - ship.fuel, 5 * ship.fuelRate, 1e-6, 'fuel burned');
|
|
});
|
|
|
|
test('fuel never goes negative and thrust stops at zero fuel', function () {
|
|
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500), fuel: 1, angle: 0 });
|
|
var dt = world.fixedDt;
|
|
for (var i = 0; i < 2000; i++) P.stepShip(world, ship, { thrust: 1, torque: 0 }, dt);
|
|
assert(ship.fuel >= 0, 'fuel negative: ' + ship.fuel);
|
|
assert(ship.fuel === 0, 'fuel should be exactly 0');
|
|
});
|
|
|
|
test('no fuel means no thrust acceleration', function () {
|
|
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500), fuel: 0, angle: 0 });
|
|
var v0 = P.len(ship.vel);
|
|
P.stepShip(world, ship, { thrust: 1, torque: 0 }, world.fixedDt);
|
|
// gravity is perpendicular-ish here, speed change is tiny but must not include thrust
|
|
var info = P.orbitInfo(world, ship.pos, ship.vel);
|
|
assert(info.speed < v0 + 1, 'speed jumped: ' + info.speed + ' vs ' + v0);
|
|
});
|
|
|
|
// ---- collision ----
|
|
// surfaceR = planetRadius + radius*0.4 = 1002.4, so the ship must be at r<=1002.4
|
|
test('fast surface impact is a crash', function () {
|
|
var ship = P.createShip({ x: 1001, y: 0, vx: -200, fuel: 100 }); // slamming in along -x
|
|
var c = P.checkSurface(world, ship);
|
|
assert(c.type === 'crash', 'expected crash, got ' + c.type);
|
|
});
|
|
|
|
test('slow, aligned surface contact is a landing', function () {
|
|
var ship = P.createShip({ x: 1001, y: 0, vy: -10, fuel: 100, angle: Math.PI / 2 }); // nose up, belly down
|
|
var c = P.checkSurface(world, ship);
|
|
assert(c.type === 'land', 'expected land, got ' + c.type);
|
|
});
|
|
|
|
test('misaligned slow contact is a crash', function () {
|
|
var ship = P.createShip({ x: 1001, y: 0, vy: -10, fuel: 100, angle: 0 }); // nose sideways
|
|
var c = P.checkSurface(world, ship);
|
|
assert(c.type === 'crash', 'expected crash, got ' + c.type);
|
|
});
|
|
|
|
test('above the surface is no interaction', function () {
|
|
var ship = P.createShip({ x: 1200, y: 0, vy: -100, fuel: 100 });
|
|
var c = P.checkSurface(world, ship);
|
|
assert(c.type === 'none', 'expected none, got ' + c.type);
|
|
});
|
|
|
|
// ---- trajectory prediction ----
|
|
test('coasting prediction matches actual coasting', function () {
|
|
var r = 1500;
|
|
var v = Math.sqrt(world.mu / r) * 1.02;
|
|
var ship = P.createShip({ x: r, y: 0, vy: v, fuel: 100 });
|
|
var pred = P.predictTrajectory(world, ship, { dt: world.fixedDt * 2, maxSteps: 300, sampleEvery: 3 });
|
|
assert(pred.points.length > 10, 'too few points: ' + pred.points.length);
|
|
|
|
// points[k] is sampled after (k+1)*sampleEvery steps of dt
|
|
var k = 50;
|
|
var sampleEvery = 3;
|
|
var dt = world.fixedDt * 2;
|
|
var steps = (k + 1) * sampleEvery;
|
|
var actual = P.createShip({ x: r, y: 0, vy: v, fuel: 100 });
|
|
for (var i = 0; i < steps; i++) P.stepShip(world, actual, { thrust: 0, torque: 0 }, dt);
|
|
assert(vecClose(pred.points[k], actual.pos, 1e-9),
|
|
'prediction diverges: ' + JSON.stringify(pred.points[k]) + ' vs ' + JSON.stringify(actual.pos));
|
|
});
|
|
|
|
test('prediction flags a crash for a falling ship', function () {
|
|
var ship = P.createShip({ x: 1100, y: 0, vy: -50, fuel: 100 });
|
|
var pred = P.predictTrajectory(world, ship, { dt: world.fixedDt * 2, maxSteps: 2000, sampleEvery: 2 });
|
|
assert(pred.result.type === 'crash' || pred.result.type === 'land', 'expected surface hit, got ' + pred.result.type);
|
|
});
|
|
|
|
test('prediction flags escape for an unbound ship', function () {
|
|
var ship = P.createShip({ x: 1500, y: 0, vy: Math.sqrt(world.mu / 1500) * 1.5, fuel: 100 });
|
|
var pred = P.predictTrajectory(world, ship, { dt: world.fixedDt * 2, maxSteps: 4000, sampleEvery: 4 });
|
|
assert(pred.result.type === 'far', 'expected far/escape, got ' + pred.result.type);
|
|
});
|
|
|
|
// ---- orbit classification ----
|
|
test('circular orbit: e~0, bound, correct altitude', function () {
|
|
var r = 1500;
|
|
var v = Math.sqrt(world.mu / r);
|
|
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
|
assert(info.bound, 'should be bound');
|
|
assertClose(info.eccentricity, 0, 1e-9, 'eccentricity');
|
|
assertClose(info.periapsis, r, 1e-6, 'periapsis');
|
|
assertClose(info.apoapsis, r, 1e-6, 'apoapsis');
|
|
assertClose(info.altitude, r - world.planetRadius, 1e-9, 'altitude');
|
|
});
|
|
|
|
test('faster than circular gives an ellipse with higher apoapsis', function () {
|
|
var r = 1500;
|
|
var v = Math.sqrt(world.mu / r) * 1.1;
|
|
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
|
assert(info.bound, 'should still be bound');
|
|
assert(info.eccentricity > 0.05, 'ecc too small: ' + info.eccentricity);
|
|
assert(info.apoapsis > r && info.periapsis < r, 'apo > r > peri');
|
|
});
|
|
|
|
test('faster than escape gives an unbound trajectory', function () {
|
|
var r = 1500;
|
|
var v = Math.sqrt(2 * world.mu / r) * 1.1;
|
|
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
|
assert(!info.bound, 'should be unbound');
|
|
assert(info.energy > 0, 'energy should be positive');
|
|
});
|
|
|
|
test('escape trajectory has a positive periapsis (closest approach)', function () {
|
|
var r = 1500;
|
|
var v = Math.sqrt(world.mu / r) * 1.5; // well above circular => unbound
|
|
var info = P.orbitInfo(world, { x: r, y: 0 }, { x: 0, y: v });
|
|
assert(!info.bound, 'should be unbound');
|
|
assert(info.periapsis > 0, 'periapsis must be positive, got ' + info.periapsis);
|
|
// purely tangential velocity => currently at periapsis (closest approach)
|
|
assertClose(info.periapsis, r, 1e-6, 'periapsis equals current radius');
|
|
});
|
|
|
|
test('station coasts on a stable circular orbit', function () {
|
|
var rs = 1800;
|
|
var vs = Math.sqrt(world.mu / rs);
|
|
var st = P.createStation({ x: 0, y: -rs, vx: vs, radius: 12 });
|
|
var dt = world.fixedDt;
|
|
var period = P.TAU * Math.sqrt((rs * rs * rs) / world.mu);
|
|
var steps = Math.round(period / dt);
|
|
for (var i = 0; i < steps; i++) P.stepStation(world, st, dt);
|
|
var rNow = Math.sqrt(st.pos.x * st.pos.x + st.pos.y * st.pos.y);
|
|
assertClose(rNow, rs, 1e-3, 'station radius drift');
|
|
});
|
|
|
|
// ---- summary ----
|
|
console.log('');
|
|
console.log(passed + ' passed, ' + failed + ' failed');
|
|
if (failed > 0) process.exit(1);
|