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.
284 lines
9.8 KiB
JavaScript
284 lines
9.8 KiB
JavaScript
/*
|
|
* Orbital Flight Simulator - physics core.
|
|
* Pure module: no DOM dependencies. Usable in the browser (window.OrbitalPhysics)
|
|
* and in Node (module.exports) for automated tests.
|
|
*
|
|
* Units: meters, seconds. Newtonian point-mass gravity: a = -mu * r_vec / |r|^3.
|
|
* Integration: classic RK4 on (pos, vel) with a FIXED timestep. Rotation is
|
|
* integrated with semi-implicit Euler (it is decoupled from the orbital motion).
|
|
*/
|
|
(function (global) {
|
|
'use strict';
|
|
|
|
var TAU = Math.PI * 2;
|
|
|
|
function len(v) { return Math.sqrt(v.x * v.x + v.y * v.y); }
|
|
|
|
function norm(v) {
|
|
var l = len(v);
|
|
return l > 1e-12 ? { x: v.x / l, y: v.y / l } : { x: 1, y: 0 };
|
|
}
|
|
|
|
function createWorld(opts) {
|
|
opts = opts || {};
|
|
return {
|
|
mu: opts.mu !== undefined ? opts.mu : 3e8,
|
|
planetRadius: opts.planetRadius !== undefined ? opts.planetRadius : 1000,
|
|
planet: { x: opts.planetX || 0, y: opts.planetY || 0 },
|
|
fixedDt: opts.fixedDt || 1 / 120,
|
|
landSpeed: opts.landSpeed !== undefined ? opts.landSpeed : 30,
|
|
landTangential: opts.landTangential !== undefined ? opts.landTangential : 50,
|
|
dockDistance: opts.dockDistance !== undefined ? opts.dockDistance : 20,
|
|
dockSpeed: opts.dockSpeed !== undefined ? opts.dockSpeed : 8
|
|
};
|
|
}
|
|
|
|
function createShip(opts) {
|
|
opts = opts || {};
|
|
var fuel = opts.fuel !== undefined ? opts.fuel : 100;
|
|
return {
|
|
pos: { x: opts.x || 0, y: opts.y || 0 },
|
|
vel: { x: opts.vx || 0, y: opts.vy || 0 },
|
|
angle: opts.angle || 0,
|
|
angVel: 0,
|
|
fuel: fuel,
|
|
maxFuel: fuel,
|
|
thrustAccel: opts.thrustAccel !== undefined ? opts.thrustAccel : 600,
|
|
fuelRate: opts.fuelRate !== undefined ? opts.fuelRate : 4,
|
|
radius: opts.radius !== undefined ? opts.radius : 6,
|
|
rotAccel: opts.rotAccel !== undefined ? opts.rotAccel : 5,
|
|
rotMax: opts.rotMax !== undefined ? opts.rotMax : 2.4,
|
|
state: 'flying',
|
|
time: 0
|
|
};
|
|
}
|
|
|
|
function createStation(opts) {
|
|
opts = opts || {};
|
|
return {
|
|
pos: { x: opts.x || 0, y: opts.y || 0 },
|
|
vel: { x: opts.vx || 0, y: opts.vy || 0 },
|
|
radius: opts.radius !== undefined ? opts.radius : 12,
|
|
angle: 0
|
|
};
|
|
}
|
|
|
|
// Newtonian gravity: acceleration toward the planet center, magnitude mu/r^2.
|
|
function gravityAt(world, pos) {
|
|
var dx = world.planet.x - pos.x;
|
|
var dy = world.planet.y - pos.y;
|
|
var r2 = dx * dx + dy * dy;
|
|
var r = Math.sqrt(r2);
|
|
var g = world.mu / r2;
|
|
return { x: (dx / r) * g, y: (dy / r) * g };
|
|
}
|
|
|
|
function accelAt(world, pos, angle, thrustMag) {
|
|
var g = gravityAt(world, pos);
|
|
if (thrustMag <= 0) return g;
|
|
return {
|
|
x: g.x + Math.cos(angle) * thrustMag,
|
|
y: g.y + Math.sin(angle) * thrustMag
|
|
};
|
|
}
|
|
|
|
// Classic RK4 step of the (pos, vel) state. The ship angle (and hence thrust
|
|
// direction) is held constant during the substep, which is exact to O(dt^2)
|
|
// for the rotation and negligible at our fixed dt.
|
|
function rk4Step(world, pos, vel, angle, thrustMag, dt) {
|
|
var k1v = accelAt(world, pos, angle, thrustMag);
|
|
var k1x = vel;
|
|
|
|
var p2 = { x: pos.x + k1x.x * dt * 0.5, y: pos.y + k1x.y * dt * 0.5 };
|
|
var v2 = { x: vel.x + k1v.x * dt * 0.5, y: vel.y + k1v.y * dt * 0.5 };
|
|
var k2v = accelAt(world, p2, angle, thrustMag);
|
|
var k2x = v2;
|
|
|
|
var p3 = { x: pos.x + k2x.x * dt * 0.5, y: pos.y + k2x.y * dt * 0.5 };
|
|
var v3 = { x: vel.x + k2v.x * dt * 0.5, y: vel.y + k2v.y * dt * 0.5 };
|
|
var k3v = accelAt(world, p3, angle, thrustMag);
|
|
var k3x = v3;
|
|
|
|
var p4 = { x: pos.x + k3x.x * dt, y: pos.y + k3x.y * dt };
|
|
var v4 = { x: vel.x + k3v.x * dt, y: vel.y + k3v.y * dt };
|
|
var k4v = accelAt(world, p4, angle, thrustMag);
|
|
var k4x = v4;
|
|
|
|
return {
|
|
pos: {
|
|
x: pos.x + (dt / 6) * (k1x.x + 2 * k2x.x + 2 * k3x.x + k4x.x),
|
|
y: pos.y + (dt / 6) * (k1x.y + 2 * k2x.y + 2 * k3x.y + k4x.y)
|
|
},
|
|
vel: {
|
|
x: vel.x + (dt / 6) * (k1v.x + 2 * k2v.x + 2 * k3v.x + k4v.x),
|
|
y: vel.y + (dt / 6) * (k1v.y + 2 * k2v.y + 2 * k3v.y + k4v.y)
|
|
}
|
|
};
|
|
}
|
|
|
|
// Advance the ship by dt. input = { thrust: 0..1, torque: -1..1 }.
|
|
function stepShip(world, ship, input, dt) {
|
|
input = input || { thrust: 0, torque: 0 };
|
|
if (ship.state !== 'flying') return;
|
|
|
|
var thrustLevel = Math.min(1, Math.max(0, input.thrust));
|
|
var wantsThrust = thrustLevel > 0 && ship.fuel > 0;
|
|
var thrustMag = wantsThrust ? ship.thrustAccel * thrustLevel : 0;
|
|
|
|
var s = rk4Step(world, ship.pos, ship.vel, ship.angle, thrustMag, dt);
|
|
ship.pos = s.pos;
|
|
ship.vel = s.vel;
|
|
|
|
if (input.torque > 0) {
|
|
ship.angVel = Math.min(ship.rotMax, ship.angVel + ship.rotAccel * dt);
|
|
} else if (input.torque < 0) {
|
|
ship.angVel = Math.max(-ship.rotMax, ship.angVel - ship.rotAccel * dt);
|
|
} else {
|
|
ship.angVel *= Math.max(0, 1 - 6 * dt);
|
|
if (Math.abs(ship.angVel) < 0.02) ship.angVel = 0;
|
|
}
|
|
ship.angle += ship.angVel * dt;
|
|
|
|
if (wantsThrust) {
|
|
ship.fuel = Math.max(0, ship.fuel - ship.fuelRate * thrustLevel * dt);
|
|
}
|
|
ship.time += dt;
|
|
}
|
|
|
|
// The station coasts on the same integrator (gravity only).
|
|
function stepStation(world, station, dt) {
|
|
var s = rk4Step(world, station.pos, station.vel, 0, 0, dt);
|
|
station.pos = s.pos;
|
|
station.vel = s.vel;
|
|
station.angle = (station.angle || 0) + dt * 0.3;
|
|
}
|
|
|
|
// Orbital elements from state vectors (two-body).
|
|
function orbitInfo(world, pos, vel) {
|
|
var dx = pos.x - world.planet.x;
|
|
var dy = pos.y - world.planet.y;
|
|
var r = Math.sqrt(dx * dx + dy * dy);
|
|
var v2 = vel.x * vel.x + vel.y * vel.y;
|
|
var speed = Math.sqrt(v2);
|
|
var energy = v2 / 2 - world.mu / r;
|
|
var bound = energy < 0;
|
|
var rv = (dx * vel.x + dy * vel.y) / r;
|
|
var h = dx * vel.y - dy * vel.x;
|
|
|
|
var eVec = {
|
|
x: ((v2 - world.mu / r) * dx - (dx * vel.x + dy * vel.y) * vel.x) / world.mu,
|
|
y: ((v2 - world.mu / r) * dy - (dx * vel.x + dy * vel.y) * vel.y) / world.mu
|
|
};
|
|
var e = Math.sqrt(eVec.x * eVec.x + eVec.y * eVec.y);
|
|
// semi-latus rectum p = h^2/mu (always >= 0). Periapsis = p/(1+e) is the
|
|
// correct positive closest-approach distance for BOTH ellipses and hyperbolas
|
|
// (the a*(1-e) / a*(e-1) forms go negative for unbound trajectories).
|
|
var p = (h * h) / world.mu;
|
|
|
|
var info = {
|
|
r: r,
|
|
speed: speed,
|
|
energy: energy,
|
|
bound: bound,
|
|
altitude: r - world.planetRadius,
|
|
radialVelocity: rv,
|
|
eccentricity: e,
|
|
h: h,
|
|
prograde: norm(vel)
|
|
};
|
|
|
|
if (bound) {
|
|
var a = -world.mu / (2 * energy);
|
|
info.semiMajor = a;
|
|
info.periapsis = p / (1 + e);
|
|
info.apoapsis = p / (1 - e);
|
|
info.period = TAU * Math.sqrt((a * a * a) / world.mu);
|
|
} else {
|
|
info.semiMajor = -world.mu / (2 * energy); // negative for hyperbola
|
|
info.periapsis = p / (1 + e); // positive closest-approach distance
|
|
info.apoapsis = Infinity;
|
|
info.period = Infinity;
|
|
info.escapeVelocity = Math.sqrt(2 * world.mu / r);
|
|
info.vinf = Math.sqrt(2 * energy);
|
|
}
|
|
return info;
|
|
}
|
|
|
|
// Surface interaction. Returns { type: 'none' | 'land' | 'crash', ... }.
|
|
function checkSurface(world, ship) {
|
|
var dx = ship.pos.x - world.planet.x;
|
|
var dy = ship.pos.y - world.planet.y;
|
|
var r = Math.sqrt(dx * dx + dy * dy);
|
|
var surfaceR = world.planetRadius + ship.radius * 0.4;
|
|
if (r > surfaceR) return { type: 'none' };
|
|
|
|
var n = { x: dx / r, y: dy / r }; // outward normal
|
|
var closing = -(ship.vel.x * n.x + ship.vel.y * n.y); // >0 when falling in
|
|
var tangent = Math.abs(ship.vel.x * -n.y + ship.vel.y * n.x);
|
|
// ship "down" vector; alignment near 1 means belly toward the surface
|
|
var down = { x: Math.cos(ship.angle + Math.PI / 2), y: Math.sin(ship.angle + Math.PI / 2) };
|
|
var align = -(down.x * n.x + down.y * n.y);
|
|
|
|
if (closing < world.landSpeed && tangent < world.landTangential && align > 0.5) {
|
|
return { type: 'land' };
|
|
}
|
|
return { type: 'crash', impactSpeed: Math.sqrt(ship.vel.x * ship.vel.x + ship.vel.y * ship.vel.y) };
|
|
}
|
|
|
|
// Coasting prediction using the EXACT same integrator as the simulation.
|
|
// Returns { points: [{x,y}], result: {type:'none'|'crash'|'land'|'far'} }.
|
|
function predictTrajectory(world, ship, opts) {
|
|
opts = opts || {};
|
|
var dt = opts.dt || world.fixedDt * 2;
|
|
var maxSteps = opts.maxSteps || 4000;
|
|
var sampleEvery = opts.sampleEvery || 4;
|
|
var maxRadius = opts.maxRadius || world.planetRadius * 12;
|
|
|
|
var pos = { x: ship.pos.x, y: ship.pos.y };
|
|
var vel = { x: ship.vel.x, y: ship.vel.y };
|
|
var points = [];
|
|
var result = { type: 'none' };
|
|
|
|
for (var i = 0; i < maxSteps; i++) {
|
|
var s = rk4Step(world, pos, vel, ship.angle, 0, dt);
|
|
pos = s.pos;
|
|
vel = s.vel;
|
|
if ((i + 1) % sampleEvery === 0) points.push({ x: pos.x, y: pos.y });
|
|
|
|
var r = Math.sqrt(
|
|
(pos.x - world.planet.x) * (pos.x - world.planet.x) +
|
|
(pos.y - world.planet.y) * (pos.y - world.planet.y)
|
|
);
|
|
if (r > maxRadius) { result = { type: 'far' }; break; }
|
|
|
|
var c = checkSurface(world, { pos: pos, vel: vel, angle: ship.angle, radius: ship.radius });
|
|
if (c.type !== 'none') {
|
|
result = c;
|
|
points.push({ x: pos.x, y: pos.y });
|
|
break;
|
|
}
|
|
}
|
|
return { points: points, result: result, dt: dt };
|
|
}
|
|
|
|
var api = {
|
|
TAU: TAU,
|
|
len: len,
|
|
norm: norm,
|
|
createWorld: createWorld,
|
|
createShip: createShip,
|
|
createStation: createStation,
|
|
gravityAt: gravityAt,
|
|
accelAt: accelAt,
|
|
rk4Step: rk4Step,
|
|
stepShip: stepShip,
|
|
stepStation: stepStation,
|
|
orbitInfo: orbitInfo,
|
|
checkSurface: checkSurface,
|
|
predictTrajectory: predictTrajectory
|
|
};
|
|
|
|
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
|
global.OrbitalPhysics = api;
|
|
})(typeof window !== 'undefined' ? window : globalThis);
|