/* * Orbital Flight Simulator - game orchestration. * Owns the fixed-timestep loop, camera, time acceleration, scenarios, * docking/landing/crash resolution, and visual exhaust particles. */ (function (global) { 'use strict'; var P = global.OrbitalPhysics; var TIME_SCALES = [1, 2, 5, 10]; var SCENARIOS = { launch: { id: 'launch', name: 'Surface Launch', blurb: 'Liftoff from the launch pad. Establish a stable orbit.', goal: 'orbit', goalText: 'Goal: bound orbit with periapsis above 150 m', setup: function (world) { var R = world.planetRadius; // ship sits on the +x axis; "away from the planet" is +x => angle 0 var ship = P.createShip({ x: R + 10, y: 0, angle: 0, fuel: 100 }); var r = 1800; var v = Math.sqrt(world.mu / r); var station = P.createStation({ x: 0, y: -r, vx: v, radius: 12 }); return { ship: ship, station: station }; } }, loworbit: { id: 'loworbit', name: 'Low Orbit', blurb: 'You are already orbiting. Rendezvous with the station.', goal: 'station', goalText: 'Goal: dock with the station (inside ring, low rel. speed)', setup: function (world) { var r = 1400; var v = Math.sqrt(world.mu / r); var ship = P.createShip({ x: r, y: 0, vy: v, angle: Math.PI / 2, fuel: 60 }); var rs = 1800; var vs = Math.sqrt(world.mu / rs); var station = P.createStation({ x: 0, y: -rs, vx: vs, radius: 12 }); return { ship: ship, station: station }; } }, rendezvous: { id: 'rendezvous', name: 'Station Rendezvous', blurb: 'You are on an elliptical orbit below the station. Match it and dock.', goal: 'station', goalText: 'Goal: dock with the station (inside ring, low rel. speed)', setup: function (world) { var r = 1600; var v = Math.sqrt(world.mu / r) * 1.08; var ship = P.createShip({ x: r, y: 0, vy: v, angle: Math.PI / 2, fuel: 80 }); var rs = 1800; var vs = Math.sqrt(world.mu / rs); var station = P.createStation({ x: 0, y: -rs, vx: vs, radius: 12 }); return { ship: ship, station: station }; } } }; function Game(renderer, ui) { this.renderer = renderer; this.ui = ui; this.world = P.createWorld({}); this.ship = null; this.station = null; this.scenarioId = null; this.status = 'idle'; // idle | ready | flying | landed | crashed | docked this.paused = false; this.userTimeScale = 1; this.timeScale = 1; this.accumulator = 0; this.simTime = 0; this.prediction = null; this.showPrediction = true; this.predictTimer = 0; this.goalReached = false; this.crashInfo = null; this.exhaust = []; this.camera = { x: 0, y: 0, zoom: 0.4, targetZoom: 0.4 }; this.cameraFollowPlanet = false; this.lastNow = null; this.frameDt = 0; var self = this; this.frame = function (now) { self.frameImpl(now); }; } Game.prototype.defaultZoom = function () { var minDim = Math.min(this.renderer.w, this.renderer.h); return minDim / (this.world.planetRadius * 4.5); }; Game.prototype.toMenu = function () { this.status = 'idle'; this.ship = null; this.station = null; this.prediction = null; this.exhaust = []; if (this.ui) this.ui.hideHud(); }; Game.prototype.loadScenario = function (id) { var sc = SCENARIOS[id]; if (!sc) return; this.scenarioId = id; var built = sc.setup(this.world); this.ship = built.ship; this.station = built.station; // Surface Launch waits on the pad until the player first thrusts; the other // scenarios start flying immediately. var ready = sc.id === 'launch'; this.status = ready ? 'ready' : 'flying'; this.ship.state = ready ? 'ready' : 'flying'; this.paused = false; this.userTimeScale = 1; this.timeScale = 1; this.accumulator = 0; this.simTime = 0; this.goalReached = false; this.crashInfo = null; this.exhaust = []; this.camera.x = this.ship.pos.x; this.camera.y = this.ship.pos.y; this.camera.zoom = this.defaultZoom(); this.camera.targetZoom = this.camera.zoom; this.cameraFollowPlanet = false; this.updatePrediction(true); this.ui.showScenario(sc); }; // Begin the Surface Launch flight: called the first time the player thrusts // while in the 'ready' state. The clock and accumulator are reset so a long // wait on the pad cannot cause a physics jump when launch finally begins. Game.prototype.beginLaunch = function () { this.status = 'flying'; this.ship.state = 'flying'; this.accumulator = 0; this.simTime = 0; }; Game.prototype.reset = function () { if (this.scenarioId) this.loadScenario(this.scenarioId); }; Game.prototype.togglePause = function () { if (this.status !== 'idle') this.paused = !this.paused; }; Game.prototype.setUserTimeScale = function (s) { this.userTimeScale = s; }; Game.prototype.cycleTimeScale = function () { var i = TIME_SCALES.indexOf(this.userTimeScale); this.userTimeScale = TIME_SCALES[(i + 1) % TIME_SCALES.length]; }; Game.prototype.togglePrediction = function () { this.showPrediction = !this.showPrediction; if (!this.showPrediction) this.prediction = null; }; Game.prototype.zoomBy = function (f) { var minDim = Math.min(this.renderer.w, this.renderer.h); var minZ = minDim / (this.world.planetRadius * 14); var maxZ = 4; this.camera.targetZoom = Math.min(maxZ, Math.max(minZ, this.camera.targetZoom * f)); }; // Toggle the camera target between following the ship and staying centered // on the planet (press C). The planet is static, so "following" it simply // keeps the whole scene in view; the camera pans smoothly (see updateCamera). Game.prototype.centerOnPlanet = function () { this.cameraFollowPlanet = !this.cameraFollowPlanet; }; // Reduce time acceleration near the surface or while close to the station. Game.prototype.effectiveTimeScale = function () { var limit = 10; var info = P.orbitInfo(this.world, this.ship.pos, this.ship.vel); if (info.altitude < 600) limit = 1; var d = Math.sqrt( (this.ship.pos.x - this.station.pos.x) * (this.ship.pos.x - this.station.pos.x) + (this.ship.pos.y - this.station.pos.y) * (this.ship.pos.y - this.station.pos.y) ); if (d < 500) limit = Math.min(limit, 1); return Math.min(this.userTimeScale, limit); }; // One fixed physics tick. Game.prototype.step = function (dt) { var world = this.world; var ship = this.ship; var station = this.station; P.stepStation(world, station, dt); this.simTime += dt; if (ship.state === 'docked') { var dx0 = ship.pos.x - station.pos.x; var dy0 = ship.pos.y - station.pos.y; var d0 = Math.sqrt(dx0 * dx0 + dy0 * dy0) || 1; var off0 = station.radius + ship.radius + 3; ship.pos = { x: station.pos.x + (dx0 / d0) * off0, y: station.pos.y + (dy0 / d0) * off0 }; ship.vel = { x: station.vel.x, y: station.vel.y }; ship.time += dt; return; } if (ship.state !== 'flying') return; var input = this.controls ? this.controls.input : { thrust: 0, torque: 0 }; P.stepShip(world, ship, input, dt); var c = P.checkSurface(world, ship); if (c.type !== 'none') { if (c.type === 'land') { ship.state = 'landed'; var n = P.norm({ x: ship.pos.x - world.planet.x, y: ship.pos.y - world.planet.y }); var sr = world.planetRadius + ship.radius * 0.4; ship.pos = { x: world.planet.x + n.x * sr, y: world.planet.y + n.y * sr }; ship.vel = { x: 0, y: 0 }; ship.angVel = 0; ship.angle = Math.atan2(n.y, n.x) + Math.PI / 2; this.status = 'landed'; } else { ship.state = 'crashed'; this.status = 'crashed'; this.crashInfo = c; } return; } var dx = ship.pos.x - station.pos.x; var dy = ship.pos.y - station.pos.y; var d = Math.sqrt(dx * dx + dy * dy); var rel = Math.sqrt( (ship.vel.x - station.vel.x) * (ship.vel.x - station.vel.x) + (ship.vel.y - station.vel.y) * (ship.vel.y - station.vel.y) ); if (d < world.dockDistance && rel < world.dockSpeed) { ship.state = 'docked'; this.status = 'docked'; var off = station.radius + ship.radius + 3; ship.pos = { x: station.pos.x + (dx / (d || 1)) * off, y: station.pos.y + (dy / (d || 1)) * off }; ship.vel = { x: station.vel.x, y: station.vel.y }; return; } if (!this.goalReached && SCENARIOS[this.scenarioId].goal === 'orbit') { var info = P.orbitInfo(world, ship.pos, ship.vel); if (info.bound && info.periapsis > world.planetRadius + 150 && info.apoapsis < world.planetRadius * 5) { this.goalReached = true; this.ui._set('goal-text', 'ORBIT ACHIEVED — now dock with the station'); } } }; Game.prototype.updateExhaust = function (frameDt) { var ship = this.ship; if (ship && ship.state === 'flying' && this.controls && this.controls.input.thrust > 0 && ship.fuel > 0) { var count = Math.max(1, Math.round(120 * frameDt)); var dx = Math.cos(ship.angle); var dy = Math.sin(ship.angle); for (var i = 0; i < count; i++) { var spread = (Math.random() - 0.5) * 0.5; var ca = Math.cos(spread); var sa = Math.sin(spread); var bx = dx * ca - dy * sa; var by = dx * sa + dy * ca; var spd = 250 + Math.random() * 150; this.exhaust.push({ x: ship.pos.x - dx * 10, y: ship.pos.y - dy * 10, vx: ship.vel.x - bx * spd, vy: ship.vel.y - by * spd, life: 0.35 + Math.random() * 0.2, maxLife: 0.55, size: 1.5 + Math.random() * 2 }); } } for (var j = this.exhaust.length - 1; j >= 0; j--) { var p = this.exhaust[j]; p.life -= frameDt; if (p.life <= 0) { this.exhaust.splice(j, 1); continue; } p.x += p.vx * frameDt; p.y += p.vy * frameDt; } if (this.exhaust.length > 500) this.exhaust.splice(0, this.exhaust.length - 500); }; Game.prototype.updateCamera = function (frameDt) { if (!this.ship) return; var cam = this.camera; var k = 1 - Math.exp(-4 * frameDt); var tx = this.cameraFollowPlanet ? this.world.planet.x : this.ship.pos.x; var ty = this.cameraFollowPlanet ? this.world.planet.y : this.ship.pos.y; cam.x += (tx - cam.x) * k; cam.y += (ty - cam.y) * k; cam.zoom += (cam.targetZoom - cam.zoom) * (1 - Math.exp(-8 * frameDt)); }; Game.prototype.updatePrediction = function (frameDt, force) { if (!this.showPrediction) { this.prediction = null; return; } this.predictTimer -= frameDt; if (!force && this.predictTimer > 0) return; this.predictTimer = 0.25; if (this.ship && this.ship.state === 'flying') { this.prediction = P.predictTrajectory(this.world, this.ship, { dt: this.world.fixedDt * 2, maxSteps: 3000, sampleEvery: 3 }); } else { this.prediction = null; } }; // Main loop: fixed-timestep accumulator so physics is frame-rate independent. Game.prototype.frameImpl = function (now) { if (this.lastNow === null) this.lastNow = now; var frameDt = (now - this.lastNow) / 1000; this.lastNow = now; if (frameDt < 0) frameDt = 0; if (frameDt > 0.25) frameDt = 0.25; // clamp hitches (tab switch etc.) this.frameDt = frameDt; // Surface Launch: the clock is stopped on the pad until the player first // thrusts. Starting here (before the physics block) means the very first // thrust is applied this same frame. if (this.status === 'ready' && !this.paused && this.controls && this.controls.input.thrust > 0) { this.beginLaunch(); } if (!this.paused && this.status !== 'idle' && this.status !== 'ready') { this.timeScale = this.effectiveTimeScale(); this.accumulator += frameDt * this.timeScale; var dt = this.world.fixedDt; var n = 0; while (this.accumulator >= dt && n < 4000) { this.step(dt); this.accumulator -= dt; n++; } if (n >= 4000) this.accumulator = 0; // spiral-of-death guard } this.updateExhaust(frameDt); this.updateCamera(frameDt); this.updatePrediction(frameDt); this.renderer.render(this); this.ui.update(this); global.requestAnimationFrame(this.frame); }; global.Game = Game; global.SCENARIOS = SCENARIOS; })(typeof window !== 'undefined' ? window : globalThis);