import * as THREE from 'three'; import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js'; import { FXAAPass } from 'three/examples/jsm/postprocessing/FXAAPass.js'; import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js'; import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js'; import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js'; import { animateBody, buildAstronaut, HELMET, REST_PALMS, NOZZLES, poseArms, settleBody } from './astronaut'; import { Sound, type Effect, type Speaker } from './audio'; import { CinematicCamera } from './cinematic'; import { Input } from './input'; import { arrayMesh, HANDS_ON, Interaction, WING_MOUNT, type HandEvent, type Rail } from './interaction'; import { stampStencil, TargetMarker } from './marker'; import { drawVisor } from './visor'; import { POWER_UP_TIME, StationPower } from './power'; import { Strike, STRIKE_LEAD, UNFURL_TIME } from './strike'; import { Body, TUNING, type Command } from './physics'; import { analytics } from './analytics'; import { platform } from './platform'; import { ICONS, TouchControls, type ButtonId } from './touch'; import { POLISHED } from './look'; import { AIRLOCK, ALTITUDE, EARTH_RADIUS, EARTH_TIME, buildAirlockInterior, buildEarth, buildHatch, buildSky, buildStars, buildStation, buildSun, Puffs } from './world'; const $ = (id: string) => document.getElementById(id)!; // --- Scene ------------------------------------------------------------ const renderer = new THREE.WebGLRenderer({ antialias: true, stencil: true }); /** Screen pixels drawn per CSS pixel. The polished look starts lower and gives up more if frames run slow. */ let sharpness = Math.min(window.devicePixelRatio, POLISHED ? 1.5 : 2); renderer.setPixelRatio(sharpness); renderer.shadowMap.enabled = true; if (POLISHED) { renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.15; } $('app').appendChild(renderer.domElement); const scene = new THREE.Scene(); scene.background = new THREE.Color(0x000004); const CHASE_FOV = 70; const camera = new THREE.PerspectiveCamera(CHASE_FOV, 1, 0.1, 20000); /** Unit vector towards the sun, shared with the planet shaders and updated every frame. */ const sunDir = new THREE.Vector3(0, 1, 0); const STATION_CENTRE = new THREE.Vector3(0, 0, 2); const sun = new THREE.DirectionalLight(0xffffff, 3); sun.castShadow = true; sun.shadow.mapSize.set(4096, 4096); sun.shadow.camera.left = sun.shadow.camera.bottom = -68; sun.shadow.camera.right = sun.shadow.camera.top = 68; sun.shadow.camera.near = 150; sun.shadow.camera.far = 450; sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.04; if (POLISHED) sun.shadow.radius = 2.5; // softer shadow edges sun.target.position.copy(STATION_CENTRE); const earthshine = new THREE.HemisphereLight(0x0a0f1e, 0x4f7fc4, 0.7); // light bounced up from the planet scene.add(sun, sun.target, earthshine, new THREE.AmbientLight(0xffffff, 0.05)); const earth = buildEarth(sunDir, renderer); const station = buildStation(); const hatch = buildHatch(); const rig = buildAstronaut(); const astronaut = rig.group; stampStencil(astronaut); // the target marker is never drawn over the astronaut const marker = new TargetMarker(); const puffs = new Puffs(); const stars = buildStars(); const sunDisc = buildSun(); scene.add(stars, sunDisc, earth, station.mesh, station.glows, buildAirlockInterior(), hatch, astronaut, puffs.mesh); const sky = POLISHED ? buildSky(renderer) : null; if (sky) scene.add(sky); // Polished look: the picture is drawn off-screen first so that anything brighter than white (the sun, // glints off metal and glass) can spill a soft glow over its surroundings, as it would in a camera. const composer = POLISHED ? new EffectComposer(renderer, new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, stencilBuffer: true })) : null; if (composer) { composer.addPass(new RenderPass(scene, camera)); composer.addPass(new UnrealBloomPass(new THREE.Vector2(1, 1), 0.22, 0.55, 1.05)); composer.addPass(new OutputPass()); composer.addPass(new FXAAPass()); // smooths jagged edges, far cheaper here than the graphics card's own way sunDisc.material.color.setScalar(2.5); } // Polished look: shiny surfaces mirror their surroundings. A six-sided camera at the astronaut // photographs the scene a few times a second, and that picture is what the visor and panels reflect. const mirror = POLISHED ? new THREE.CubeCamera(0.5, 20000, new THREE.WebGLCubeRenderTarget(128, { type: THREE.HalfFloatType })) : null; let mirrorAge = Infinity; function updateMirror(dt: number): void { if (!mirror) return; mirrorAge += dt; if (mirrorAge < 0.5) return; mirrorAge = 0; mirror.position.copy(body.pos); const shown = [astronaut, marker.group, hands.group, puffs.mesh].map((o) => [o, o.visible] as const); for (const [o] of shown) o.visible = false; renderer.shadowMap.autoUpdate = false; // keep the shadows from the main picture mirror.update(renderer, scene); renderer.shadowMap.autoUpdate = true; for (const [o, was] of shown) o.visible = was; mirror.renderTarget.texture.needsPMREMUpdate = true; scene.environment = mirror.renderTarget.texture; } // The airlock is kept dim so the window is the brightest thing in it: a low work light over the // astronaut, and blue light off the planet spilling in round the hatch. for (const [x, color, power] of [[5.6, 0xdfe6f2, 0.75], [8.0, 0x8fbcff, 1.3]] as const) { const airlockLight = new THREE.PointLight(color, power, 7, 1.6); airlockLight.position.set(x, -3, 7); scene.add(airlockLight); } // Helmet lamp: rides on the astronaut and points where they face. const lamp = new THREE.SpotLight(0xf4f8ff, 0, 45, 0.55, 0.5, 1.6); lamp.position.copy(HELMET).add(new THREE.Vector3(0, 0.05, -0.3)); lamp.target.position.set(0, 0.3, -10); astronaut.add(lamp, lamp.target); const hands = new Interaction(station.colliders); // The channel the failed battery feeds: dark, with its solar wings folded, until the new unit is bolted in. const power = new StationPower(station.glows, station.colliders, hands.socket.pos, () => sound.play('clunk')); // The solar wing that the second mission's meteorite tears off, and the new one that replaces it. const healthyMount = arrayMesh(false); healthyMount.position.copy(WING_MOUNT); const strike = new Strike( station.colliders, healthyMount, () => (sound.play('impact'), sound.play('alarm')), () => body.pos.distanceTo(WING_MOUNT) < 9 && sound.play('zap'), () => sound.play('clunk'), ); scene.add(hands.group, marker.group, power.group, strike.group); // --- Orbit ------------------------------------------------------------ const TAU = Math.PI * 2; const ORBIT_PERIOD = 900; // seconds for one compressed lap of the planet: about nine minutes of day, six of night const ORBIT_RATE = TAU / ORBIT_PERIOD; const SUN_NOON = new THREE.Vector3(0.35, 1, 0).normalize(); // sun direction at local noon const ORBIT_AXIS = new THREE.Vector3(1, 0, 0); /** The sun is hidden by the planet once it drops this far below level (from radius and altitude). */ const ECLIPSE_Y = -Math.sqrt(1 - (EARTH_RADIUS / (EARTH_RADIUS + ALTITUDE)) ** 2); const ECLIPSE_ANGLE = Math.acos(ECLIPSE_Y / SUN_NOON.y); /** Every spacewalk starts in mid-morning light: an hour-angle of one radian before local noon. */ const START_ANGLE = TAU - 1.0; const orbit = { angle: START_ANGLE }; // angle 0 is local noon const SUN_WHITE = new THREE.Color(0xfff6e6); const SUN_LOW = new THREE.Color(0xff8a3c); let daylight = 1; let lampForced = false; function updateOrbit(dt: number): void { orbit.angle = (orbit.angle + dt * ORBIT_RATE) % TAU; // The ground and the sun turn together, so the day/night line stays fixed on the planet. sunDir.copy(SUN_NOON).applyAxisAngle(ORBIT_AXIS, orbit.angle); earth.rotation.x = orbit.angle; daylight = THREE.MathUtils.smoothstep(sunDir.y, ECLIPSE_Y - 0.04, ECLIPSE_Y + 0.05); sun.intensity = 3 * daylight; sun.color.lerpColors(SUN_LOW, SUN_WHITE, THREE.MathUtils.smoothstep(sunDir.y, ECLIPSE_Y, ECLIPSE_Y + 0.3)); sun.position.copy(STATION_CENTRE).addScaledVector(sunDir, 300); earthshine.intensity = (0.03 + 0.7 * THREE.MathUtils.smoothstep(sunDir.y, -0.15, 0.4)) * (POLISHED ? 0.35 : 1); EARTH_TIME.value += dt * 0.004; if (sky) (sky.position.copy(camera.position), ((sky.material as THREE.ShaderMaterial).uniforms.dim.value = 1 - 0.55 * daylight)); (stars.material as THREE.PointsMaterial).opacity = 1 - 0.5 * daylight; sunDisc.position.copy(camera.position).addScaledVector(sunDir, 8000); // On through the night and the low-sun minutes after dawn, when the shadowed side is still black. lamp.intensity = lampForced || ((daylight < 0.5 || sunDir.y < 0) && mode !== 'airlock') ? 130 : 0; } /** Seconds until the next sunset (in daylight) or sunrise (in shadow). */ function nextSunEvent(): { label: string; seconds: number } { const a = orbit.angle; if (a > ECLIPSE_ANGLE && a < TAU - ECLIPSE_ANGLE) return { label: 'SUNRISE IN', seconds: (TAU - ECLIPSE_ANGLE - a) / ORBIT_RATE }; return { label: 'SUNSET IN', seconds: ((ECLIPSE_ANGLE - a + TAU) % TAU) / ORBIT_RATE }; } // --- State ------------------------------------------------------------ const body = new Body(); const input = new Input(renderer.domElement); const sound = new Sound(); const cmd: Command = { move: new THREE.Vector3(), rot: new THREE.Vector3(), mouseX: 0, mouseY: 0, brake: false }; let started = false; /** Why the player is stuck with only a restart left, or '' while they are not. */ let lostWhy = ''; // Phones and tablets get on-screen controls, and instructions that show the buttons' pictures in // place of key names. It switches on for a touch-first device, or at the first touch on any other. const touch = new TouchControls(input, renderer.domElement); let touchMode = false; function enableTouch(): void { touchMode = true; analytics.touch(); document.body.classList.add('touch'); } if (window.matchMedia('(hover: none) and (pointer: coarse)').matches || location.search.includes('touch')) enableTouch(); window.addEventListener('pointerdown', (e) => e.pointerType === 'touch' && !touchMode && enableTouch(), true); const KEY_BUTTON: Record = { F: 'grab', W: 'thrust', X: 'stop', G: 'hook', R: 'restart' }; const ico = (id: ButtonId) => `${ICONS[id]}`; /** A control as the instructions name it: the key on a keyboard, the button's picture on a touch screen. */ const cap = (k: string) => (touchMode && KEY_BUTTON[k] ? ico(KEY_BUTTON[k]) : `${k}`); /** The keys an instruction can name. Its picture of a key bobs up and down until the player presses it. */ const KEY_CODES: Record = { F: ['KeyF'], X: ['KeyX'], G: ['KeyG'], W: ['KeyW'], A: ['KeyA'], S: ['KeyS'], D: ['KeyD'], Q: ['KeyQ'], E: ['KeyE'], V: ['KeyV'], B: ['KeyB'], R: ['KeyR'], Space: ['Space'], Shift: ['ShiftLeft', 'ShiftRight'], }; const press = (k: string, lower = false) => `${touchMode ? (lower ? 'tap' : 'Tap') : lower ? 'press' : 'Press'} ${cap(k)}`; const hold = (k: string) => `Hold ${cap(k)}`; /** 'airlock' is the scripted start inside the station; 'free' is normal flight; 'done' is after going back in. */ let mode: 'airlock' | 'free' | 'done' = 'airlock'; let view: 'chase' | 'helmet' = 'chase'; let cinematicOn = false; const cinematic = new CinematicCamera(); const camQuat = new THREE.Quaternion(); /** 0 puts the camera in the helmet, 1 behind the astronaut; it eases between them. */ let chaseBlend = 0; // Airlock sequence const FACING_OUT = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), -Math.PI / 2); const HATCH_SWING = 1.85; // radians const HATCH_TIME = 4.5; // seconds const EGRESS_SPEED = 0.5; // m/s, pulling along the walls /** `open` is how far the hatch has swung (0 to 1); it moves towards `want`. */ const air = { want: 0, open: 0, speed: 0, yaw: 0, pitch: 0 }; // The doorway's own collider: a slab filling the opening, parked far away whenever the hatch is not shut. const SEAL_MIN = new THREE.Vector3(7.6, -4.5, 6); const SEAL_MAX = new THREE.Vector3(8.6, -2, 8); const SEAL_AWAY = new THREE.Vector3(0, 1e5, 0); const hatchSeal = new THREE.Box3(SEAL_MIN.clone(), SEAL_MAX.clone()); station.colliders.push(hatchSeal); /** * Once the player pushes off, the way out plays by itself: a glide up to the hatch seen from the * helmet, then the film camera's own shots (the ones B gives) from outside. `stage` counts the cuts. */ const egress = { on: false, stage: 0 }; const egressSight = new THREE.Vector3(); function setEgress(on: boolean): void { egress.on = on; egress.stage = 0; } /** What the player has done since the current step began, for the tutorial's checks. */ const track = { time: 0, turned: 0, rolled: 0, reeled: 0, dirs: new Set(), held: 0, viewChanged: false, keys: new Set(), rollLeft: 0, rollRight: 0 }; let missionClock = 0; // --- Radio ------------------------------------------------------------ const radioQueue: [Speaker, string][] = []; let radioBusy = false; let radioQuiet = 0; function say(...lines: [Speaker, string][]): void { radioQueue.push(...lines); while (radioQueue.length > 4) radioQueue.shift(); // if the player races ahead, skip the stale chatter } function pumpRadio(dt: number): void { radioQuiet += dt; if (!radioBusy && radioQueue.length) { const [who, text] = radioQueue.shift()!; radioBusy = true; radioQuiet = 0; sound.radio(who, text, () => (radioBusy = false)); } } // --- Controls panel --------------------------------------------------- /** Every line the controls panel can show, in display order. They are revealed as the tutorial reaches them. */ const HELP: Record = { hatch: 'F open hatch', forward: 'W move forward', look: 'Mouse look around', move: 'W A S D forward / back / sideways', updown: 'Space / Shift up / down', roll: 'Q / E roll', brake: 'X hold to stop', grab: 'F grab or let go of a rail', tether: 'G tap to clip or unclip the tether', reel: 'G hold to reel in on the tether', carry: 'F also picks up items', tool: 'F hold at the worksite to run the power tool', camera: 'V helmet / outside view B film camera', misc: 'T attitude hold L lamp M mute R restart', }; /** A newer line that makes an earlier one redundant. */ const REPLACES: Record = { move: 'forward', grab: 'hatch' }; const revealed = new Set(); function reveal(ids: string[], highlight = true): void { for (const id of ids) { revealed.add(id); if (REPLACES[id]) revealed.delete(REPLACES[id]); } $('help').innerHTML = Object.keys(HELP) .filter((id) => revealed.has(id)) .map((id) => `
${HELP[id]}
`) .join(''); } // --- Script: intro, tutorial, training, mission ------------------------- interface Step { /** Starts a new chapter: shows a title card, and R restarts from here. */ chapter?: [title: string, subtitle: string]; say?: [Speaker, string][]; goal: () => string; reveal?: string[]; /** What a touch screen is shown at this step, where that differs. */ touchReveal?: string[]; /** Where the on-screen marker points. */ target?: () => THREE.Vector3 | null; /** A spot to fly to and stop at, within a metre and a half. */ waypoint?: THREE.Vector3; begin?: () => void; done: () => boolean; /** Different words for a touch screen, where there are buttons and a stick and no keys. */ touchSay?: [Speaker, string][]; /** Teaches a control the touch screen does not have, so it is left out there. */ keysOnly?: boolean; /** The step that finishes a repair. */ repair?: boolean; /** The last step of a mission: when it is done the spacewalk is over. */ final?: boolean; /** The tether stays where it is for this step: it can be neither unclipped nor moved. */ tied?: boolean; /** The step is skipped unless this holds when its turn comes. */ when?: () => boolean; } const railMiddle = (tag: string) => { const r = hands.rails.find((x: Rail) => x.tag === tag)!; return r.a.clone().addScaledVector(r.dir, r.len / 2); }; const airlockRail = railMiddle('airlock'); const worksiteRail = railMiddle('worksite'); const newBattery = hands.item('battery'); const oldBattery = hands.item('old-battery'); const tool = hands.item('tool'); const wingRail = railMiddle('wingsite'); const newArray = hands.item('array'); const oldArray = hands.item('old-array'); const hatchApproach = AIRLOCK.hatch.clone().add(new THREE.Vector3(1.6, 0, 0)); // Both drill markers sit on a handrail, so the arrow always points at a real place on the station. // Each is under nine metres from the airlock rail, well inside the tether's twelve. const WAYPOINT_1 = new THREE.Vector3(2.2, -3, 0); // starboard side of the lab const WAYPOINT_2 = new THREE.Vector3(10.5, 3.2, 0.25); // top of the truss, to starboard const stopped = () => body.vel.length() < 0.03; /** How many of the given thruster directions (axis and sign, like 'x-1') have been fired during this step. */ const fired = (...dirs: string[]) => dirs.filter((d) => track.dirs.has(d)).length; const looseBolts = () => hands.bolts.filter((b) => b <= 0).length; const tightBolts = () => hands.bolts.filter((b) => b >= 1).length; const STEPS: Step[] = [ // Airlock { say: [['HOUSTON', 'E V one, Houston. Airlock is at vacuum and you are go for egress. Open the hatch when you are ready.']], goal: () => `${press('F')} to open the hatch`, reveal: ['hatch'], done: () => air.open >= 1, }, { say: [['HOUSTON', 'Hatch is open. Beautiful day out there. Ease yourself out, nice and slow.']], goal: () => (egress.on ? '' : touchMode ? `Tap ${ico('thrust')} to move out of the airlock` : `Hold ${cap('W')} to move out of the airlock`), reveal: ['forward'], done: () => mode === 'free', }, // Tutorial { say: [ ['EV1', 'Houston, E V one is outside.'], ['HOUSTON', 'Copy, we see you. You are drifting. Hold X and the jetpack will null your rates.'], ], touchSay: [ ['EV1', 'Houston, E V one is outside.'], ['HOUSTON', 'Copy, we see you. You are drifting. Hold the stop button and the jetpack will null your rates.'], ], goal: () => `${hold('X')} to stop drifting`, reveal: ['brake'], done: stopped, }, { say: [['HOUSTON', 'Good. Now get your bearings. Move the mouse to look around. The station is behind you.']], touchSay: [['HOUSTON', 'Good. Now get your bearings. Use the stick to look around. The station is behind you.']], goal: () => (touchMode ? 'Drag the stick to look around' : 'Move the mouse to look around'), reveal: ['look'], done: () => track.turned > 2.5, }, { // Keyboard only: a touch screen meets its one thrust button later, on the flight back to the handrail. say: [['HOUSTON', 'Thruster check. Short taps only. W, A, S and D to translate.']], goal: () => `Tap ${cap('W')} ${cap('A')} ${cap('S')} ${cap('D')} to try each thruster (${fired('x1', 'x-1', 'z1', 'z-1')}/4)`, reveal: ['move'], keysOnly: true, done: () => fired('x1', 'x-1', 'z1', 'z-1') === 4, }, { say: [['HOUSTON', 'Good. Now up and down. Space for up, shift for down.']], goal: () => `Tap ${cap('Space')}, then ${cap('Shift')}, to go up and down (${fired('y1', 'y-1')}/2)`, reveal: ['updown'], keysOnly: true, done: () => fired('y1', 'y-1') === 2, }, { say: [['HOUSTON', 'And roll, with Q and E.']], touchSay: [['HOUSTON', 'Now roll. Put a finger on the astronaut and drag it left, then right.']], goal: () => (touchMode ? 'Hold the astronaut and drag it left and right to roll' : `Roll with ${cap('Q')} and ${cap('E')}`), reveal: ['roll'], // On a touch screen the roll has to be tried both ways, as the moving finger on screen shows. done: () => (touchMode ? track.rollLeft > 0.5 && track.rollRight > 0.5 : track.rolled > 1), }, { // Only for someone who is still drifting after the thruster checks. when: () => body.vel.length() > 0.1, say: [['HOUSTON', 'Good check. Null your rates again.']], goal: () => `${hold('X')} to stop`, done: stopped, }, { say: [['HOUSTON', 'Now translate back to the handrail on top of the airlock, and grab it.']], touchSay: [['HOUSTON', 'Good. The thrust button pushes you the way you are facing. Hold it to fly back to the handrail on top of the airlock, and grab it.']], goal: () => (touchMode ? `Hold ${ico('thrust')} to fly to the marked handrail, then tap ${ico('grab')} to grab it` : `Fly to the marked handrail and ${press('F', true)} to grab it`), reveal: ['grab'], touchReveal: ['move', 'grab'], target: () => airlockRail, done: () => !!hands.grab, }, { say: [['HOUSTON', 'Good grip. Before anything else, clip your safety tether to that rail.']], goal: () => `${press('G')} to clip your tether`, reveal: ['tether'], done: () => !!hands.tether, }, { say: [ ['EV1', 'Tether is locked.'], ['HOUSTON', 'Copy tether. Let go when ready. You will push gently away from the rail.'], ], goal: () => `${press('F')} to let go and push off the rail`, done: () => !hands.grab, }, { say: [['HOUSTON', 'Two more things. V switches between your helmet and the outside view. B puts a camera out in space to watch you work.']], touchSay: [['HOUSTON', 'One more thing. The camera button steps through your helmet, the outside view, and cameras out in space.']], goal: () => (touchMode ? `Try ${ico('camera')}, or carry on` : `Try ${cap('V')} and ${cap('B')}, or carry on`), reveal: ['camera', 'misc'], done: () => track.time > 10 || track.viewChanged, }, // Training { chapter: ['TRAINING', 'Translation drill'], say: [['HOUSTON', 'Training run. The first marker is the handrail on the side of the lab, forward of the airlock. Translate to it and hold position there.']], goal: () => 'Fly to the marked handrail on the side of the lab and stop beside it', waypoint: WAYPOINT_1, done: () => track.held > 1, }, { say: [['HOUSTON', 'Good. Second marker is the handrail on top of the truss. Mind the radiators.']], goal: () => 'Fly up to the marked handrail on top of the truss and stop beside it', waypoint: WAYPOINT_2, done: () => track.held > 1, }, { // The last drill is flown on the airlock tether; anyone clipped elsewhere, or not at all, is sent back first. when: () => hands.tether?.rail.tag !== 'airlock', say: [['HOUSTON', 'Before the last drill, go back to the airlock handrail and clip your tether to it.']], goal: () => `Clip your tether (${cap('G')}) to the airlock handrail`, target: () => airlockRail, done: () => hands.tether?.rail.tag === 'airlock', }, { say: [['HOUSTON', 'One last drill, and it will save you propellant. Your power tool is stowed on the top handrail of the module aft of the airlock, nearly ten metres out. Fly out and collect it. Stay on your tether.']], goal: () => `Fly out to the power tool and pick it up with ${cap('F')}. Stay on your tether`, reveal: ['carry'], target: () => tool.pos, tied: true, done: () => hands.hasTool, }, { say: [ ['EV1', 'Tool is on my wrist.'], ['HOUSTON', 'Good. Now do not fly back. Hold G, and the reel will wind you home along your tether. It costs you no propellant at all.'], ], touchSay: [ ['EV1', 'Tool is on my wrist.'], ['HOUSTON', 'Good. Now do not fly back. Hold the tether button, and the reel will wind you home along your tether. It costs you no propellant at all.'], ], goal: () => `${hold('G')} to reel yourself back to the airlock handrail. It uses no propellant`, reveal: ['reel'], target: () => hands.tether?.point ?? airlockRail, tied: true, done: () => !!hands.tether && track.reeled > 0.5 && hands.tetherOut < 4, }, // Mission { chapter: ['MISSION 1', 'Battery swap on the truss'], say: [ ['HOUSTON', 'E V one, Houston. Training is complete. Now the real work. A battery unit on the truss has failed. The station is running dark, and one pair of solar wings has folded itself away. We need that unit swapped.'], ['HOUSTON', 'The worksite is on top of the truss. Unclip here, and move your tether to the handrail beside it.'], ], goal: () => `Clip your tether (${cap('G')}) to the handrail by the worksite`, target: () => worksiteRail, begin: () => (missionClock = 0), done: () => hands.tether?.rail.tag === 'worksite', }, { say: [['HOUSTON', 'You should see the failed unit, under the flashing red beacon. Release the four hold-down bolts.']], goal: () => `${hold('F')} near the worksite to release the bolts (${looseBolts()}/4)`, reveal: ['tool'], target: () => hands.socket.pos, done: () => looseBolts() === 4, }, { say: [['HOUSTON', 'Bolts are free. Lift the old unit out. It is a hundred and sixty kilos, so expect sluggish thrusters.']], goal: () => `Pick up the old battery with ${cap('F')}`, target: () => oldBattery.pos, done: () => hands.held === oldBattery, }, { say: [['HOUSTON', 'Park it on the handrail next to you for now.']], goal: () => `Stow the old battery: ${press('F', true)} close to a handrail`, target: () => worksiteRail, done: () => oldBattery.state === 'stowed', }, { say: [['HOUSTON', 'The spare is stowed on the forward face of the truss, to starboard.']], goal: () => `Fetch the new battery with ${cap('F')}`, target: () => newBattery.pos, done: () => hands.held === newBattery, }, { say: [['HOUSTON', 'Bring it back and seat it in the tray.']], goal: () => `Carry it to the worksite and ${press('F', true)} inside the frame`, target: () => hands.socket.pos, done: () => newBattery.state === 'installed', }, { say: [['EV1', 'New unit is seated.'], ['HOUSTON', 'Good seat. Torque the four bolts.']], repair: true, goal: () => `${hold('F')} to tighten the bolts (${tightBolts()}/4)`, target: () => hands.socket.pos, done: () => tightBolts() === 4, }, { say: [['HOUSTON', 'Good power on that unit. Lights are coming back all along the station, and the solar wings are opening out. Outstanding work. Collect the old battery, then move your tether back to the airlock.']], goal: () => (hands.held === oldBattery ? `Clip your tether (${cap('G')}) back on the airlock handrail` : `Pick up the old battery with ${cap('F')}`), target: () => (hands.held === oldBattery ? airlockRail : oldBattery.pos), done: () => hands.held === oldBattery && hands.tether?.rail.tag === 'airlock', }, { say: [['HOUSTON', 'Stow the old unit on the airlock rail. The next crew will bring it inside.']], goal: () => `Stow the old battery at the airlock: ${press('F', true)} close to the rail`, target: () => airlockRail, done: () => oldBattery.state === 'stowed' && oldBattery.pos.distanceTo(airlockRail) < 3.5, }, { say: [['HOUSTON', 'That is everything. Come on home, E V one.']], goal: () => `Fly to the hatch and ${press('F', true)} to go back inside`, target: () => hatchApproach, final: true, done: () => mode === 'done', }, // Second mission { chapter: ['MISSION 2', 'Meteorite strike'], say: [ ['HOUSTON', 'E V one, Houston. Meteoroid inbound, starboard side. Brace.'], ['EV1', 'Houston, we have been hit! The starboard solar wing is gone. It is torn clean off.'], ], goal: () => '', begin: () => { missionClock = 0; startShow('strike'); }, done: () => !show && strike.state === 'struck', }, { say: [['HOUSTON', 'We saw it, E V one. The inner starboard wing is gone and its mount is arcing. We need a new array on that mount. First, collect the spare. It is stowed on top of the truss, just above you.']], goal: () => `Pick up the new solar array with ${cap('F')}`, target: () => newArray.pos, done: () => hands.held === newArray, }, { say: [['HOUSTON', 'Good. Now take it out along the truss to starboard. Your tether will not reach, so move it from handrail to handrail as you go. Clip on at the rail beside the damaged mount.']], goal: () => hands.held === newArray || newArray.pos.distanceTo(wingRail) < 4 ? `Carry the array out to the damaged mount. Move your tether (${cap('G')}) from handrail to handrail along the truss, and clip it to the rail by the mount` : `Pick up the new solar array with ${cap('F')}`, target: () => (hands.held === newArray || newArray.pos.distanceTo(wingRail) < 4 ? wingRail : newArray.pos), done: () => hands.tether?.rail.tag === 'wingsite' && (hands.held === newArray || newArray.pos.distanceTo(wingRail) < 4), }, { when: () => hands.held === newArray, say: [['HOUSTON', 'We have cut the power to that mount, so it is safe to touch. Park the spare on the handrail.']], goal: () => `Stow the new array: ${press('F', true)} close to the handrail`, target: () => wingRail, done: () => newArray.state === 'stowed', }, { say: [['HOUSTON', 'Now release the four bolts on the damaged unit.']], goal: () => `${hold('F')} near the damaged mount to release the bolts (${looseBolts()}/4)`, target: () => hands.socket.pos, done: () => looseBolts() === 4, }, { say: [['HOUSTON', 'Bolts are free. Lift it out.']], goal: () => `Pick up the damaged array with ${cap('F')}`, target: () => oldArray.pos, done: () => hands.held === oldArray, }, { say: [['HOUSTON', 'Park it on the handrail. We will bring it inside on a later walk.']], goal: () => `Stow the damaged array: ${press('F', true)} close to the handrail`, target: () => wingRail, done: () => oldArray.state === 'stowed', }, { say: [['HOUSTON', 'Now the spare.']], goal: () => `Pick up the new solar array with ${cap('F')}`, target: () => newArray.pos, done: () => hands.held === newArray, }, { say: [['HOUSTON', 'Seat it on the mount.']], goal: () => `Carry it to the mount and ${press('F', true)} inside the frame`, target: () => hands.socket.pos, done: () => newArray.state === 'installed', }, { say: [['EV1', 'New array is seated.'], ['HOUSTON', 'Copy. Torque the four bolts.']], repair: true, goal: () => `${hold('F')} to tighten the bolts (${tightBolts()}/4)`, target: () => hands.socket.pos, done: () => tightBolts() === 4, }, { say: [['HOUSTON', 'We have good current from the new wing. Look at that, it is opening out beautifully. Outstanding work, E V one. Bring your tether back along the truss and come on home.']], goal: () => `Work your tether back along the truss, then fly to the hatch and ${press('F', true)} to go back inside`, target: () => hatchApproach, final: true, done: () => mode === 'done', }, ]; let stepIndex = -1; /** The step that ends with the new battery bolted down. */ const REPAIRED = STEPS.findIndex((s) => s.repair); /** From this step on the power tool is already on the wrist. */ const TOOLED = STEPS.findIndex((s) => s.reveal?.includes('reel')); /** Where the second mission starts, and its step that ends with the new solar array bolted down. */ const MISSION_2 = STEPS.findIndex((s) => s.chapter?.[0] === 'MISSION 2'); const REPAIRED_2 = STEPS.map((s) => !!s.repair).lastIndexOf(true); /** Once a mission is over, the step it ended on; null while one is being flown. */ let ended: number | null = null; /** The first mission has been finished on this device at some time, so the second can be started directly. */ const DONE_KEY = 'spacewalk-mission-1'; function beginStep(i: number): void { while (STEPS[i] && ((touchMode && STEPS[i].keysOnly) || STEPS[i].when?.() === false)) i++; stepIndex = i; track.time = track.turned = track.rolled = track.reeled = track.held = track.rollLeft = track.rollRight = 0; track.dirs.clear(); track.keys.clear(); track.viewChanged = false; // The step just finished, so whatever mission control was saying about it is cut short, and // anything still waiting to be said about it is dropped: the radio goes straight to what is next. radioQueue.length = 0; sound.hush(); radioBusy = false; const step = STEPS[i]; // Every finished task is reported to the portal, as progress through the game. if (started) platform.task(i, STEPS.length, step ? step.goal().replace(/<[^>]*>/g, '').trim() : 'Mission complete'); if (!step) return finish(); if (step.chapter) showTitle(...step.chapter); if (step.say) say(...((touchMode && step.touchSay) || step.say)); const shown = (touchMode && step.touchReveal) || step.reveal; if (shown) reveal(shown); step.begin?.(); } function finish(): void { ended = Math.min(stepIndex, STEPS.length - 1); stepIndex = -1; const more = ended < MISSION_2; if (more) { try { localStorage.setItem(DONE_KEY, '1'); } catch { /* private window: the second mission is still offered on the end card */ } } $('next-btn').classList.toggle('hidden', !more); $('again-btn').classList.toggle('second', more); platform.stop(); say(['HOUSTON', 'Hatch closed and locked. Welcome home, E V one. Great work today.']); const mins = Math.floor(missionClock / 60), secs = Math.floor(missionClock % 60); $('end-stats').innerHTML = `Mission time ${mins}:${String(secs).padStart(2, '0')}
Propellant left ${Math.round(body.fuel)}%
Suit integrity ${Math.round(body.suit)}%`; $('end').classList.remove('hidden'); sound.play('chime'); } let titleTimer = 0; function showTitle(title: string, subtitle: string): void { $('title').innerHTML = `${title}${subtitle}`; $('title').classList.add('show'); titleTimer = 4.5; sound.play('chime'); } /** Step that starts the chapter containing step `i`. */ function chapterStart(i: number): number { let s = Math.min(Math.max(i, 0), STEPS.length - 1); while (s > 0 && !STEPS[s].chapter) s--; return s; } /** The chapter step `i` belongs to, as the player numbers know it; the steps before the first title card are the tutorial. */ const chapterName = (i: number) => STEPS[chapterStart(i)].chapter?.[0] ?? 'tutorial'; /** Start (or restart) from the given step. Step 0 is inside the airlock; anything later starts just outside it. */ function startFrom(i: number): void { ended = null; platform.start(); body.vel.set(0, 0, 0); body.angVel.set(0, 0, 0); body.fuel = 100; body.suit = 100; body.hold = true; radioQueue.length = 0; sound.hush(); radioBusy = false; $('end').classList.add('hidden'); air.speed = air.yaw = air.pitch = 0; body.quat.copy(FACING_OUT); camQuat.copy(FACING_OUT); setCinematic(false); setEgress(false); air.open = air.want = 0; // later chapters start outside, with the hatch already shut behind lastSpin.set(0, 0, 0); if (i === 0) { mode = 'airlock'; body.pos.copy(AIRLOCK.start); orbit.angle = START_ANGLE; chaseBlend = 0; revealed.clear(); reveal([]); hands.reset(body, false); } else { mode = 'free'; body.pos.set(AIRLOCK.exitX, AIRLOCK.start.y, AIRLOCK.start.z); orbit.angle = START_ANGLE; chaseBlend = view === 'chase' ? 1 : 0; // Everything taught before this chapter is already on the panel. reveal(STEPS.slice(0, i).flatMap((s) => s.reveal ?? []), false); hands.reset(body, true, i >= MISSION_2 ? 1 : 0, i >= TOOLED); } settleBody(rig, body.vel, body.angVel); hatch.rotation.z = 0; show = null; document.body.classList.remove('film'); // Starting after the repair (development only) finds the station already lit. power.set(i > REPAIRED, true); // The second mission opens with the wing still whole; starting further into it (development only) finds it gone or replaced. strike.set(i <= MISSION_2 ? 'intact' : i <= REPAIRED_2 ? 'struck' : 'repaired'); if (i > REPAIRED_2) { newArray.state = 'installed'; newArray.pos.copy(hands.socket.pos); oldArray.state = 'stowed'; oldArray.pos.copy(wingRail).add(v1.set(0, 0, 0.5)); } if (started) analytics.start(chapterName(i)); beginStep(i); } /** A finished step is counted, and so is the chapter when it was the last of one. */ function advance(): void { const i = stepIndex; if (!STEPS[i]?.done()) return; analytics.step(i - chapterStart(i) + 1, track.time); if (STEPS[i].final) return analytics.complete(), finish(); beginStep(i + 1); if (stepIndex >= 0 && chapterStart(stepIndex) !== chapterStart(i)) (analytics.complete(), analytics.start(chapterName(stepIndex))); } // --- Per-frame pieces ------------------------------------------------- const v1 = new THREE.Vector3(); const v2 = new THREE.Vector3(); const q1 = new THREE.Quaternion(); const AXES = ['x', 'y', 'z'] as const; const SIDES = [-1, 1]; /** * The scripted films, seen from outside while the player's controls are frozen. `t` is seconds * since the film began. * * 'power' is the pay-off for the battery swap: first the worksite as its beacon goes green and the * lights start along the truss, then the whole port side as the station lights up and the solar * wings open out. * * 'strike' opens the second mission: the starboard wings seen from aft as the meteorite comes in * and hits, then close on the wrecked mount spitting sparks, then the whole starboard side from far * off as the torn wing tumbles away. * * 'unfurl' is the pay-off for that repair: the new unit close up, then the fresh wing running out. */ type Film = 'power' | 'strike' | 'unfurl'; let show: { t: number; kind: Film } | null = null; const SHOW_CLOSE = 2.6; // seconds on the first shot const SHOW_END = POWER_UP_TIME + 2.2; const STRIKE_AT = 2.4; // seconds into its film when the meteorite hits const STRIKE_SHOTS = [3.7, 7.4, 11.6]; // when each of that film's three shots ends const UNFURL_END = UNFURL_TIME + 2; const showFrom = new THREE.Vector3(); const showAt = new THREE.Vector3(); function startShow(kind: Film): void { setCinematic(true); show = { t: 0, kind }; document.body.classList.add('film'); } function updateShow(dt: number): void { const s = show!; s.t += dt; let end = SHOW_END; let shake = 0; if (s.kind === 'power') { if (s.t < SHOW_CLOSE) { // Close on the worksite, from the forward side and a little above, creeping in. showAt.copy(hands.socket.pos); showFrom.set(2.6, 2.3, -4.6).multiplyScalar((1 - 0.05 * s.t) * cinematic.spread).add(showAt); camera.fov = 40; } else { // Wide, from high off the bow looking to port: the truss runs away across the frame and the wings open either side of it. const k = (s.t - SHOW_CLOSE) / (SHOW_END - SHOW_CLOSE); showAt.set(-24, 0, 3); showFrom.set(2 + 6 * k, 33 - 3 * k, -50).sub(showAt).multiplyScalar(cinematic.spread).add(showAt); camera.fov = 50; } } else if (s.kind === 'strike') { end = STRIKE_SHOTS[2]; if (s.t >= STRIKE_AT - STRIKE_LEAD) strike.hit(); const since = s.t - STRIKE_AT; if (since > 0) shake = Math.exp(-since * 2.2); if (s.t < STRIKE_SHOTS[0]) { // From aft and above, looking forward along the wing: the stone comes in over the station towards the camera. showAt.set(32, 3.6, 11); showFrom.set(42 - 0.5 * s.t, 8.5, 31).sub(showAt).multiplyScalar(cinematic.spread).add(showAt); camera.fov = 52; } else if (s.t < STRIKE_SHOTS[1]) { // Close on what is left of the mount, from outboard and aft, drifting sideways: the station is behind it. const k = s.t - STRIKE_SHOTS[0]; showAt.copy(WING_MOUNT).add(v1.set(0, -0.1, 1.2)); showFrom.set(4.4 - 0.3 * k, 2.1, 3.2).multiplyScalar(cinematic.spread).add(showAt); camera.fov = 40; } else { // Far off the starboard bow: the gap where the wing was, and its pieces going away below. const k = s.t - STRIKE_SHOTS[1]; showAt.set(27, -3 - 0.5 * k, 12); showFrom.set(64 + 1.2 * k, 26, -30).sub(showAt).multiplyScalar(cinematic.spread).add(showAt); camera.fov = 44; } } else { end = UNFURL_END; if (s.t < SHOW_CLOSE) { // Close on the new unit as its light goes green, from outboard and above. showAt.copy(WING_MOUNT); showFrom.set(3.2, 2.4, -2.2).multiplyScalar((1 - 0.05 * s.t) * cinematic.spread).add(showAt); camera.fov = 40; } else { // From high off the stern: the wing runs out towards the camera, with the station beyond it. const k = (s.t - SHOW_CLOSE) / (UNFURL_END - SHOW_CLOSE); showAt.set(31, 0, 14); showFrom.set(52 - 5 * k, 20 + 3 * k, 50).sub(showAt).multiplyScalar(cinematic.spread).add(showAt); camera.fov = 48; } } camera.position.copy(showFrom); camera.up.set(0, 1, 0); camera.lookAt(showAt); // The hit jolts the picture. if (shake > 0.01) camera.rotateX((Math.random() - 0.5) * 0.05 * shake), camera.rotateY((Math.random() - 0.5) * 0.05 * shake); camera.updateProjectionMatrix(); if (s.t >= end) { show = null; document.body.classList.remove('film'); setCinematic(false); camQuat.copy(body.quat); } } /** The moment the new battery is bolted down: the channel comes up, and the camera cuts outside to watch. */ function updatePower(dt: number): void { if (!power.on && mode === 'free' && newBattery.state === 'installed' && tightBolts() === 4) { power.set(true); sound.play('chime'); startShow('power'); } power.update(dt, clock); // The failed unit blinks red, the spare waits on amber, and the unit carrying load shows green. const blink = clock % 1.1 < 0.22 ? 2.2 : 0.25; hands.setStrip(oldBattery, blink, blink * 0.1, blink * 0.06); if (power.on) hands.setStrip(newBattery, 0.25, 1.7, 0.6); else hands.setStrip(newBattery, 1.5, 0.75, 0.1); // The solar wing: the same again, with the new array unit. if (strike.state === 'struck' && hands.job === 1 && mode === 'free' && newArray.state === 'installed' && tightBolts() === 4) { strike.repair(); sound.play('chime'); startShow('unfurl'); } // Mission control cuts the power to the wrecked mount once the tether is on the rail beside it. if (hands.tether?.rail.tag === 'wingsite') strike.live = false; strike.update(dt); // Until the hit, the wrecked unit is not there to see: the healthy mount stands in its place. if (strike.state === 'intact') hands.hidden.add(oldArray); else hands.hidden.delete(oldArray); hands.setStrip(oldArray, strike.live ? blink : 0.12, strike.live ? blink * 0.1 : 0.02, strike.live ? blink * 0.06 : 0.02); if (strike.state === 'repaired') hands.setStrip(newArray, 0.25, 1.7, 0.6); else hands.setStrip(newArray, 1.5, 0.75, 0.1); } function setCinematic(on: boolean): void { cinematicOn = on; document.body.classList.toggle('cinematic', on); if (on) cinematic.cut(body.pos, station.colliders); else { camera.fov = CHASE_FOV; camera.updateProjectionMatrix(); } } /** The camera button's round: helmet, outside view, then each of the film camera's shots. */ const SHOTS = ['helmet', 'chase', 'close', 'orbit', 'wide'] as const; let shot = 1; function cycleCamera(): void { if (!cinematicOn) shot = view === 'helmet' ? 0 : 1; shot = (shot + 1) % SHOTS.length; const next = SHOTS[shot]; if (next === 'helmet' || next === 'chase') { if (cinematicOn) setCinematic(false); view = next; } else { if (!cinematicOn) setCinematic(true); cinematic.cut(body.pos, station.colliders, next); } } const STICK_RATE = 1.3; // rad/s of turn with the stick pushed right over function readInput(dt: number): void { /** A control works only once the tutorial has introduced it. */ const taught = (id: string) => revealed.has(id); for (const k in KEY_CODES) if (KEY_CODES[k].some((c) => input.down(c))) track.keys.add(k); if (input.wasPressed('KeyT') && taught('misc')) body.hold = !body.hold; if (input.wasPressed('KeyL') && taught('misc')) lampForced = !lampForced; if (input.wasPressed('KeyM')) sound.toggleMute(); if (input.wasPressed('KeyR')) startFrom(chapterStart(ended ?? stepIndex)); if (mode !== 'airlock' && taught('camera') && !show) { // V flips between the outside view and the helmet; B steps through film-camera shots. if (input.wasPressed('KeyV')) { if (cinematicOn) setCinematic(false); else view = view === 'chase' ? 'helmet' : 'chase'; track.viewChanged = true; } if (input.wasPressed('KeyB')) { setCinematic(true); track.viewChanged = true; } if (input.wasPressed('TouchCamera')) { cycleCamera(); track.viewChanged = true; } } const down = input.down('ShiftLeft') || input.down('ShiftRight'); cmd.move.set(input.axis('KeyA', 'KeyD'), (input.down('Space') ? 1 : 0) - (down ? 1 : 0), input.axis('KeyW', 'KeyS')); // Dragging the astronaut to the right rolls clockwise, as E does. cmd.rot.set(input.axis('ArrowDown', 'ArrowUp'), input.axis('ArrowRight', 'ArrowLeft'), THREE.MathUtils.clamp(input.axis('KeyE', 'KeyQ') - touch.roll * 0.5, -1, 1)); const mouse = input.consumeMouse(); cmd.mouseX = mouse.x; cmd.mouseY = mouse.y; cmd.brake = input.down('KeyX'); // The stick asks for a turn rate, where the mouse gives a nudge: the further it is pushed, the // faster the turn, and letting go stops it. Small pushes are softened for fine aiming. const sx = touch.stick.x * Math.abs(touch.stick.x), sy = touch.stick.y * Math.abs(touch.stick.y); if (sx || sy) { if (mode === 'airlock') { cmd.mouseX += sx * 500 * dt; cmd.mouseY += sy * 500 * dt; } else { const perPixel = body.hold || hands.grab ? TUNING.mouseHold : TUNING.mouseFree; const ease = Math.min(1, 10 * dt); cmd.mouseX += ((body.angVel.y + sx * STICK_RATE) / perPixel) * ease; cmd.mouseY += ((body.angVel.x + sy * STICK_RATE) / perPixel) * ease; } } // Nothing the player presses during the power-up film moves the astronaut. if (show) { cmd.move.set(0, 0, 0); cmd.rot.set(0, 0, 0); cmd.mouseX = cmd.mouseY = 0; cmd.brake = false; } // Outside, every control is dead until mission control has introduced it: first only X works, // then the mouse, then the thrusters, then roll. A player still holding W from the airlock // doesn't sail away, and nobody gets lost before they have been shown how to stop. if (mode === 'free') { if (!taught('brake')) cmd.brake = false; if (!taught('look')) { cmd.mouseX = cmd.mouseY = 0; cmd.rot.x = cmd.rot.y = 0; } if (!taught('move')) cmd.move.set(0, 0, 0); if (!taught('updown')) cmd.move.y = 0; if (!taught('roll')) cmd.rot.z = 0; } } /** The scripted start: open the hatch, then pull yourself out along the airlock with W. */ function updateAirlock(dt: number): void { body.vel.set(0, 0, 0); body.thrust.set(0, 0, 0); if ((input.wasPressed('KeyF') || input.wasPressed('TouchHand')) && air.want === 0 && air.open === 0) { air.want = 1; sound.play('latch'); say(['EV1', 'Copy, Houston. Opening the hatch.']); } if (air.open >= 1 || egress.on) { // One push on W is enough: from then on the astronaut glides out and the film cameras take over. if ((cmd.move.z < 0 || input.wasPressed('KeyW')) && !egress.on) setEgress(true); const want = egress.on ? EGRESS_SPEED : 0; air.speed += THREE.MathUtils.clamp(want - air.speed, -0.6 * dt, 0.6 * dt); body.pos.x += air.speed * dt; } if (egress.on) { // The cameras frame a point just outside the hatch until the astronaut has come through it. egressSight.set(Math.max(body.pos.x, AIRLOCK.hatch.x + 0.9), body.pos.y, body.pos.z); const stage = body.pos.x < 8.2 ? 0 : body.pos.x < 10.5 ? 1 : 2; if (stage > egress.stage) { egress.stage = stage; cinematicOn = true; document.body.classList.add('cinematic'); cinematic.cut(body.pos, station.colliders, stage === 1 ? 'close' : 'orbit', egressSight); } if (body.pos.x > 11.7) air.want = 0; // clear of the door's swing: it closes behind } // The player can turn the head a little on top of the idle glances; it faces ahead for the way out. const freedom = egress.on ? 0 : 1; air.yaw = THREE.MathUtils.clamp(air.yaw - cmd.mouseX * 0.002 * freedom, -0.7, 0.7) * (freedom ? 1 : Math.exp(-3 * dt)); air.pitch = THREE.MathUtils.clamp(air.pitch - cmd.mouseY * 0.002 * freedom, -0.45, 0.45) * (freedom ? 1 : Math.exp(-3 * dt)); body.quat.copy(FACING_OUT); // only the head turns: see headLook if (body.pos.x >= AIRLOCK.exitX) { mode = 'free'; body.quat.copy(FACING_OUT); body.vel.set(air.speed, 0, 0); body.angVel.set(0, 0, 0); // The airlock's own keys are finished with; the panel starts again from the first flying control. revealed.delete('hatch'); revealed.delete('forward'); // Cut straight back to the player's own view. setEgress(false); setCinematic(false); air.want = 0; camQuat.copy(body.quat); chaseBlend = view === 'chase' ? 1 : 0; } } /** Swing the hatch towards open or shut. */ function updateHatch(dt: number): void { // A shut hatch is solid; while it is open or swinging the doorway is clear. if (air.open === 0) hatchSeal.set(SEAL_MIN, SEAL_MAX); else hatchSeal.min.copy(hatchSeal.max.copy(SEAL_AWAY)); if (air.open === air.want) return; const step = dt / HATCH_TIME; air.open = air.want > air.open ? Math.min(1, air.open + step) : Math.max(0, air.open - step); hatch.rotation.z = THREE.MathUtils.smootherstep(air.open, 0, 1) * HATCH_SWING; if (air.open === air.want) sound.play('clunk'); } const nearHatch = () => STEPS[stepIndex]?.target?.() === hatchApproach && body.pos.distanceTo(hatchApproach) < 2.2; /** * What the hand key (F, or the hand button on a touch screen) would do right now: run the power * tool while held ('work'), pick up, put down or fit an item ('carry'), take or let go of a rail or * work the hatch ('grab'), or nothing because nothing is in reach. */ function handDoes(skipWork = false): 'work' | 'carry' | 'grab' | null { if (!skipWork && revealed.has('tool') && hands.canWork(body)) return 'work'; if (revealed.has('carry')) { if (hands.held && !hands.grab) return 'carry'; if (!hands.held && hands.nearItem && !hands.locked(hands.nearItem)) return 'carry'; } if (nearHatch()) return 'grab'; return revealed.has('grab') && (hands.grab || hands.nearRail) ? 'grab' : null; } /** A press of the hand key shorter than this (seconds) is a tap; longer, at the worksite, runs the tool. */ const TAP_TIME = 0.18; let handHeld = 0; /** The tether key or button held longer than this (seconds) reels in; shorter is a tap, which clips or unclips. */ const HOOK_TAP = 0.3; let hookHeld = 0; let hookClipped = false; // this press clipped the tether, so letting go must not unclip it const EFFECTS: Record = { grab: 'grab', letgo: 'click', clip: 'click', unclip: 'click', pickup: 'grab', drop: 'click', install: 'clunk', equip: 'click', bolt: 'click', taut: 'twang', locked: 'thud', }; function updateFlight(dt: number): void { // Going back in: at the last step, F at the hatch ends the spacewalk. const atHatch = STEPS[stepIndex]?.target?.() === hatchApproach && body.pos.distanceTo(hatchApproach) < 2.2; // One key does every hand job, whichever is on offer. Where the power tool has work to do, // holding the key runs it and a quick tap does the next job down (letting go of a rail, say). const handDown = !show && (input.down('KeyF') || input.down('TouchHand')); const does = handDoes(); let hand: 'carry' | 'grab' | null = null; let drilling = false; if (does === 'work') { if (handDown) drilling = (handHeld += dt) > TAP_TIME; else if (handHeld > 0 && handHeld <= TAP_TIME) hand = handDoes(true) as 'carry' | 'grab' | null; } else if (!show && (input.wasPressed('KeyF') || input.wasPressed('TouchHand'))) hand = does; if (!handDown) handHeld = 0; const grabKey = hand === 'grab'; // One tether control, G or the touch button: a tap clips or unclips at a rail, and holding it reels in. // With no line out there is nothing to reel, so the press clips at once. const hookDown = !show && (input.down('KeyG') || input.down('TouchHook')); let hookTap = false; if (!show && (input.wasPressed('KeyG') || input.wasPressed('TouchHook'))) { hookClipped = hookTap = !hands.tether; hookHeld = 1e-4; // so that a tap shorter than one frame still counts } if (hookDown) hookHeld += dt; else { if (hookHeld > 0 && hookHeld <= HOOK_TAP && hands.tether && !hookClipped && !hookTap) hookTap = true; hookHeld = 0; } const reeling = !show && revealed.has('reel') && hookDown && hookHeld > HOOK_TAP && !!hands.tether; // While a drill is being flown on the tether, a tap is refused: the hook stays on its rail. const tied = !!STEPS[stepIndex]?.tied; if (hookTap && tied && revealed.has('tether')) sound.play('thud'); if (atHatch && grabKey) { mode = 'done'; body.vel.set(0, 0, 0); sound.play('latch'); return; } hands.update(dt, body, cmd, { grab: grabKey && revealed.has('grab'), clip: hookTap && !tied && revealed.has('tether'), carry: (input.wasPressed('KeyC') || hand === 'carry') && revealed.has('carry'), // C still works, unadvertised reel: reeling, work: (drilling || input.down('Mouse0')) && revealed.has('tool'), }); sound.setReel(hands.winding || hands.rewinding, hands.rewinding); for (const e of hands.events) sound.play(EFFECTS[e]); hands.events.length = 0; if (body.impact > 0.4) sound.play('thud'); if (body.impact > TUNING.safeImpact) flashDamage(); emitPuffs(); emitTurnPuffs(dt); // Tutorial bookkeeping const steering = cmd.rot.lengthSq() > 0 || cmd.mouseX !== 0 || cmd.mouseY !== 0; track.turned += Math.hypot(body.angVel.x, body.angVel.y) * dt; track.rolled += Math.abs(body.angVel.z) * dt; if (body.angVel.z > 0) track.rollLeft += body.angVel.z * dt; else track.rollRight -= body.angVel.z * dt; if (hands.tether && reeling) track.reeled += dt; for (const a of AXES) if (Math.abs(body.thrust[a]) > 0.5 && !cmd.brake) track.dirs.add(a + Math.sign(body.thrust[a])); const wp = STEPS[stepIndex]?.waypoint; track.held = wp && body.pos.distanceTo(wp) < 1.5 && body.vel.length() < 0.4 ? track.held + dt : 0; const axes = AXES.filter((a) => Math.abs(body.thrust[a]) > 0.05).length; sound.setThrust(body.fuel > 0 ? axes : 0, steering && !hands.grab && body.fuel > 0 ? 1 : 0); sound.setTool(hands.working >= 0, hands.working >= 0 ? hands.bolts[hands.working] : 0); } /** Gas leaves from the corner nozzles that face away from each thrust direction. */ function emitPuffs(): void { for (const a of AXES) { const t = body.thrust[a]; if (Math.abs(t) < 0.05) continue; const g = -Math.sign(t); // direction the gas goes along this axis for (const sx of SIDES) for (const sy of SIDES) { if ((a === 'x' && sx !== g) || (a === 'y' && sy !== g)) continue; const at = v2.set(sx * NOZZLES.x, sy > 0 ? NOZZLES.yTop : NOZZLES.yBottom, a === 'z' && g < 0 ? NOZZLES.zFront : NOZZLES.zBack); const dir = v1.set((Math.random() - 0.5) * 0.7, (Math.random() - 0.5) * 0.7, (Math.random() - 0.5) * 0.7); dir[a] += g * 3.5; at[a] += g * 0.06; puffs.emit(at.applyQuaternion(body.quat).add(body.pos), dir.applyQuaternion(body.quat).add(body.vel), 1.5); } } } const lastSpin = new THREE.Vector3(); const spinChange = new THREE.Vector3(); const spread = new THREE.Vector3(); /** * Turning costs propellant too, so it shows: whenever the spin rate changes (steering, or attitude * hold stopping a turn) a pair of corner jets on opposite sides fire short, small bursts in * opposite directions. */ function emitTurnPuffs(dt: number): void { spinChange.copy(body.angVel).sub(lastSpin).divideScalar(dt); lastSpin.copy(body.angVel); if (hands.grab || body.fuel <= 0) return; for (const a of AXES) { const accel = spinChange[a]; if (Math.abs(accel) < 0.1) continue; const s = Math.sign(accel); for (const side of SIDES) { // Which corner fires, and which way its gas goes, to twist the suit about this axis. const other = Math.random() < 0.5 ? -1 : 1; const gas = v1.set(0, 0, 0); let x = side, y = other; if (a === 'y') gas.z = side * s; else if (a === 'x') ((x = other), (y = side), (gas.z = -side * s)); else gas.y = -side * s; const at = v2.set(x * NOZZLES.x, y > 0 ? NOZZLES.yTop : NOZZLES.yBottom, gas.z < 0 ? NOZZLES.zFront : NOZZLES.zBack); at.addScaledVector(gas, 0.05); gas.multiplyScalar(1.6).add(spread.set((Math.random() - 0.5) * 0.4, (Math.random() - 0.5) * 0.4, (Math.random() - 0.5) * 0.4)); puffs.emit(at.applyQuaternion(body.quat).add(body.pos), gas.applyQuaternion(body.quat).add(body.vel), 0.7); } } } /** * While waiting in the airlock the astronaut glances about unprompted: down at the suit and * gloves, then at each wall. Each entry is a time in seconds, then yaw and pitch in radians. */ const GLANCES = [ [0, 0, 0], [2.5, 0, 0], [4.5, 0, -0.95], [7, 0.12, -0.9], [9, 0.6, -0.15], [11.5, 0.6, -0.05], [13.5, -0.6, -0.12], [16, -0.55, 0.05], [18, 0, 0.08], [20, 0, 0], ]; const glance = { yaw: 0, pitch: 0 }; const headEuler = new THREE.Euler(); let headWeight = 1; const VISOR = new THREE.Vector3(0, 0.02, -0.33); // from the middle of the helmet to just outside its faceplate function idleGlance(time: number): void { const t = time % GLANCES[GLANCES.length - 1][0]; let n = 0; while (GLANCES[n + 1][0] <= t) n++; const [t0, y0, p0] = GLANCES[n], [t1, y1, p1] = GLANCES[n + 1]; const k = THREE.MathUtils.smootherstep(t, t0, t1); glance.yaw = THREE.MathUtils.lerp(y0, y1, k); glance.pitch = THREE.MathUtils.lerp(p0, p1, k); } /** Gloves lifted in front of the chest while the astronaut looks down at them in the airlock. */ const GLOVE_CHECK = REST_PALMS.map((p) => new THREE.Vector3(p.x * 0.55, HELMET.y - 0.5, HELMET.z - 0.42)); const armTargets = (): (THREE.Vector3 | null)[] => mode === 'airlock' && !egress.on && glance.pitch < -0.45 ? GLOVE_CHECK : hands.handTargets(); // On a touch screen the astronaut can be rolled by dragging: the finger has to land on the suit // (or, from inside the helmet, near the middle of the screen). const rollAt = new THREE.Vector3(); touch.rollZone = () => { if (!started || mode !== 'free' || cinematicOn || !revealed.has('roll') || body.suit <= 0) return null; const r = window.innerHeight * 0.17; if (chaseBlend < 0.5) return { x: window.innerWidth / 2, y: window.innerHeight / 2, r }; rollAt.copy(body.pos).project(camera); return { x: (rollAt.x * 0.5 + 0.5) * window.innerWidth, y: (-rollAt.y * 0.5 + 0.5) * window.innerHeight, r }; }; const visor = $('visor') as unknown as SVGSVGElement; let visorShown = 0; /** * Breathing inside the helmet. One breath is `BREATH` seconds: in, a short hold, then a longer * breath out. Each breath out leaves a trace of mist on the glass, and every so often a heavier one * fogs it properly; either way it clears again slowly. */ const BREATH = 4.4; const air2 = { phase: 0, fog: 0, heavy: 0, next: 9, shown: -1 }; function breathe(dt: number, heard: number, inside: number): void { air2.phase = (air2.phase + dt / BREATH) % 1; const p = air2.phase; const exhaling = p > 0.42; const flow = p < 0.34 ? Math.sin((p / 0.34) * Math.PI) : exhaling && p < 0.9 ? Math.sin(((p - 0.42) / 0.48) * Math.PI) * 0.8 : 0; sound.setBreath(started ? flow * heard : 0, exhaling); if ((air2.next -= dt) <= 0) { air2.heavy = 0.3 + Math.random() * 0.3; air2.next = 14 + Math.random() * 26; } // Mist builds on the way out, towards a level set by how heavy the breath is, and fades at its own slow pace. const reach = 0.07 + air2.heavy; if (exhaling && air2.fog < reach) air2.fog += flow * dt * 0.28 * (0.3 + air2.heavy * 3); air2.fog *= Math.exp(-dt / 7); air2.heavy *= Math.exp(-dt / 5); const fog = Math.round(air2.fog * inside * 100) / 100; if (fog !== air2.shown) { air2.shown = fog; $('fog').style.opacity = String(fog); document.body.style.setProperty('--fog', String(fog)); } } const debug: { inspect: { yaw: number; pitch: number; dist: number } | null } = { inspect: null }; const CHASE_OFFSET = new THREE.Vector3(0, 1.05, 3.5); function updateCamera(dt: number): void { // The figure rides on the body with a little give: see animateBody. astronaut.position.copy(rig.shift).applyQuaternion(body.quat).add(body.pos); astronaut.quaternion.copy(body.quat).multiply(rig.lean); // Inside the airlock the view is from the helmet. const goal = mode !== 'airlock' && view === 'chase' ? 1 : 0; chaseBlend += THREE.MathUtils.clamp(goal - chaseBlend, -dt / 1.2, dt / 1.2); const e = THREE.MathUtils.smootherstep(chaseBlend, 0, 1); astronaut.visible = cinematicOn || e > 0.3; // First person is seen from inside the helmet: its rim fades in as the camera comes forward. // A phone's screen is too small for the rim, so there first person is a plain view (the breathing stays). const first = cinematicOn || debug.inspect ? 0 : 1 - THREE.MathUtils.smoothstep(e, 0, 0.35); const inside = touchMode ? 0 : first; if (inside !== visorShown) visor.style.opacity = String((visorShown = inside)); document.body.classList.toggle('helmet', inside > 0.5); breathe(dt, first, inside); if (show) { updateShow(dt); camera.updateMatrixWorld(); return; } if (cinematicOn) { cinematic.update(dt, camera, body.pos, station.colliders, egress.on ? egressSight : body.pos); camera.updateMatrixWorld(); return; } // From the helmet the camera is locked to the head; from behind it trails the turn a little. camQuat.slerp(body.quat, 1 - Math.exp(-THREE.MathUtils.lerp(80, 10, e) * dt)); camera.position.lerpVectors(HELMET, CHASE_OFFSET, e).applyQuaternion(camQuat).add(body.pos); camera.quaternion.copy(camQuat); // In the airlock the head turns while the body stays put, so looking down shows the suit. The // eye sits at the front of the visor, which keeps the helmet itself out of the picture. const headFree = mode === 'airlock' && !egress.on ? 1 : 0; headWeight += THREE.MathUtils.clamp(headFree - headWeight, -dt / 0.8, dt / 0.8); if (mode === 'airlock') { idleGlance(clock); headEuler.set(air.pitch + glance.pitch * headWeight, air.yaw + glance.yaw * headWeight, 0, 'YXZ'); camera.quaternion.multiply(q1.setFromEuler(headEuler)); camera.position.add(v1.copy(VISOR).applyQuaternion(camQuat)); astronaut.visible = true; } if (debug.inspect) { // Development only: orbit the camera around the astronaut to look at the model. const { yaw, pitch, dist } = debug.inspect; camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(dist); camera.position.applyQuaternion(body.quat).add(body.pos); camera.up.set(0, 1, 0).applyQuaternion(body.quat); camera.lookAt(body.pos); astronaut.visible = true; } camera.updateMatrixWorld(); } // --- HUD -------------------------------------------------------------- const fwd = new THREE.Vector3(); /** Put a HUD element over a world direction or point; optionally pin it to the screen edge when out of view. */ function place(el: HTMLElement, world: THREE.Vector3, pin: boolean): void { camera.getWorldDirection(fwd); const behind = v1.copy(world).sub(camera.position).dot(fwd) <= 0; const p = v1.copy(world).project(camera); if (behind) { if (!pin) { el.style.display = 'none'; return; } p.x = -p.x; p.y = -p.y; } const m = Math.max(Math.abs(p.x), Math.abs(p.y)); if (behind || m > 0.84) { if (!pin) { el.style.display = 'none'; return; } p.x *= 0.84 / (m || 1); p.y *= 0.84 / (m || 1); } el.style.display = 'block'; const x = (p.x * 0.5 + 0.5) * window.innerWidth - el.offsetWidth / 2; let y = (-p.y * 0.5 + 0.5) * window.innerHeight - el.offsetHeight / 2; // An arrow pinned to the top edge sits under the instruction box, never across it. if (pin) y = Math.max(y, $('objective').getBoundingClientRect().bottom + 6); el.style.transform = `translate(${x.toFixed(1)}px, ${y.toFixed(1)}px)`; } function setBar(bar: HTMLElement, label: HTMLElement, pct: number): void { bar.style.width = `${pct}%`; bar.className = `fill${pct < 15 ? ' crit' : pct < 35 ? ' warn' : ''}`; label.textContent = `${Math.round(pct)}%`; } const el = { speed: $('speed'), fuel: $('fuel'), fuelBar: $('fuel-bar'), suit: $('suit'), suitBar: $('suit-bar'), hold: $('hold'), sunLabel: $('sun-label'), sunTime: $('sun-time'), objective: $('objective'), beacon: $('marker-beacon'), beaconArrow: $('beacon-arrow'), beaconDist: $('beacon-dist'), flash: $('flash'), tether: $('tether'), prompt: $('prompt'), }; function updateHud(dt: number): void { document.body.classList.toggle('airlock', mode === 'airlock'); if (titleTimer > 0 && (titleTimer -= dt) <= 0) $('title').classList.remove('show'); const speed = body.vel.length(); el.speed.textContent = hands.grab ? 'HOLDING RAIL' : `${speed.toFixed(2)} m/s`; el.speed.style.color = speed > TUNING.safeImpact ? '#ffc857' : ''; setBar(el.fuelBar, el.fuel, body.fuel); setBar(el.suitBar, el.suit, body.suit); el.hold.textContent = body.hold ? 'ON' : 'OFF'; el.hold.style.color = body.hold ? '#6fe3a5' : '#ffc857'; const ev = nextSunEvent(); el.sunLabel.textContent = ev.label; el.sunTime.textContent = `${Math.floor(ev.seconds / 60)}:${String(Math.floor(ev.seconds % 60)).padStart(2, '0')}`; if (hands.tether) { el.tether.textContent = `${hands.tetherOut.toFixed(1)} / ${HANDS_ON.tetherLength} m`; el.tether.style.color = hands.taut ? '#ffc857' : ''; } else { el.tether.textContent = 'UNCLIPPED'; el.tether.style.color = '#ff8a8a'; } // Only touch the page when the text changes, so the pulsing prompt's animation isn't restarted every frame. const promptHtml = mode === 'free' ? promptLines().join('
') : ''; if (promptHtml !== lastPrompt) el.prompt.innerHTML = lastPrompt = promptHtml; const step = STEPS[stepIndex]; const target = mode === 'free' ? (step?.waypoint ?? step?.target?.() ?? null) : null; if (target && !cinematicOn) { const dist = `${body.pos.distanceTo(target).toFixed(1)} m`; camera.getWorldDirection(fwd); const ahead = v1.copy(target).sub(camera.position).dot(fwd) > 0; const p = v1.copy(target).project(camera); if (ahead && Math.abs(p.x) < 0.9 && Math.abs(p.y) < 0.86) { // In view: the bouncing arrow, drawn in the scene so the astronaut can pass in front of it. marker.show(target, camera, dist, dt, ui); el.beacon.style.display = 'none'; } else { // Out of view: an arrow on the edge of the screen, pointing the way to turn. marker.hide(); const side = ahead ? 1 : -1; const angle = Math.atan2(-p.y * side * window.innerHeight, p.x * side * window.innerWidth); el.beaconArrow.style.transform = `rotate(${angle.toFixed(3)}rad)`; if (el.beaconDist.textContent !== dist) el.beaconDist.textContent = dist; place(el.beacon, target, true); } } else { marker.hide(); el.beacon.style.display = 'none'; } let text = step?.goal() ?? ''; const dry = mode === 'free' && body.fuel <= 0 && !hands.grab; const lost = body.suit <= 0 || (mode === 'free' && !hands.tether && (dry || body.pos.length() > 150)); const why = !lost ? '' : body.suit <= 0 ? 'suit' : dry ? 'dry' : 'drift'; if (why !== lostWhy && (lostWhy = why)) analytics.lost(why); if (body.suit <= 0) text = `Suit breach. ${press('R')} to restart this chapter.`; else if (mode === 'free' && !hands.tether && body.pos.length() > 150) text = `You have drifted out of reach of the station. ${press('R')} to restart this chapter.`; else if (dry) text = hands.tether ? `Propellant empty. ${hold('G')} to reel in on your tether.` : `Propellant empty. ${press('R')} to restart this chapter.`; if (text !== lastObjective) { // A redrawn key picks up its bobbing where the last one left off. el.objective.style.setProperty('--phase', `${(-(clock % 0.9)).toFixed(2)}s`); el.objective.innerHTML = lastObjective = text; el.objective.style.display = text ? 'block' : 'none'; } if (touchMode) updateTouch(lost, dry); // The moving finger that shows the roll: over the astronaut, for as long as the roll is being taught and no real finger is on it. const zone = touchMode && step?.reveal?.includes('roll') && !touch.rolling ? touch.rollZone() : null; ghost.style.display = zone ? 'block' : 'none'; if (zone) ghost.style.transform = `translate(${zone.x.toFixed(0)}px, ${zone.y.toFixed(0)}px)`; // The moving mouse that shows how to look around: under the instruction, clear of the astronaut, while looking is being taught. const mousing = !touchMode && started && !ended && mode === 'free' && !!step?.reveal?.includes('look'); ghostMouse.style.display = mousing ? 'block' : 'none'; if (mousing) ghostMouse.style.transform = `translate(${(innerWidth / 2).toFixed(0)}px, ${Math.max(120, innerHeight * 0.2).toFixed(0)}px)`; } let lastObjective = ''; const ghost = $('ghost'); const ghostMouse = $('ghost-mouse'); /** Each on-screen control appears when the tutorial reaches it, and pulses when it is the thing to press. */ function updateTouch(lost: boolean, dry: boolean): void { const has = (id: string) => revealed.has(id); const teaching = (id: string) => !!((touchMode && STEPS[stepIndex]?.touchReveal) || STEPS[stepIndex]?.reveal)?.includes(id); const inside = started && mode === 'airlock' && !egress.on; const free = started && mode === 'free' && body.suit > 0; const does = free ? handDoes() : null; touch.showStick(inside || (free && has('look'))); touch.show('thrust', (inside && has('forward')) || (free && has('move')), inside || teaching('move')); touch.show('stop', free && has('brake'), teaching('brake')); // The hand shows only while there is something for a hand to do, and pulses for a new chance to take hold. touch.show('grab', (inside && air.want === 0) || !!does, inside || does === 'work' || (!hands.grab && !hands.held && !(does === 'grab' && !nearHatch() && hands.tooFast(body)))); // The tether button is there only while it can do something: clip at a rail within reach, or reel in // when the line is taut, the propellant is gone, or the reel is being taught. const reelNow = has('reel') && !!hands.tether && (hands.taut || dry || teaching('reel')); touch.show('hook', free && has('tether') && ((!!hands.nearRail && !STEPS[stepIndex]?.tied) || reelNow || input.down('TouchHook')), teaching('tether') || reelNow); // it stays while held, so a reel is not cut short touch.show('camera', free && has('camera'), teaching('camera')); touch.show('restart', started && lost, true); } let lastPrompt = ''; const key = (k: string, text: string) => `${touchMode ? ico(KEY_BUTTON[k]) : `${k}`} ${text}`; const clipFirst = () => revealed.has('tether') && !STEPS[stepIndex]?.tied && !!hands.grab && hands.tether?.rail !== hands.grab.rail; /** Context prompts for whatever is within reach. Keys the tutorial has not introduced yet stay hidden. */ function promptLines(): string[] { const lines: string[] = []; // One key serves every hand job, so only the job it would do right now is offered. const does = handDoes(); if (does === 'work') lines.push(`${key('F', hands.installed()?.name === hands.socket.item ? 'hold to tighten bolts' : 'hold to release bolts')}`); else if (does === 'carry') { if (hands.held) { const outcome = hands.releaseOutcome(); const what = hands.held.label; // Fitting or stowing is offered; simply letting an item go is left for the player to find. if (outcome === 'install') lines.push(key('F', `install ${what}`)); else if (outcome === 'stow') lines.push(key('F', `stow ${what} on the rail`)); } else if (hands.nearItem) lines.push(key('F', `pick up ${hands.nearItem.label}`)); } else if (revealed.has('grab')) { // Holding a rail with the tether still to clip here, the clip is the one thing offered. if (hands.grab) clipFirst() || lines.push(key('F', 'let go and push off')); else if (hands.nearRail) lines.push(hands.tooFast(body) ? 'Too fast to grab the rail' : `${key('F', 'grab handrail')}`); } if (revealed.has('carry') && !hands.held && hands.nearItem && hands.locked(hands.nearItem)) lines.push(`The ${hands.nearItem.label} is bolted down`); // The tether is offered once the rail is in hand, or when a hand is full and cannot take the rail: never alongside a grab or a pick-up. const tied = !!STEPS[stepIndex]?.tied; if (revealed.has('tether') && hands.nearRail && (hands.grab || hands.held) && !tied) { const clipped = hands.tether?.rail === hands.nearRail.rail; if (!clipped) lines.push(`${key('G', 'clip tether here')}`); else if (!hands.grab) lines.push(key('G', 'unclip tether')); } if (hands.taut && revealed.has('reel')) lines.push(`Tether at full length. ${key('G', 'hold to reel in')}`); return lines; } function flashDamage(): void { el.flash.style.transition = 'none'; el.flash.style.opacity = '0.35'; void el.flash.offsetWidth; el.flash.style.transition = ''; el.flash.style.opacity = '0'; } // --- Start and loop --------------------------------------------------- /** How much the panels and text are enlarged for a big frame; 1 on ordinary ones. See --ui in the styles. */ let ui = 1; function resize(): void { ui = THREE.MathUtils.clamp(Math.round((window.innerHeight / 800) * 20) / 20, 1, 1.6); document.documentElement.style.setProperty('--ui', String(ui)); renderer.setSize(window.innerWidth, window.innerHeight); composer?.setPixelRatio(sharpness); composer?.setSize(window.innerWidth, window.innerHeight); camera.aspect = window.innerWidth / window.innerHeight; cinematic.spread = THREE.MathUtils.clamp(1.25 / camera.aspect, 1, 2.2); camera.updateProjectionMatrix(); drawVisor($('visor') as unknown as SVGSVGElement, window.innerWidth, window.innerHeight, !POLISHED); } window.addEventListener('resize', resize); resize(); // The portal's SDK is set up in the background; the game never waits for it. platform.onMute = (muted) => sound.forceMute(muted); analytics.init(); void platform.init().then(() => { if (platform.device === 'mobile' || platform.device === 'tablet') enableTouch(); }); /** Begin (or begin again) from a card's button. The portal gets its chance for a break first. */ async function begin(step: number): Promise { if (platform.busy) return; sound.start(); // within the click, as browsers require await platform.pause(); started = true; $('start').classList.add('hidden'); sound.forceMute(platform.muted); input.lock(); startFrom(step); } $('start-btn').addEventListener('click', () => void begin(0)); $('skip-btn').addEventListener('click', () => void begin(MISSION_2)); $('next-btn').addEventListener('click', () => void begin(MISSION_2)); // Anyone who has flown the first mission here before can go straight to the second. try { if (localStorage.getItem(DONE_KEY)) $('skip-btn').classList.remove('hidden'); } catch { /* no storage: only the full game is offered */ } renderer.domElement.addEventListener('click', () => started && input.lock()); $('again-btn').addEventListener('click', () => void begin(chapterStart(ended ?? stepIndex))); // Before the game starts, show the airlock interior behind the title card. body.pos.copy(AIRLOCK.start); body.quat.copy(FACING_OUT); camQuat.copy(FACING_OUT); hands.reset(body, false); let last = performance.now(); let clock = 0; // Polished look: if a second and a half of frames average slower than about 45 a second, draw // fewer pixels (the picture is then stretched to fit, slightly softer). It never goes back up. const pace = { frames: 0, ms: 0 }; /** Store pictures and videos (npm run media) are always made at full size. */ const CAPTURING = import.meta.env.DEV && new URLSearchParams(location.search).has('capture'); function watchPace(ms: number): void { if (!POLISHED || !started || document.hidden || ms > 250 || clock < 4 || CAPTURING) return; pace.frames++; pace.ms += ms; if (pace.frames < 90) return; const average = pace.ms / pace.frames; pace.frames = pace.ms = 0; if (average < 22 || sharpness <= 0.75) return; sharpness = Math.max(0.75, sharpness - 0.25); renderer.setPixelRatio(sharpness); resize(); } function frame(now: number): void { watchPace(now - last); const dt = Math.min((now - last) / 1000, 1 / 30); last = now; clock += dt; // While the portal is showing a break, nothing in the game moves and no key does anything. if (started && !platform.busy) { readInput(dt); if (mode === 'airlock') updateAirlock(dt); else if (mode === 'free' && body.suit > 0) updateFlight(dt); updateHatch(dt); if (mode !== 'free' || body.suit <= 0) (sound.setThrust(0, 0), sound.setTool(false), sound.setReel(false)); track.time += dt; missionClock += dt; if (stepIndex >= 0) advance(); pumpRadio(dt); } input.endFrame(); animateBody(rig, body.vel, body.angVel, body.quat, clock, dt); poseArms(rig, armTargets(), dt); puffs.update(dt); updatePower(dt); updateCamera(dt); updateOrbit(dt); updateHud(dt); updateMirror(dt); if (composer) composer.render(dt); else renderer.render(scene, camera); requestAnimationFrame(frame); } requestAnimationFrame(frame); /** Development only: cut the film camera to a chosen kind of shot. */ function film(kind: 'close' | 'wide' | 'orbit' | 'chase'): void { if (kind === 'chase') { view = 'chase'; setCinematic(false); return; } if (!cinematicOn) setCinematic(true); cinematic.cut(body.pos, station.colliders, kind); } if (import.meta.env.DEV) { Object.assign(window, { game: { renderer, scene, earth, stationMesh: station.mesh, sun, draw: () => (composer ? composer.render() : renderer.render(scene, camera)), mirrorNow: () => ((mirrorAge = Infinity), updateMirror(0)), camera, reveal, film, power, strike, MISSION_2, showTime: () => show?.t ?? -1, fogUp: (v: number) => (air2.fog = v), showAt: (t: number) => show && ((show.t = t), show.kind === 'power' ? (power.age = t) : show.kind === 'unfurl' && (strike.age = t)), body, cmd, TUNING, orbit, debug, hands, rig, air, track, sound, startFrom, jump: beginStep, colliders: station.colliders, step: () => stepIndex, mode: () => mode }, }); } if (CAPTURING) { void import('./capture').then((m) => m.run((window as unknown as { game: unknown }).game)); }