From 567ac1a26dd3ede8dc5f4222bccabe19d1ce1bb3 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 15 Nov 2026 20:19:41 +0300 Subject: [PATCH] Add a built-in wiki. --- public/css/hud.css | 62 + public/css/screens.css | 73 + public/css/themes.css | 20 +- src/client/app.ts | 42 + src/client/glossary.ts | 188 ++ src/client/router.ts | 3 + src/client/screens/builder/diagnosticsBar.ts | 96 +- src/client/screens/dashboard.ts | 72 + src/client/screens/dashboard/sidebarCards.ts | 8 + src/client/screens/launch/orbitPhase.ts | 3 +- src/client/screens/mainMenu.ts | 8 + src/client/screens/wiki.ts | 34 + src/client/session.ts | 4 +- src/client/state.ts | 11 +- src/client/three/earthTexture.ts | 10 +- src/client/ui/tooltip.ts | 35 +- src/client/wiki/interactiveLabs.ts | 1680 ++++++++++++++++++ src/client/wiki/walkthrough.ts | 490 +++++ src/client/wiki/wikiData.ts | 687 +++++++ src/client/wiki/wikiModal.ts | 55 + src/client/wiki/wikiWorkspace.ts | 441 +++++ src/server/ai/runner.ts | 19 +- src/server/hazards.ts | 5 +- src/server/routes/agencyRoutes.ts | 18 +- src/server/routes/contractRoutes.ts | 16 +- src/server/routes/missionRoutes.ts | 34 +- src/shared/compliance.ts | 8 +- src/shared/compliance/evaluate.ts | 26 + 28 files changed, 4030 insertions(+), 118 deletions(-) create mode 100644 src/client/screens/wiki.ts create mode 100644 src/client/wiki/interactiveLabs.ts create mode 100644 src/client/wiki/walkthrough.ts create mode 100644 src/client/wiki/wikiData.ts create mode 100644 src/client/wiki/wikiModal.ts create mode 100644 src/client/wiki/wikiWorkspace.ts diff --git a/public/css/hud.css b/public/css/hud.css index fc8afb4..0d4b678 100644 --- a/public/css/hud.css +++ b/public/css/hud.css @@ -112,6 +112,16 @@ .notif-drawer { width: min(370px, calc(100vw - 32px)) !important; } + .wiki-layout { + grid-template-columns: 1fr; + grid-template-rows: auto 1fr; + } + .wiki-sidebar { + max-height: 210px; + border-right: none; + border-bottom: 1px solid var(--border); + padding-bottom: 14px; + } } .builder-summary-bar { @@ -270,3 +280,55 @@ color: var(--brand-blue); background: var(--bg-elevated); } + +.wiki-drawer-overlay { + z-index: 190; + padding: 18px; +} +.wiki-drawer-panel { + width: min(1160px, 100%); + height: min(88vh, 880px); + max-height: none; + padding: 0; + display: flex; + flex-direction: column; + overflow: hidden; +} + +#walkthrough-coach-root { + position: fixed; + top: 62px; + left: calc(50% - var(--right-sidebar-offset, 0px) / 2); + transform: translateX(-50%); + z-index: 160; + max-width: min(470px, calc(100vw - var(--right-sidebar-offset, 0px) - 32px)); + pointer-events: none; +} +#walkthrough-coach-root > * { + pointer-events: auto; +} +.walkthrough-card { + padding: 12px 14px; + border-color: var(--sim-accent); + box-shadow: 0 10px 28px rgba(0, 0, 0, 0.55); +} +.walkthrough-pill { + padding: 6px 10px; + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + border-color: var(--sim-accent); +} +.walkthrough-title { + font-family: var(--mono); + font-size: 12px; + font-weight: 700; + color: var(--text); + margin-bottom: 3px; +} +.walkthrough-hint { + font-size: 11px; + line-height: 1.45; + color: var(--text-dim); +} diff --git a/public/css/screens.css b/public/css/screens.css index 3b83fdd..92e52b4 100644 --- a/public/css/screens.css +++ b/public/css/screens.css @@ -218,3 +218,76 @@ .grade { font-size: 68px; font-weight: 800; font-family: var(--mono); line-height: 1; } .grade.s { color: var(--brand-blue); } .grade.a { color: var(--green); } .grade.b { color: var(--amber); } .grade.c { color: var(--red); } .grade.f { color: var(--red); } + +.wiki-page { display: flex; flex-direction: column; height: 100%; overflow: hidden; background: var(--bg-deep); } +.wiki-topbar { + padding: 12px 20px; border-bottom: 1px solid var(--border); background: var(--bg-panel-solid); + display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; flex-shrink: 0; +} +.wiki-topbar-controls { flex-wrap: wrap; align-items: center; } +.wiki-search-input { width: clamp(210px, 24vw, 300px); min-width: 180px; } +.wiki-layout { + display: grid; grid-template-columns: 270px 1fr; flex: 1; min-height: 0; overflow: hidden; +} +.wiki-sidebar { + border-right: 1px solid var(--border); background: var(--bg-panel-solid); + padding: 14px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; padding-bottom: 64px; +} +.wiki-nav-group { display: flex; flex-direction: column; gap: 4px; } +.wiki-nav-cat { + font-family: var(--mono); font-size: 9px; font-weight: 700; letter-spacing: 0.14em; + text-transform: uppercase; color: var(--text-faint); padding: 4px 6px; +} +.wiki-nav-item { + display: flex; align-items: center; justify-content: space-between; gap: 6px; width: 100%; + padding: 8px 10px; background: transparent; border: 1px solid transparent; clip-path: var(--chamfer-sm); + color: var(--text-dim); font-family: var(--mono); font-size: 11px; text-align: left; cursor: pointer; + transition: background-color 0.14s, border-color 0.14s, color 0.14s; +} +.wiki-nav-item:hover { background: var(--bg-elevated); color: var(--text); border-color: var(--border); } +.wiki-nav-item.active { background: var(--sim-glow); color: var(--sim-accent); border-color: var(--sim-accent); } +.wiki-search-hit { + display: flex; flex-direction: column; gap: 3px; width: 100%; padding: 8px 10px; + background: var(--bg-deep); border: 1px solid var(--border); clip-path: var(--chamfer-sm); + color: var(--text); text-align: left; cursor: pointer; +} +.wiki-search-hit:hover { border-color: var(--sim-accent); background: var(--bg-elevated); } +.wiki-main { + overflow-y: auto; padding: 22px 26px 86px; display: flex; flex-direction: column; gap: 16px; +} +.wiki-main > * { max-width: 980px; } +.wiki-article-header h2 { font-size: 20px; color: var(--text); } +.wiki-callout { + display: flex; align-items: flex-start; gap: 10px; padding: 11px 14px; + background: rgba(52, 211, 153, 0.08); border: 1px solid rgba(52, 211, 153, 0.35); + clip-path: var(--chamfer-sm); color: var(--text); +} +.wiki-section { padding: 16px 18px; display: flex; flex-direction: column; gap: 10px; } +.wiki-prose { font-size: 13px; line-height: 1.62; color: var(--text-dim); } +.wiki-bullets { + padding-left: 18px; display: flex; flex-direction: column; gap: 6px; + font-size: 12px; line-height: 1.55; color: var(--text); +} +.wiki-formula { + padding: 8px 12px; background: var(--bg-deep); border: 1px solid var(--border-bright); + clip-path: var(--chamfer-sm); font-family: var(--mono); font-size: 12px; color: var(--brand-blue); +} +.wiki-lab-card { padding: 16px 18px; } +.wiki-lab-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; } +.wiki-checklist-item { + padding: 10px 12px; background: var(--bg-deep); border: 1px solid var(--border); + clip-path: var(--chamfer-sm); transition: border-color 0.15s; +} +.wiki-checklist-item.done { border-color: rgba(52, 211, 153, 0.45); } +.wiki-glossary-card { padding: 12px 14px; display: flex; flex-direction: column; gap: 4px; } +.wiki-glossary-card.highlighted { border-color: var(--sim-accent); box-shadow: 0 0 18px var(--sim-glow); } +.wiki-refs-section { margin-top: 4px; } +.wiki-ref-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; } +.wiki-ref-card { + display: block; text-decoration: none; color: inherit; padding: 12px 14px; + background: var(--bg-panel-solid); border: 1px solid var(--border); clip-path: var(--chamfer-sm); + transition: border-color 0.15s, background-color 0.15s; +} +.wiki-ref-card:hover { border-color: var(--brand-blue); background: var(--bg-elevated); } +.wiki-ext-link { text-decoration: none; } +.wiki-footer-nav { padding-top: 8px; border-top: 1px solid var(--border); } diff --git a/public/css/themes.css b/public/css/themes.css index facd93a..3f99f2d 100644 --- a/public/css/themes.css +++ b/public/css/themes.css @@ -113,7 +113,15 @@ :root.reduced-effects .launch-events, :root.reduced-effects .comfort-btn, :root.reduced-effects .notif-toggle-bar, -:root.reduced-effects .hud-tooltip { +:root.reduced-effects .hud-tooltip, +:root.reduced-effects .wiki-nav-item, +:root.reduced-effects .wiki-search-hit, +:root.reduced-effects .wiki-callout, +:root.reduced-effects .wiki-formula, +:root.reduced-effects .wiki-checklist-item, +:root.reduced-effects .wiki-ref-card, +:root.reduced-effects .walkthrough-card, +:root.reduced-effects .walkthrough-pill { clip-path: none !important; border-radius: 4px; } @@ -168,6 +176,16 @@ .hud-tooltip[hidden] { display: none; } +.hud-tooltip.pinned { + pointer-events: auto; +} +.hud-tooltip-actions { + margin-top: 8px; + padding-top: 6px; + border-top: 1px solid var(--border); + display: flex; + justify-content: flex-end; +} .hud-tooltip-cat { font-family: var(--mono); font-size: 9px; diff --git a/src/client/app.ts b/src/client/app.ts index b1a7db4..cbde370 100644 --- a/src/client/app.ts +++ b/src/client/app.ts @@ -10,8 +10,10 @@ import { import { applyThemeFromState, type DebriefScreenParams, + getCurrentScreen, type LaunchScreenParams, state, + type WikiScreenParams, } from "./state.js"; import { getColorMode, @@ -35,7 +37,11 @@ import { renderMainMenu } from "./screens/mainMenu.js"; import { renderMissionConfig } from "./screens/missionConfig.js"; import { renderOnboarding } from "./screens/onboarding.js"; import { renderRocketBuilder } from "./screens/rocketBuilder.js"; +import { renderWiki } from "./screens/wiki.js"; import { renderWorldMap } from "./screens/worldMap.js"; +import { initWalkthroughController } from "./wiki/walkthrough.js"; +import type { WikiArticleId } from "./wiki/wikiData.js"; +import { openWikiDrawer } from "./wiki/wikiModal.js"; registerScreenRenderers({ mainMenu: (el) => renderMainMenu(el), @@ -48,6 +54,7 @@ registerScreenRenderers({ debrief: (el, p) => renderDebrief(el, p as DebriefScreenParams), contracts: (el) => renderContracts(el), worldMap: (el) => renderWorldMap(el), + wiki: (el, p) => renderWiki(el, p as WikiScreenParams), }); function renderComfortToolbar(): void { @@ -122,6 +129,41 @@ async function boot(): Promise { window.addEventListener("sgywftp:theme-changed", renderComfortToolbar); initNotificationDrawer(); initTooltipController(); + initWalkthroughController(); + window.addEventListener("sgywftp:open-wiki", (ev) => { + const detail = + ( + ev as CustomEvent<{ + articleId?: WikiArticleId; + glossaryKey?: string; + query?: string; + preferDrawer?: boolean; + }> + ).detail ?? {}; + const cur = getCurrentScreen(); + const preserveScreens = new Set([ + "builder", + "config", + "launch", + "debrief", + "contracts", + "worldMap", + ]); + if (detail.preferDrawer || preserveScreens.has(cur)) { + openWikiDrawer({ + articleId: detail.articleId, + glossaryKey: detail.glossaryKey, + query: detail.query, + }); + } else { + navigate("wiki", { + articleId: detail.articleId, + glossaryKey: detail.glossaryKey, + query: detail.query, + returnTo: cur === "wiki" ? "dashboard" : cur, + }); + } + }); const readyPromise = waitForStylesAndLoad(); try { await loadCatalogs(); diff --git a/src/client/glossary.ts b/src/client/glossary.ts index 2dbab46..bd33e01 100644 --- a/src/client/glossary.ts +++ b/src/client/glossary.ts @@ -1,4 +1,6 @@ // Terminologic glossary, cus I forget what this shit means every 2 seconds pls don't ask me this, I not know rockeet siençe +import type { WikiArticleId } from "./wiki/wikiData.js"; + export interface GlossaryEntry { title: string; summary: string; @@ -9,6 +11,9 @@ export interface GlossaryEntry { | "Flight & Orbit" | "Avionics & Bus" | "Program & Compliance"; + wikiArticleId?: WikiArticleId; + wikipediaTitle?: string; + wikipediaUrl?: string; } const TERMINOLOGY_GLOSSARY_RAW = { @@ -19,6 +24,9 @@ const TERMINOLOGY_GLOSSARY_RAW = { formula: "Δv = Isp · g0 · ln(m_wet / m_dry) (two-phase when jettisoning drop tanks)", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Delta-v", + wikipediaUrl: "https://en.wikipedia.org/wiki/Delta-v", }, dv_margin: { title: "Delta-v Margin", @@ -26,12 +34,18 @@ const TERMINOLOGY_GLOSSARY_RAW = { "Difference between your rocket Δv and the mission target requirement. Positive margin provides reserve for wind shear, throttling, and guidance dispersion.", formula: "Margin = Vehicle Δv − Required Δv", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Tsiolkovsky rocket equation", + wikipediaUrl: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation", }, req_dv: { title: "Required Delta-v", summary: "Minimum velocity budget needed to enter the target orbit, including inclination plane cost, Earth ascent losses (~1,400–1,800 m/s), and transfer burns.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Delta-v", + wikipediaUrl: "https://en.wikipedia.org/wiki/Delta-v", }, twr: { title: "Thrust-to-Weight Ratio (TWR)", @@ -39,12 +53,18 @@ const TERMINOLOGY_GLOSSARY_RAW = { "Total engine thrust divided by vehicle Earth weight at liftoff. Must exceed 1.02 to lift off the pad; 1.30–1.70 minimizes gravity losses without excessive Max-Q.", formula: "TWR = Thrust / (Wet Mass × 9.81 m/s²)", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Thrust-to-weight ratio", + wikipediaUrl: "https://en.wikipedia.org/wiki/Thrust-to-weight_ratio", }, stage_twr: { title: "Stage Ignition TWR", summary: "Thrust-to-weight ratio at the moment this stage ignites in flight. Upper stages should maintain ≥ 0.50 so the vehicle climbs past apoapsis before falling back.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Multistage rocket", + wikipediaUrl: "https://en.wikipedia.org/wiki/Multistage_rocket", }, isp: { title: "Specific Impulse (Isp)", @@ -52,60 +72,91 @@ const TERMINOLOGY_GLOSSARY_RAW = { "Propellant fuel efficiency measured in seconds (higher means more thrust per kg burned per second). Vacuum Isp is higher than sea-level Isp due to zero atmospheric backpressure.", formula: "ve = Isp · g0 (effective exhaust velocity)", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Specific impulse", + wikipediaUrl: "https://en.wikipedia.org/wiki/Specific_impulse", }, nozzle_ratio: { title: "Nozzle Expansion Ratio", summary: "Bell exit-area scaling factor. Smaller bells (0.85–1.0×) resist sea-level flow separation near liftoff; wider bells (1.15–1.4×) boost vacuum Isp on upper stages.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "De Laval nozzle", + wikipediaUrl: "https://en.wikipedia.org/wiki/De_Laval_nozzle", }, gimbal: { title: "Gimbal Deflection Range", summary: "Maximum nozzle pivot angle (± degrees) for Thrust Vector Control (TVC). Enables steering during the pitch-over turn and counters aerodynamic instability or wind shear.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Gimbaled thrust", + wikipediaUrl: "https://en.wikipedia.org/wiki/Gimbaled_thrust", }, propellant_chemistry: { title: "Propellant Chemistry", summary: "Kerolox (RP-1/LOX) is dense with high thrust; Hydrolox (LH2/LOX) offers top Isp but needs bulky insulated tanks; Methalox balances density & efficiency; Hypergolic is storable; Solid cannot throttle.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Liquid-propellant rocket", + wikipediaUrl: "https://en.wikipedia.org/wiki/Liquid-propellant_rocket", }, crossfeed: { title: "Propellant Crossfeed", summary: "Plumbing manifold that draws fuel and oxidizer from external drop tanks first while keeping the core tank full, allowing empty external casings to drop early mid-burn.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Propellant crossfeed", + wikipediaUrl: "https://en.wikipedia.org/wiki/Propellant_crossfeed", }, drop_tanks: { title: "Disposable Drop Tanks", summary: "Aerodynamic external tanks mounted radially onto a liquid stage (e.g., 1× Shuttle-style belly tank or 2×–6× side pods). Drained first via crossfeed and jettisoned empty mid-burn to raise Δv.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Propellant crossfeed", + wikipediaUrl: "https://en.wikipedia.org/wiki/Propellant_crossfeed", }, fill_ratio: { title: "Tank Fill Ratio", summary: "Percentage of propellant volume loaded before launch (Expert mode). Offloading propellant lowers liftoff weight and raises TWR at the cost of reduced total Δv.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Tsiolkovsky rocket equation", + wikipediaUrl: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation", }, engine_count: { title: "Engine Cluster Count", summary: "Number of identical engines mounted on this stage thrust structure. Multiplies stage thrust and mass flow proportionally while keeping the same propellant tank.", category: "Propulsion", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Rocket engine", + wikipediaUrl: "https://en.wikipedia.org/wiki/Rocket_engine", }, wet_dry_mass: { title: "Wet vs Dry Mass", summary: "Wet mass is fueled liftoff mass (structure + engines + payload + propellant). Dry mass is structural mass remaining at burnout. Rocket Δv grows with the ratio of Wet to Dry mass.", category: "Structures & Aero", + wikiArticleId: "propulsion-staging", + wikipediaTitle: "Tsiolkovsky rocket equation", + wikipediaUrl: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation", }, cg_cp: { title: "CG vs CP (Center of Gravity / Pressure)", summary: "CG is the mass balance point; CP is where aerodynamic lift acts. Keeping CG ahead of (above) CP makes the rocket naturally arrow-stable in flight.", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Center of pressure (fluid mechanics)", + wikipediaUrl: + "https://en.wikipedia.org/wiki/Center_of_pressure_(fluid_mechanics)", }, stability_calibers: { title: "Static Stability Margin (Calibers)", @@ -113,6 +164,9 @@ const TERMINOLOGY_GLOSSARY_RAW = { "Distance from Center of Pressure up to Center of Gravity divided by hull diameter. Positive calibers passively stabilize ascent; deeply negative values risk tumbling under Max-Q.", formula: "Margin = (CG_y − CP_y) / Max Diameter", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Center of mass", + wikipediaUrl: "https://en.wikipedia.org/wiki/Center_of_mass", }, fineness: { title: "Fineness Ratio (L / D)", @@ -120,6 +174,9 @@ const TERMINOLOGY_GLOSSARY_RAW = { "Ratio of overall rocket height to maximum fuselage diameter. Tall slender rockets (> 20.5 L/D) cut frontal drag but endure sharper structural bending during Max-Q.", formula: "L/D = Total Height / Max Diameter", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Fineness ratio", + wikipediaUrl: "https://en.wikipedia.org/wiki/Fineness_ratio", }, buckling: { title: "Axial Buckling Ratio", @@ -127,6 +184,9 @@ const TERMINOLOGY_GLOSSARY_RAW = { "Ratio of peak compressive/bending launch load to the airframe shell limit. Must remain below 1.00; thicken walls or upgrade hull materials/structures if exceeded.", formula: "Buckling = Peak Axial + Wind Load / Shell Yield Capacity", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Buckling", + wikipediaUrl: "https://en.wikipedia.org/wiki/Buckling", }, max_q: { title: "Max-Q (Maximum Dynamic Pressure)", @@ -134,252 +194,380 @@ const TERMINOLOGY_GLOSSARY_RAW = { "Peak aerodynamic pressure q = ½ ρ v² experienced in the dense lower atmosphere near Mach 1. Over-speeding or soft walls above stage Max-Q limit cause structural breakup.", formula: "q = ½ · ρ(alt) · v²", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Max Q", + wikipediaUrl: "https://en.wikipedia.org/wiki/Max_Q", }, wall_factor: { title: "Wall Thickness Multiplier", summary: "Scales airframe skin gauge above/below baseline. Thicker walls raise buckling and Max-Q structural limits while adding dry mass.", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Buckling", + wikipediaUrl: "https://en.wikipedia.org/wiki/Buckling", }, airframe_material: { title: "Hull Material", summary: "Alloys and composites trade mass density against yield strength and heat tolerance: Al-Li and Carbon Composite shave dry weight; Stainless Steel resists high thermal loads.", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Launch vehicle", + wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_vehicle", }, interstage: { title: "Interstage Adapter", summary: "Structural shroud/truss bridging two stage diameters and enclosing upper-stage engine bells with pneumatic or pyrotechnic separation latches.", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Multistage rocket", + wikipediaUrl: "https://en.wikipedia.org/wiki/Multistage_rocket", }, grid_fins: { title: "Aerodynamic Fins / Grid Fins", summary: "Tail-mounted fins generating restoring drag force aft of the Center of Gravity, pulling CP downward to stabilize top-heavy or wide-fairing rockets.", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Grid fin", + wikipediaUrl: "https://en.wikipedia.org/wiki/Grid_fin", }, heatshield: { title: "TPS Heatshield Blanket", summary: "Thermal Protection System ablative or tile cladding that raises stage survival temperature against high-speed atmospheric friction and reentry plasma.", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Atmospheric entry", + wikipediaUrl: "https://en.wikipedia.org/wiki/Atmospheric_entry", }, fairing: { title: "Payload Fairing", summary: "Clamshell nose shroud shielding satellites from supersonic airflow, wind shear, and debris. Automatically jettisoned once outside dense atmosphere (~80–120 km).", category: "Structures & Aero", + wikiArticleId: "structures-aero", + wikipediaTitle: "Payload fairing", + wikipediaUrl: "https://en.wikipedia.org/wiki/Payload_fairing", }, las: { title: "Launch Abort System (LAS)", summary: "High-thrust solid escape tower mounted atop crew capsules to yank astronauts clear of pad fires or mid-ascent booster failures.", category: "Structures & Aero", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "Launch escape system", + wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_escape_system", }, apoapsis: { title: "Apoapsis (Ap)", summary: "Highest altitude point along an orbital ellipse. Reaching target apoapsis allows coasting upward before a final circularization burn raises periapsis.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Apsis", + wikipediaUrl: "https://en.wikipedia.org/wiki/Apsis", }, periapsis: { title: "Periapsis (Pe)", summary: "Lowest altitude point along an orbit. Must stay above Earth dense atmosphere (≥ 90 km) for a stable non-decaying parking orbit.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Apsis", + wikipediaUrl: "https://en.wikipedia.org/wiki/Apsis", }, inclination: { title: "Orbital Inclination (i)", summary: "Angle between the orbital plane and Earth equator (0° equatorial, 28.5° KSC, 97.5° polar Sun-synchronous). Higher inclination loses surface rotational launch assist.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Orbital inclination", + wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_inclination", }, mach: { title: "Mach Number", summary: "Airspeed divided by the local speed of sound at current altitude temperature. Transonic shock waves and drag peak sharply between Mach 0.85 and 1.25.", category: "Flight & Orbit", + wikiArticleId: "structures-aero", + wikipediaTitle: "Max Q", + wikipediaUrl: "https://en.wikipedia.org/wiki/Max_Q", }, g_load: { title: "Axial Acceleration (G-Load)", summary: "Total acceleration felt by vehicle structure and crew in multiples of Earth gravity (9.81 m/s²). Crewed capsules enforce strict G-limits as propellant empties.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Orbital spaceflight", + wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_spaceflight", }, heat_flux: { title: "Aerodynamic Heat Flux", summary: "Stagnation heating power (W/cm²) transferred from compressed supersonic air onto the nosecone, drop tanks, and exposed structures.", category: "Flight & Orbit", + wikiArticleId: "structures-aero", + wikipediaTitle: "Spacecraft thermal control", + wikipediaUrl: "https://en.wikipedia.org/wiki/Spacecraft_thermal_control", }, flight_path_angle: { title: "Pitch & Gravity Turn", summary: "Vehicle nose angle relative to the local horizon (90° straight up, 0° horizontal). A crisp pitch-over kick lets gravity bend velocity efficiently toward orbit.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Gravity turn", + wikipediaUrl: "https://en.wikipedia.org/wiki/Gravity_turn", }, meco_seco: { title: "MECO / SECO", summary: "Main Engine Cutoff (first-stage shutdown and separation) and Second/Sustainer Engine Cutoff (upper stage shutdown once target orbit corridor is met).", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Multistage rocket", + wikipediaUrl: "https://en.wikipedia.org/wiki/Multistage_rocket", }, burnout_metrics: { title: "Burnout Velocity & Downrange", summary: "Speed and great-circle distance traveled east/azimuth from the launch pad when orbital insertion or fuel exhaustion occurs.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Low Earth orbit", + wikipediaUrl: "https://en.wikipedia.org/wiki/Low_Earth_orbit", }, dv_remaining: { title: "Remaining Δv Reserve", summary: "Unspent velocity-change impulse remaining after parking orbit insertion, used for circularization or trans-lunar / planetary injection burns.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Hohmann transfer orbit", + wikipediaUrl: "https://en.wikipedia.org/wiki/Hohmann_transfer_orbit", }, park_orbit_quality: { title: "Orbit Insertion Grade", summary: "Precision rating (A+ to Failed) comparing achieved Apoapsis, Periapsis, and Inclination corridor accuracy against mission tolerances.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Orbital spaceflight", + wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_spaceflight", }, max_q_throttle: { title: "Max-Q Throttle Limit", summary: "Automated engine throttle-down near Max-Q (~Mach 0.9–1.5) to prevent aerodynamic dynamic pressure from exceeding airframe yield stress.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Max Q", + wikipediaUrl: "https://en.wikipedia.org/wiki/Max_Q", }, fairing_sep_alt: { title: "Fairing Separation Altitude", summary: "Altitude (km) at which the protective payload shroud jettisons. Jettisoning too low risks aero/micrometeoroid payload damage; too high hauls unnecessary mass.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Payload fairing", + wikipediaUrl: "https://en.wikipedia.org/wiki/Payload_fairing", }, turn_end_alt: { title: "Gravity Turn End Altitude", summary: "Altitude at which guidance finishes flattening toward horizontal (0°). Too low burns in thick air; too high wastes propellant fighting gravity.", category: "Flight & Orbit", + wikiArticleId: "guidance-orbit", + wikipediaTitle: "Gravity turn", + wikipediaUrl: "https://en.wikipedia.org/wiki/Gravity_turn", }, flight_computer: { title: "Flight Computer (GNC)", summary: "Guidance, Navigation & Control avionics processing attitude loops, crossfeed valve sequencing, telemetry encoding, and fault voting.", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "General Mission Analysis Tool", + wikipediaUrl: "https://en.wikipedia.org/wiki/General_Mission_Analysis_Tool", }, rad_hardening: { title: "Radiation Hardening (RAD)", summary: "Chip-level shielding & Triple Modular Redundancy resisting cosmic rays and solar proton storms that trigger Single-Event Upsets (SEUs).", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "Radiation hardening", + wikipediaUrl: "https://en.wikipedia.org/wiki/Radiation_hardening", }, cpu_load: { title: "Peak CPU Load", summary: "Flight computer processor utilization across multi-engine throttling, drop-tank crossfeed logic, comms, and hazard avoidance. Exceeding 92–100% risks guidance freeze.", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "Radiation hardening", + wikipediaUrl: "https://en.wikipedia.org/wiki/Radiation_hardening", }, seu: { title: "Single-Event Upsets (SEUs)", summary: "Transient bit-flips caused by ionizing radiation during solar storms or high-altitude belts. Unshielded avionics suffer cumulative resets if SEUs spike.", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "Single-event upset", + wikipediaUrl: "https://en.wikipedia.org/wiki/Single-event_upset", }, reliability_risk: { title: "Hardware Defect Risk", summary: "Estimated per-flight component malfunction chance derived from part maturity, thermal/Max-Q margins, and manufacturing quality control.", category: "Avionics & Bus", + wikiArticleId: "compliance-qa", + wikipediaTitle: "Technology readiness level", + wikipediaUrl: "https://en.wikipedia.org/wiki/Technology_readiness_level", }, maturity: { title: "Design Maturity", summary: "Flight qualification tier (Concept → Prototype → Flight-Proven). Test flights and successful missions lower hardware failure probability and insurance costs.", category: "Avionics & Bus", + wikiArticleId: "compliance-qa", + wikipediaTitle: "Design review (U.S. government)", + wikipediaUrl: + "https://en.wikipedia.org/wiki/Design_review_(U.S._government)", }, spacecraft_bus: { title: "Spacecraft Bus & Power", summary: "Payload support subsystems: solar arrays or RTGs, batteries, Reaction Control System (RCS), and thermal radiators needed to keep the mission alive in space.", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "Satellite bus", + wikipediaUrl: "https://en.wikipedia.org/wiki/Satellite_bus", }, power_margin: { title: "Electrical Power Margin", summary: "Generated solar/RTG wattage minus continuous bus, heater, and comms transmitter consumption. Negative balance causes battery depletion and brownouts.", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "Radioisotope thermoelectric generator", + wikipediaUrl: + "https://en.wikipedia.org/wiki/Radioisotope_thermoelectric_generator", }, comms_link: { title: "Comms Signal Health", summary: "RF/Optical telemetry link quality balancing antenna dish gain, transmitter band (S/X/Ka/Optical), Earth tracking network tier, and distance attenuation.", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "NASA Deep Space Network", + wikipediaUrl: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network", }, telemetry_freq: { title: "Tracking Station & Link Band", summary: "Ground antenna handover across range stations (Regional vs Global Deep Space Network) and carrier frequency carrying live guidance and health frames.", category: "Avionics & Bus", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "NASA Deep Space Network", + wikipediaUrl: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network", }, crew_eclss: { title: "Crew Capacity & ECLSS", summary: "Astronaut seats aboard the flight and Environmental Control & Life Support System rating governing oxygen regeneration, CO2 scrubbing, and emergency reserve.", category: "Program & Compliance", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "Life-support system", + wikipediaUrl: "https://en.wikipedia.org/wiki/Life-support_system", }, safety_compliance: { title: "Engineering & Safety Compliance", summary: "Pre-launch Range Safety rules (PROP, STR, FLT, SAF, AVN, BUS). Blocking failures halt launch; advisory warnings may require design fixes or a paid Waiver.", category: "Program & Compliance", + wikiArticleId: "compliance-qa", + wikipediaTitle: "Range safety", + wikipediaUrl: "https://en.wikipedia.org/wiki/Range_safety", }, waivers: { title: "Flight Safety Waiver", summary: "Regulatory exception allowing launch despite an advisory compliance flag for an added fee and increased in-flight risk. Critical safety rules cannot be waived.", category: "Program & Compliance", + wikiArticleId: "compliance-qa", + wikipediaTitle: "Range safety", + wikipediaUrl: "https://en.wikipedia.org/wiki/Range_safety", }, rd_tech: { title: "R&D Tech Tree", summary: "Agency research investments unlocking advanced engines, high-capacity external drop tanks, low-mass alloys, and deep-space avionics.", category: "Program & Compliance", + wikiArticleId: "tech-tree-ref", + wikipediaTitle: "Technology readiness level", + wikipediaUrl: "https://en.wikipedia.org/wiki/Technology_readiness_level", }, difficulty: { title: "Simulation Difficulty", summary: "Controls engineering realism: Casual grants forgiving margins; Standard balances physics & finance; Expert enables tank fill ratios, severe wind shear, and radiation SEUs.", category: "Program & Compliance", + wikiArticleId: "getting-started", + wikipediaTitle: "Spaceflight", + wikipediaUrl: "https://en.wikipedia.org/wiki/Spaceflight", }, design_tier: { title: "Builder Architecture Mode", summary: "Guided mode uses structured per-stage slots + drop-tank symmetry controls; Pro Freeform enables direct 3D axis placement, arbitrary radial pods, and custom part stacking.", category: "Program & Compliance", + wikiArticleId: "compliance-qa", + wikipediaTitle: "Launch vehicle", + wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_vehicle", }, contract_tier: { title: "Contract Tier & Payout", summary: "Mission difficulty bracket (T1–T5) setting payload mass, orbital destination, deadline window, completion payout, and penalty upon loss or cancellation.", category: "Program & Compliance", + wikiArticleId: "economy-world", + wikipediaTitle: "Launch window", + wikipediaUrl: "https://en.wikipedia.org/wiki/Launch_window", }, space_weather: { title: "Space Weather & Range Hazards", summary: "Forecast solar wind, proton storms (raising SEU risk), upper atmospheric wind shear (spiking Max-Q loads), and micrometeoroid flux affecting launch timing.", category: "Program & Compliance", + wikiArticleId: "economy-world", + wikipediaTitle: "Space weather", + wikipediaUrl: "https://en.wikipedia.org/wiki/Space_weather", }, launch_cost: { title: "Total Mission Cost", summary: "Total expenditure debited upon launch: stages, engines, core & disposable tanks, avionics, payload integration, range fees, and any active waivers.", category: "Program & Compliance", + wikiArticleId: "economy-world", + wikipediaTitle: "Orbital spaceflight", + wikipediaUrl: "https://en.wikipedia.org/wiki/Orbital_spaceflight", }, ground_network: { title: "Ground Tracking Network", summary: "Earth dish infrastructure tier (Regional vs Global DSN) needed to maintain command uplink downrange and across deep-space distances.", category: "Program & Compliance", + wikiArticleId: "bus-avionics-crew", + wikipediaTitle: "NASA Deep Space Network", + wikipediaUrl: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network", }, } as const satisfies Record; diff --git a/src/client/router.ts b/src/client/router.ts index 4e683f5..5781d0e 100644 --- a/src/client/router.ts +++ b/src/client/router.ts @@ -54,4 +54,7 @@ export function navigate( if (typeof cleanup === "function") { activeCleanup = cleanup; } + window.dispatchEvent( + new CustomEvent("sgywftp:screen-changed", { detail: { screen } }), + ); } diff --git a/src/client/screens/builder/diagnosticsBar.ts b/src/client/screens/builder/diagnosticsBar.ts index b82e787..4ada2b2 100644 --- a/src/client/screens/builder/diagnosticsBar.ts +++ b/src/client/screens/builder/diagnosticsBar.ts @@ -463,63 +463,61 @@ export function renderDiagnosticsSection(ctx: BuilderContext): void { }, headerTitle, ), - ...ctx.latestCoach - .slice(0, 2) - .map((c) => + ...ctx.latestCoach.slice(0, 2).map((c) => + h( + "div", + { + style: { + fontSize: "11px", + marginTop: "4px", + paddingTop: "4px", + borderTop: "1px solid var(--border)", + }, + }, + h( + "div", + { class: "row", style: { gap: "6px" } }, + h( + "span", + { + class: `badge ${c.severity === "critical" ? "err" : c.severity === "warn" ? "warn" : "info"}`, + }, + c.conceptTag ?? c.code, + ), + h("strong", {}, c.title), + ), h( "div", { + class: "dim", + style: { lineHeight: "1.35", marginTop: "2px" }, + }, + c.explanation, + ), + c.formula + ? h( + "div", + { + class: "mono accent", + style: { fontSize: "10px", marginTop: "2px" }, + }, + c.formula, + ) + : null, + h( + "div", + { + class: "mono", style: { - fontSize: "11px", - marginTop: "4px", - paddingTop: "4px", - borderTop: "1px solid var(--border)", + fontSize: "10px", + color: "var(--green)", + marginTop: "2px", }, }, - h( - "div", - { class: "row", style: { gap: "6px" } }, - h( - "span", - { - class: `badge ${c.severity === "critical" ? "err" : c.severity === "warn" ? "warn" : "info"}`, - }, - c.conceptTag ?? c.code, - ), - h("strong", {}, c.title), - ), - h( - "div", - { - class: "dim", - style: { lineHeight: "1.35", marginTop: "2px" }, - }, - c.explanation, - ), - c.formula - ? h( - "div", - { - class: "mono accent", - style: { fontSize: "10px", marginTop: "2px" }, - }, - c.formula, - ) - : null, - h( - "div", - { - class: "mono", - style: { - fontSize: "10px", - color: "var(--green)", - marginTop: "2px", - }, - }, - `Tip: ${c.actionHint}`, - ), + `Tip: ${c.actionHint}`, ), ), + ), ), ); } diff --git a/src/client/screens/dashboard.ts b/src/client/screens/dashboard.ts index f94c00a..64a93ea 100644 --- a/src/client/screens/dashboard.ts +++ b/src/client/screens/dashboard.ts @@ -25,6 +25,11 @@ import { type DashboardSidebarDeps, } from "./dashboard/sidebarCards.js"; import { openTechLabModal } from "./dashboard/techLabModal.js"; +import { + dismissFirstRunTutorialOffer, + shouldShowFirstRunTutorialOffer, + startWalkthrough, +} from "../wiki/walkthrough.js"; export function renderDashboard(root: HTMLElement): () => void { const agency = state.agency; @@ -160,6 +165,14 @@ export function renderDashboard(root: HTMLElement): () => void { { class: "mono dim", style: { fontSize: "11px" } }, state.world?.simDate ?? "Synchronizing ephemeris...", ), + h( + "button", + { + class: "btn xs", + onClick: () => navigate("wiki", { returnTo: "dashboard" }), + }, + "Wiki & Tutorial", + ), h( "button", { class: "btn xs ghost", onClick: () => navigate("mainMenu") }, @@ -268,9 +281,68 @@ export function renderDashboard(root: HTMLElement): () => void { const hazardPanel = createHazardPanel(); const lastSettlementCard = createLastSettlementCard(agency); const navGrid = createNavGrid(deps); + const tutorialOfferBanner = shouldShowFirstRunTutorialOffer(agency) + ? h( + "div", + { + class: "panel", + style: { padding: "12px", borderColor: "var(--sim-accent)" }, + }, + h( + "div", + { class: "col", style: { gap: "8px" } }, + h( + "div", + { class: "spread" }, + h("h3", { class: "accent" }, "New Flight Director?"), + h("span", { class: "badge info" }, "TUTORIAL"), + ), + h( + "p", + { class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } }, + "Open the Flight Wiki for interactive Δv, CG/CP & Gravity Turn labs, or launch the step-by-step Walkthrough.", + ), + h( + "div", + { class: "row", style: { gap: "6px" } }, + h( + "button", + { + class: "btn xs primary", + onClick: () => { + tutorialOfferBanner?.remove(); + startWalkthrough(0); + }, + }, + "Start Walkthrough", + ), + h( + "button", + { + class: "btn xs", + onClick: () => navigate("wiki", { returnTo: "dashboard" }), + }, + "Open Wiki", + ), + h( + "button", + { + class: "btn xs ghost", + onClick: () => { + dismissFirstRunTutorialOffer(); + tutorialOfferBanner?.remove(); + }, + }, + "Dismiss", + ), + ), + ), + ) + : null; if (terminatedBanner) sidebarEl.appendChild(terminatedBanner); if (standdownBanner) sidebarEl.appendChild(standdownBanner); if (bailoutBanner) sidebarEl.appendChild(bailoutBanner); + if (tutorialOfferBanner) sidebarEl.appendChild(tutorialOfferBanner); sidebarEl.append(agencyStatsPanel, contractPanel); if (hazardPanel) sidebarEl.appendChild(hazardPanel); if (lastSettlementCard) sidebarEl.appendChild(lastSettlementCard); diff --git a/src/client/screens/dashboard/sidebarCards.ts b/src/client/screens/dashboard/sidebarCards.ts index 63f2ede..e65aabd 100644 --- a/src/client/screens/dashboard/sidebarCards.ts +++ b/src/client/screens/dashboard/sidebarCards.ts @@ -509,6 +509,14 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement { }, launchBtnLabel, ), + h( + "button", + { + class: "btn full-span ghost", + onClick: () => navigate("wiki", { returnTo: "dashboard" }), + }, + "Flight Wiki & Interactive Tutorial", + ), ); return navGrid; } diff --git a/src/client/screens/launch/orbitPhase.ts b/src/client/screens/launch/orbitPhase.ts index 22c3818..d9234ab 100644 --- a/src/client/screens/launch/orbitPhase.ts +++ b/src/client/screens/launch/orbitPhase.ts @@ -123,7 +123,8 @@ export function enterOrbitPhase(ctx: LaunchContext): void { ? new THREE.MeshBasicMaterial({ color: bodyColors[bodyId] }) : new THREE.MeshStandardMaterial({ map: bodyId === "earth" ? getEarthSurfaceTexture() : null, - color: bodyId === "earth" ? 0xffffff : (bodyColors[bodyId] ?? 0x4f9cf9), + color: + bodyId === "earth" ? 0xffffff : (bodyColors[bodyId] ?? 0x4f9cf9), roughness: 0.72, metalness: 0.08, }), diff --git a/src/client/screens/mainMenu.ts b/src/client/screens/mainMenu.ts index 6ad00eb..872e0c6 100644 --- a/src/client/screens/mainMenu.ts +++ b/src/client/screens/mainMenu.ts @@ -331,6 +331,14 @@ export function renderMainMenu(root: HTMLElement): () => void { ) : null, h("button", { class: "btn", onClick: openSettingsModal }, "Settings"), + h( + "button", + { + class: "btn", + onClick: () => navigate("wiki", { returnTo: "mainMenu" }), + }, + "Flight Wiki", + ), ), h( "div", diff --git a/src/client/screens/wiki.ts b/src/client/screens/wiki.ts new file mode 100644 index 0000000..c6136ec --- /dev/null +++ b/src/client/screens/wiki.ts @@ -0,0 +1,34 @@ +// Wikipedia +import { navigate } from "../router.js"; +import type { WikiScreenParams } from "../state.js"; +import { h } from "../ui.js"; +import { renderWikiWorkspace } from "../wiki/wikiWorkspace.js"; + +export function renderWiki( + root: HTMLElement, + params: WikiScreenParams = {}, +): void { + const returnScreen = + params.returnTo && params.returnTo !== "wiki" + ? params.returnTo + : "dashboard"; + const backLabel = + returnScreen === "mainMenu" + ? "← Main Menu" + : returnScreen === "contracts" + ? "← Contracts" + : returnScreen === "worldMap" + ? "← World Map" + : "← Dashboard"; + + const pageEl = h("div", { class: "screen wiki-page" }); + renderWikiWorkspace(pageEl, { + initialArticleId: params.articleId, + initialGlossaryKey: params.glossaryKey, + initialQuery: params.query, + mode: "page", + backLabel, + onBack: () => navigate(returnScreen), + }); + root.appendChild(pageEl); +} diff --git a/src/client/session.ts b/src/client/session.ts index b3ed9aa..fe5529c 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -133,9 +133,7 @@ function handleLiveEvent(ev: { void refreshWorld(); if (isMine) void refreshMe(); } else if (ev.type === "agency.bankrupt") { - const reason = d.reason - ? ` (${String(d.reason).replace(/_/g, " ")})` - : ""; + const reason = d.reason ? ` (${String(d.reason).replace(/_/g, " ")})` : ""; const msg = `INSOLVENCY ALERT: ${d.agency} declared bankruptcy${reason}.`; pushNotification( msg, diff --git a/src/client/state.ts b/src/client/state.ts index 4df0e53..8d58ece 100644 --- a/src/client/state.ts +++ b/src/client/state.ts @@ -1,4 +1,5 @@ // Client application state, screen route/parameter interfaces, contract lookup, and theme sync. +import type { WikiArticleId } from "./wiki/wikiData.js"; import { syncSimulationTheme } from "./theme.js"; import type { ActiveMission, @@ -23,7 +24,8 @@ export type ScreenName = | "launch" | "debrief" | "contracts" - | "worldMap"; + | "worldMap" + | "wiki"; export interface ModelIndexEntry { file: string; @@ -85,6 +87,13 @@ export interface DebriefScreenParams { isSpectating?: boolean; } +export interface WikiScreenParams { + articleId?: WikiArticleId; + glossaryKey?: string; + query?: string; + returnTo?: ScreenName; +} + export function currentContract(): ContractOffer | MissionTemplate | null { if (!state.agency) return null; if (state.agency.activeContract) return state.agency.activeContract; diff --git a/src/client/three/earthTexture.ts b/src/client/three/earthTexture.ts index 0bc0cd5..0948abf 100644 --- a/src/client/three/earthTexture.ts +++ b/src/client/three/earthTexture.ts @@ -144,7 +144,8 @@ function buildEarthSurface(): HTMLCanvasElement { vg = lerp(vg, 112, rock * 0.7); vb = lerp(vb, 104, rock * 0.7); const snow = - (sstep(0.66, 0.74, elev) + sstep(0.8, 0.9, latN + (elev - 0.5) * 0.25)) * + (sstep(0.66, 0.74, elev) + + sstep(0.8, 0.9, latN + (elev - 0.5) * 0.25)) * land; const iceCap = sstep(0.86, 0.94, latN + (cont - 0.5) * 0.3) * land; r = lerp(vr, 232, Math.min(1, snow * 0.9 + iceCap)); @@ -241,9 +242,10 @@ function compressHighlights( function upgradeTexture(tex: THREE.Texture, url: string, soften = false): void { loader.load(url, (loaded) => { - tex.image = soften && loaded.image instanceof HTMLImageElement - ? compressHighlights(loaded.image) - : loaded.image; + tex.image = + soften && loaded.image instanceof HTMLImageElement + ? compressHighlights(loaded.image) + : loaded.image; tex.needsUpdate = true; }); } diff --git a/src/client/ui/tooltip.ts b/src/client/ui/tooltip.ts index e87cdf4..c1b6cf9 100644 --- a/src/client/ui/tooltip.ts +++ b/src/client/ui/tooltip.ts @@ -15,6 +15,7 @@ export function hideTooltip(): void { } if (tooltipEl) { tooltipEl.hidden = true; + tooltipEl.classList.remove("pinned"); } } @@ -37,14 +38,46 @@ function showTooltipFor(anchor: HTMLElement): void { if (!entry) return; const tip = ensureTooltipEl(); clear(tip); + tip.classList.toggle("pinned", tooltipPinned); tip.append( h("div", { class: "hud-tooltip-cat" }, entry.category), h("div", { class: "hud-tooltip-title" }, entry.title), - h("div", { class: "hud-tooltip-body" }, entry.summary + " -- Your favorite coach, ULTRACAT"), + h( + "div", + { class: "hud-tooltip-body" }, + entry.summary + " -- Your favorite coach, ULTRACAT", + ), ); if (entry.formula) { tip.appendChild(h("div", { class: "hud-tooltip-formula" }, entry.formula)); } + if (tooltipPinned) { + tip.appendChild( + h( + "div", + { class: "hud-tooltip-actions" }, + h( + "button", + { + type: "button", + class: "btn xs primary", + onClick: () => { + hideTooltip(); + window.dispatchEvent( + new CustomEvent("sgywftp:open-wiki", { + detail: { + articleId: entry.wikiArticleId ?? "glossary-index", + glossaryKey: key, + }, + }), + ); + }, + }, + "Open in Wiki →", + ), + ), + ); + } tip.hidden = false; tip.style.left = "0px"; tip.style.top = "0px"; diff --git a/src/client/wiki/interactiveLabs.ts b/src/client/wiki/interactiveLabs.ts new file mode 100644 index 0000000..8a8595a --- /dev/null +++ b/src/client/wiki/interactiveLabs.ts @@ -0,0 +1,1680 @@ +// Interactive physics sandboxes, career checklist, and live catalog directories for the Wikipedia +import { navigate } from "../router.js"; +import { currentContract, state } from "../state.js"; +import { TERMINOLOGY_GLOSSARY, type GlossaryKey } from "../glossary.js"; +import { simulateAscent } from "../../shared/ascent_sim.js"; +import { + airDensity, + speedOfSoundAtAlt, +} from "../../shared/ascent/environment.js"; +import { COMPLIANCE_RULES_META } from "../../shared/compliance.js"; +import { + buildRocket, + createDefaultFlightParams, + createStarterDesign, + DIFFICULTY_PROFILES, + G0, + normalizeDifficulty, + TECH_TREE, + validateDesign, +} from "../../shared/physics.js"; +import type { RocketDesign, RuleCategory } from "../../shared/types.js"; +import { clear, fmtMoney, fmtNum, h, toast } from "../ui.js"; +import { + getManualChecklistState, + isWalkthroughActive, + resetWalkthroughProgress, + setManualChecklistItem, + startWalkthrough, + stopWalkthrough, + WALKTHROUGH_STEPS, +} from "./walkthrough.js"; +import type { WikiArticleId, WikiLabKind } from "./wikiData.js"; + +export interface LabCallbacks { + onOpenArticle: (articleId: WikiArticleId) => void; + onCloseDrawer?: () => void; +} + +let glossaryInstanceSeq = 0; + +function getCanvasPalette() { + const cs = getComputedStyle(document.documentElement); + return { + bg: cs.getPropertyValue("--bg-deep").trim() || "#0b0e14", + panel: cs.getPropertyValue("--bg-elevated").trim() || "#19202e", + border: cs.getPropertyValue("--border").trim() || "#2a3449", + text: cs.getPropertyValue("--text").trim() || "#e2e8f0", + dim: cs.getPropertyValue("--text-dim").trim() || "#94a3b8", + accent: cs.getPropertyValue("--sim-accent").trim() || "#60a5fa", + green: cs.getPropertyValue("--green").trim() || "#34d399", + amber: cs.getPropertyValue("--amber").trim() || "#f59e0b", + red: cs.getPropertyValue("--red").trim() || "#f87171", + violet: cs.getPropertyValue("--violet").trim() || "#a78bfa", + }; +} + +function createLabSlider( + label: string, + min: number, + max: number, + step: number, + initial: number, + formatValue: (v: number) => string, + onChange: (v: number) => void, +): { row: HTMLElement; setValue: (v: number) => void } { + const valEl = h( + "span", + { class: "mono accent", style: { fontSize: "11px" } }, + formatValue(initial), + ); + const input = h("input", { + type: "range", + class: "slider", + min, + max, + step, + value: initial, + onInput: () => { + const v = Number(input.value); + valEl.textContent = formatValue(v); + onChange(v); + }, + }) as HTMLInputElement; + return { + row: h( + "div", + { class: "slot-group" }, + h( + "div", + { class: "spread" }, + h("span", { class: "slot-title" }, label), + valEl, + ), + input, + ), + setValue: (v: number) => { + const clamped = Math.max(min, Math.min(max, v)); + input.value = String(clamped); + valEl.textContent = formatValue(clamped); + }, + }; +} + +function renderMissionChecklist(cb: LabCallbacks): HTMLElement { + const listEl = h("div", { class: "col", style: { gap: "8px" } }); + const headerActions = h("div", { + class: "row", + style: { gap: "8px", flexWrap: "wrap" }, + }); + + function redraw(): void { + clear(listEl); + clear(headerActions); + const agency = state.agency; + const manual = getManualChecklistState(); + const active = isWalkthroughActive(); + + headerActions.append( + h( + "button", + { + class: `btn sm ${active ? "warn" : "primary"}`, + onClick: () => { + if (active) { + stopWalkthrough(); + } else { + startWalkthrough(0); + cb.onCloseDrawer?.(); + } + redraw(); + }, + }, + active + ? "Stop Cross-Screen Walkthrough" + : "Start Interactive Walkthrough", + ), + h( + "button", + { + class: "btn sm ghost", + onClick: () => { + resetWalkthroughProgress(); + redraw(); + }, + }, + "Reset Checklist", + ), + ); + + let completedCount = 0; + WALKTHROUGH_STEPS.forEach((step, idx) => { + const autoDone = step.isComplete(agency); + const checked = autoDone || !!manual[step.id]; + if (checked) completedCount++; + const chk = h("input", { + type: "checkbox", + checked, + onChange: () => { + setManualChecklistItem(step.id, chk.checked); + redraw(); + }, + }) as HTMLInputElement; + listEl.appendChild( + h( + "div", + { class: `wiki-checklist-item ${checked ? "done" : ""}` }, + h( + "div", + { + class: "spread", + style: { gap: "10px", alignItems: "flex-start" }, + }, + h( + "label", + { + class: "row", + style: { + cursor: "pointer", + alignItems: "flex-start", + gap: "8px", + flex: "1", + }, + }, + chk, + h( + "div", + { class: "col", style: { gap: "3px" } }, + h( + "div", + { class: "row", style: { gap: "6px" } }, + h( + "strong", + { class: "mono", style: { fontSize: "12px" } }, + step.title, + ), + autoDone + ? h("span", { class: "badge ok" }, "AUTO-DETECTED") + : checked + ? h("span", { class: "badge info" }, "CHECKED") + : h("span", { class: "badge" }, `STEP ${idx + 1}`), + ), + h( + "p", + { + class: "dim", + style: { fontSize: "11px", lineHeight: "1.45" }, + }, + step.summary, + ), + ), + ), + h( + "div", + { class: "row", style: { gap: "6px", flexShrink: "0" } }, + h( + "button", + { + class: "btn xs ghost", + onClick: () => { + startWalkthrough(idx); + cb.onCloseDrawer?.(); + navigate(step.targetScreen); + }, + }, + `Coach on ${step.targetScreenLabel} →`, + ), + ), + ), + ), + ); + }); + + headerActions.prepend( + h( + "span", + { class: "badge info wiki-progress-pill" }, + `${completedCount}/${WALKTHROUGH_STEPS.length} COMPLETE`, + ), + ); + } + + redraw(); + return h( + "div", + { class: "wiki-lab-card panel" }, + h( + "div", + { + class: "spread", + style: { marginBottom: "10px", flexWrap: "wrap", gap: "8px" }, + }, + h("h3", { class: "accent" }, "Interactive Career Flight Checklist"), + headerActions, + ), + listEl, + ); +} + +function renderDeltaVStagingLab(): HTMLElement { + const sim = { + s1PropT: 180, + s1DryT: 18, + s1Isp: 300, + s1ThrustKN: 3400, + s2PropT: 48, + s2DryT: 5.5, + s2Isp: 348, + s2ThrustKN: 650, + payloadT: 2.5, + useDropTanks: true, + dropPropT: 44, + dropDryT: 3.5, + }; + + const canvas = h("canvas", { + class: "canvas-box", + width: 680, + height: 110, + style: { marginTop: "8px" }, + }) as HTMLCanvasElement; + const statsGrid = h("div", { + class: "stat-grid", + style: { marginTop: "8px" }, + }); + + function computeAndDraw() { + const payloadKg = sim.payloadT * 1000; + const s2DryKg = sim.s2DryT * 1000; + const s2PropKg = sim.s2PropT * 1000; + const s2WetKg = payloadKg + s2DryKg + s2PropKg; + const s2BurnoutKg = payloadKg + s2DryKg; + const dv2 = + s2BurnoutKg > 0 ? sim.s2Isp * G0 * Math.log(s2WetKg / s2BurnoutKg) : 0; + const twr2 = (sim.s2ThrustKN * 1000) / (s2WetKg * G0); + + const dropPropKg = sim.useDropTanks ? sim.dropPropT * 1000 : 0; + const dropDryKg = sim.useDropTanks ? sim.dropDryT * 1000 : 0; + const s1DryKg = sim.s1DryT * 1000; + const s1CorePropKg = sim.s1PropT * 1000; + const s1StartKg = s2WetKg + s1DryKg + s1CorePropKg + dropDryKg + dropPropKg; + + let dv1 = 0; + if (sim.useDropTanks && dropPropKg > 0) { + const mAfterDropBurn = s1StartKg - dropPropKg; + const dv1a = sim.s1Isp * G0 * Math.log(s1StartKg / mAfterDropBurn); + const mCoreStart = mAfterDropBurn - dropDryKg; + const mCoreEnd = mCoreStart - s1CorePropKg; + const dv1b = + mCoreEnd > 0 ? sim.s1Isp * G0 * Math.log(mCoreStart / mCoreEnd) : 0; + dv1 = dv1a + dv1b; + } else { + const m1End = s1StartKg - s1CorePropKg; + dv1 = m1End > 0 ? sim.s1Isp * G0 * Math.log(s1StartKg / m1End) : 0; + } + + const twr1 = (sim.s1ThrustKN * 1000) / (s1StartKg * G0); + const totalDv = dv1 + dv2; + const leoReady = totalDv >= 9300 && twr1 >= 1.22 && twr2 >= 0.45; + const lunarReady = totalDv >= 13800 && twr1 >= 1.22 && twr2 >= 0.45; + + clear(statsGrid); + statsGrid.append( + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Total Stacked Δv"), + h( + "div", + { class: `v ${totalDv >= 9300 ? "good" : "warn"}` }, + `${fmtNum(totalDv)} m/s`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Stage 1 / Stage 2 Δv"), + h("div", { class: "v" }, `${fmtNum(dv1)} + ${fmtNum(dv2)} m/s`), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Liftoff / Upper TWR"), + h( + "div", + { + class: `v ${twr1 >= 1.22 && twr2 >= 0.45 ? "good" : twr1 >= 1.05 ? "warn" : "bad"}`, + }, + `${twr1.toFixed(2)} / ${twr2.toFixed(2)}`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Mission Envelope"), + h( + "div", + { class: `v ${lunarReady ? "good" : leoReady ? "good" : "bad"}` }, + lunarReady + ? "LUNAR / DEEP SPACE" + : leoReady + ? "LEO ORBIT READY" + : "SUBORBITAL / TWR LOW", + ), + ), + ); + + const ctx = canvas.getContext("2d"); + if (!ctx) return; + const pal = getCanvasPalette(); + ctx.fillStyle = pal.bg; + ctx.fillRect(0, 0, canvas.width, canvas.height); + + const maxRef = Math.max(15000, totalDv + 500); + const barX = 16; + const barW = canvas.width - 32; + const barY = 26; + const barH = 30; + ctx.fillStyle = pal.panel; + ctx.fillRect(barX, barY, barW, barH); + + const w1 = Math.min(barW, (dv1 / maxRef) * barW); + const w2 = Math.min(barW - w1, (dv2 / maxRef) * barW); + ctx.fillStyle = pal.accent; + ctx.fillRect(barX, barY, w1, barH); + ctx.fillStyle = pal.green; + ctx.fillRect(barX + w1, barY, w2, barH); + + const drawMarker = (dvMark: number, label: string, color: string) => { + const mx = barX + (dvMark / maxRef) * barW; + ctx.strokeStyle = color; + ctx.lineWidth = 1.5; + ctx.setLineDash([4, 3]); + ctx.beginPath(); + ctx.moveTo(mx, barY - 8); + ctx.lineTo(mx, barY + barH + 10); + ctx.stroke(); + ctx.setLineDash([]); + ctx.fillStyle = color; + ctx.font = "10px monospace"; + ctx.fillText( + label, + Math.min(canvas.width - 90, mx + 4), + barY + barH + 22, + ); + }; + drawMarker(9300, "LEO ~9,300", pal.amber); + drawMarker(13800, "TLI ~13,800", pal.violet); + + ctx.fillStyle = pal.text; + ctx.font = "bold 11px monospace"; + ctx.fillText(`Stage 1: ${Math.round(dv1)} m/s`, barX, 16); + ctx.fillStyle = pal.green; + ctx.fillText(`Stage 2: ${Math.round(dv2)} m/s`, barX + 185, 16); + ctx.fillStyle = pal.dim; + ctx.fillText( + `Liftoff Mass: ${(s1StartKg / 1000).toFixed(1)} t | Payload Fraction: ${((payloadKg / s1StartKg) * 100).toFixed(2)}%`, + barX + 355, + 16, + ); + } + + const s1PropCtrl = createLabSlider( + "Stage 1 Core Propellant", + 20, + 450, + 5, + sim.s1PropT, + (v) => `${v} t`, + (v) => { + sim.s1PropT = v; + computeAndDraw(); + }, + ); + const s1IspCtrl = createLabSlider( + "Stage 1 Effective Isp", + 230, + 400, + 2, + sim.s1Isp, + (v) => `${v} s`, + (v) => { + sim.s1Isp = v; + computeAndDraw(); + }, + ); + const s1ThrustCtrl = createLabSlider( + "Stage 1 Thrust", + 400, + 12000, + 100, + sim.s1ThrustKN, + (v) => `${v} kN`, + (v) => { + sim.s1ThrustKN = v; + computeAndDraw(); + }, + ); + const s2PropCtrl = createLabSlider( + "Stage 2 Propellant", + 5, + 150, + 1, + sim.s2PropT, + (v) => `${v} t`, + (v) => { + sim.s2PropT = v; + computeAndDraw(); + }, + ); + const s2IspCtrl = createLabSlider( + "Stage 2 Vacuum Isp", + 280, + 465, + 2, + sim.s2Isp, + (v) => `${v} s`, + (v) => { + sim.s2Isp = v; + computeAndDraw(); + }, + ); + const payloadCtrl = createLabSlider( + "Payload Mass", + 0.3, + 30, + 0.2, + sim.payloadT, + (v) => `${v.toFixed(1)} t`, + (v) => { + sim.payloadT = v; + computeAndDraw(); + }, + ); + + const dropChk = h("input", { + type: "checkbox", + checked: sim.useDropTanks, + onChange: () => { + sim.useDropTanks = dropChk.checked; + computeAndDraw(); + }, + }) as HTMLInputElement; + + const loadMineBtn = h( + "button", + { + class: "btn xs primary", + disabled: !state.agency?.rocketDesign?.stages?.length, + onClick: () => { + if (!state.agency?.rocketDesign) return; + try { + const asm = buildRocket( + state.agency.rocketDesign, + state.parts, + state.materials, + { + mission: currentContract(), + difficulty: state.agency.difficulty, + }, + ); + const st1 = asm.stages[0]; + const st2 = asm.stages[1] ?? asm.stages[0]; + if (st1) { + sim.s1PropT = Math.max( + 20, + Math.round((st1.corePropellantMass ?? st1.propellantMass) / 1000), + ); + sim.s1DryT = Math.max(1, Number((st1.dryMass / 1000).toFixed(1))); + sim.s1Isp = Math.round( + st1.ispSeaLevelS * 0.35 + st1.ispVacS * 0.65, + ); + sim.s1ThrustKN = Math.max(400, Math.round(st1.thrustN / 1000)); + sim.useDropTanks = (st1.dropTankPropellantMass ?? 0) > 0; + sim.dropPropT = Math.round( + (st1.dropTankPropellantMass ?? 40000) / 1000, + ); + sim.dropDryT = Math.max( + 1, + Number(((st1.dropTankDryMass ?? 3500) / 1000).toFixed(1)), + ); + dropChk.checked = sim.useDropTanks; + } + if (asm.stages[1]) { + sim.s2PropT = Math.max(5, Math.round(st2.propellantMass / 1000)); + sim.s2DryT = Math.max(0.5, Number((st2.dryMass / 1000).toFixed(1))); + sim.s2Isp = Math.round(st2.ispVacS); + sim.s2ThrustKN = Math.max(100, Math.round(st2.thrustN / 1000)); + } + sim.payloadT = Math.max( + 0.3, + Number((asm.totalPayloadMass / 1000).toFixed(1)), + ); + s1PropCtrl.setValue(sim.s1PropT); + s1IspCtrl.setValue(sim.s1Isp); + s1ThrustCtrl.setValue(sim.s1ThrustKN); + s2PropCtrl.setValue(sim.s2PropT); + s2IspCtrl.setValue(sim.s2Isp); + payloadCtrl.setValue(sim.payloadT); + computeAndDraw(); + toast(`Loaded parameters from ${asm.design.name}`, "ok"); + } catch (err) { + toast((err as Error).message, "err"); + } + }, + }, + "Load My Rocket", + ); + + computeAndDraw(); + + return h( + "div", + { class: "wiki-lab-card panel" }, + h( + "div", + { + class: "spread", + style: { marginBottom: "8px", gap: "8px", flexWrap: "wrap" }, + }, + h( + "h3", + { class: "accent" }, + "Interactive Lab: Rocket Equation, Staging & Crossfeed", + ), + h( + "div", + { class: "row", style: { gap: "8px" } }, + h( + "label", + { + class: "row", + style: { cursor: "pointer", fontSize: "11px", gap: "5px" }, + }, + dropChk, + h("span", { class: "mono" }, "Crossfeed Drop Tanks (+44t)"), + ), + loadMineBtn, + ), + ), + h( + "div", + { class: "wiki-lab-grid" }, + s1PropCtrl.row, + s1IspCtrl.row, + s1ThrustCtrl.row, + s2PropCtrl.row, + s2IspCtrl.row, + payloadCtrl.row, + ), + statsGrid, + canvas, + ); +} + +function renderStabilityMaxQLab(): HTMLElement { + const st = { + payloadT: 3.5, + fairingDiaM: 5.2, + hasGridFins: true, + fuelBurnPct: 25, + altitudeKm: 13, + velocityMs: 490, + }; + const canvas = h("canvas", { + class: "canvas-box", + width: 680, + height: 190, + style: { marginTop: "8px" }, + }) as HTMLCanvasElement; + const stats = h("div", { class: "stat-grid", style: { marginTop: "8px" } }); + + function update() { + const heightM = 40; + const maxD = Math.max(3.8, st.fairingDiaM); + const fuelRemainFrac = 1 - st.fuelBurnPct / 100; + const boosterMass = 18 + 160 * fuelRemainFrac; + const upperMass = 6 + 38; + const payloadMass = st.payloadT; + const totalM = boosterMass + upperMass + payloadMass; + const cgY = + (boosterMass * 11 + upperMass * 27 + payloadMass * 36) / + Math.max(1, totalM); + + const fairingAero = st.fairingDiaM * 1.9; + const bodyAero = 3.8 * 3.0; + const finAero = st.hasGridFins ? 11.5 : 0; + const cpY = + (fairingAero * 35 + bodyAero * 17 + finAero * 3.2) / + Math.max(1, fairingAero + bodyAero + finAero); + const marginCal = (cgY - cpY) / maxD; + + const altM = st.altitudeKm * 1000; + const rho = airDensity(altM); + const qPa = 0.5 * rho * st.velocityMs * st.velocityMs; + const mach = st.velocityMs / Math.max(100, speedOfSoundAtAlt(altM)); + + clear(stats); + stats.append( + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "CG / CP Height"), + h("div", { class: "v" }, `${cgY.toFixed(1)}m / ${cpY.toFixed(1)}m`), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Stability Margin (AERO-01)"), + h( + "div", + { + class: `v ${marginCal >= 0.4 ? "good" : marginCal >= 0 ? "warn" : "bad"}`, + }, + `${marginCal >= 0 ? "+" : ""}${marginCal.toFixed(2)} calibers`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Dynamic Pressure (q)"), + h( + "div", + { + class: `v ${qPa <= 38000 ? "good" : qPa <= 52000 ? "warn" : "bad"}`, + }, + `${(qPa / 1000).toFixed(1)} kPa`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Local Airspeed"), + h("div", { class: "v" }, `Mach ${mach.toFixed(2)}`), + ), + ); + + const ctx = canvas.getContext("2d"); + if (!ctx) return; + const pal = getCanvasPalette(); + ctx.fillStyle = pal.bg; + ctx.fillRect(0, 0, canvas.width, canvas.height); + + // Draw horizontal schematic of rocket on top half + const x0 = 70; + const scaleX = 13.5; + const cy = 62; + ctx.strokeStyle = pal.border; + ctx.strokeRect(x0, cy - 18, 25 * scaleX, 36); + ctx.fillStyle = pal.panel; + ctx.fillRect(x0, cy - 18, 25 * scaleX, 36); + ctx.fillRect(x0 + 25 * scaleX, cy - 14, 9 * scaleX, 28); + ctx.strokeRect(x0 + 25 * scaleX, cy - 14, 9 * scaleX, 28); + // Nose fairing + const noseH = st.fairingDiaM * 3.1; + ctx.beginPath(); + ctx.moveTo(x0 + 34 * scaleX, cy - noseH); + ctx.lineTo(x0 + 40 * scaleX, cy); + ctx.lineTo(x0 + 34 * scaleX, cy + noseH); + ctx.closePath(); + ctx.fillStyle = pal.panel; + ctx.fill(); + ctx.strokeStyle = pal.accent; + ctx.stroke(); + + if (st.hasGridFins) { + ctx.fillStyle = pal.green; + ctx.fillRect(x0 + 18, cy - 28, 24, 10); + ctx.fillRect(x0 + 18, cy + 18, 24, 10); + } + + const cgX = x0 + (cgY / heightM) * (40 * scaleX); + const cpX = x0 + (cpY / heightM) * (40 * scaleX); + ctx.fillStyle = pal.amber; + ctx.beginPath(); + ctx.arc(cgX, cy, 6, 0, Math.PI * 2); + ctx.fill(); + ctx.font = "bold 11px monospace"; + ctx.fillText(`CG ${cgY.toFixed(1)}m`, cgX - 24, cy - 24); + + ctx.fillStyle = pal.accent; + ctx.beginPath(); + ctx.arc(cpX, cy, 6, 0, Math.PI * 2); + ctx.fill(); + ctx.fillText(`CP ${cpY.toFixed(1)}m`, cpX - 24, cy + 36); + + ctx.fillStyle = pal.dim; + ctx.font = "10px monospace"; + ctx.fillText("AFT (ENGINE)", 12, cy + 4); + ctx.fillText("NOSE", x0 + 40 * scaleX + 10, cy + 4); + + // Draw dynamic pressure gauge bar at bottom + const qBarX = 20; + const qBarY = 136; + const qBarW = canvas.width - 40; + ctx.fillStyle = pal.panel; + ctx.fillRect(qBarX, qBarY, qBarW, 20); + const qFrac = Math.min(1, qPa / 65000); + ctx.fillStyle = + qPa <= 38000 ? pal.green : qPa <= 52000 ? pal.amber : pal.red; + ctx.fillRect(qBarX, qBarY, qBarW * qFrac, 20); + ctx.strokeStyle = pal.border; + ctx.strokeRect(qBarX, qBarY, qBarW, 20); + ctx.fillStyle = pal.text; + ctx.fillText( + `Dynamic Pressure q = ${(qPa / 1000).toFixed(1)} kPa (Typ. Al-7075 Stage Max-Q Limit ~50–60 kPa)`, + qBarX, + 174, + ); + } + + const finsChk = h("input", { + type: "checkbox", + checked: st.hasGridFins, + onChange: () => { + st.hasGridFins = finsChk.checked; + update(); + }, + }) as HTMLInputElement; + + const pCtrl = createLabSlider( + "Payload Mass", + 0.5, + 25, + 0.5, + st.payloadT, + (v) => `${v.toFixed(1)} t`, + (v) => { + st.payloadT = v; + update(); + }, + ); + const fCtrl = createLabSlider( + "Fairing Diameter", + 2.8, + 11.5, + 0.5, + st.fairingDiaM, + (v) => `${v.toFixed(1)} m`, + (v) => { + st.fairingDiaM = v; + update(); + }, + ); + const burnCtrl = createLabSlider( + "Stage 1 Fuel Burned", + 0, + 90, + 5, + st.fuelBurnPct, + (v) => `${v}%`, + (v) => { + st.fuelBurnPct = v; + update(); + }, + ); + const altCtrl = createLabSlider( + "Altitude", + 0, + 60, + 1, + st.altitudeKm, + (v) => `${v} km`, + (v) => { + st.altitudeKm = v; + update(); + }, + ); + const velCtrl = createLabSlider( + "Airspeed", + 50, + 2400, + 25, + st.velocityMs, + (v) => `${v} m/s`, + (v) => { + st.velocityMs = v; + update(); + }, + ); + + update(); + return h( + "div", + { class: "wiki-lab-card panel" }, + h( + "div", + { + class: "spread", + style: { marginBottom: "8px", gap: "8px", flexWrap: "wrap" }, + }, + h( + "h3", + { class: "accent" }, + "Interactive Lab: CG vs CP Stability & Max-Q", + ), + h( + "label", + { + class: "row", + style: { cursor: "pointer", fontSize: "11px", gap: "5px" }, + }, + finsChk, + h("span", { class: "mono" }, "Titanium Aft Grid Fins"), + ), + ), + h( + "div", + { class: "wiki-lab-grid" }, + pCtrl.row, + fCtrl.row, + burnCtrl.row, + altCtrl.row, + velCtrl.row, + ), + stats, + canvas, + ); +} + +function renderGravityTurnLab(): HTMLElement { + const baseDesign: RocketDesign = state.agency?.rocketDesign?.stages?.length + ? structuredClone(state.agency.rocketDesign) + : createStarterDesign(currentContract(), "explorer"); + const fp = { + ...createDefaultFlightParams(currentContract()), + ...baseDesign.flightParams, + }; + + const canvas = h("canvas", { + class: "canvas-box", + width: 680, + height: 195, + style: { marginTop: "8px" }, + }) as HTMLCanvasElement; + const stats = h("div", { class: "stat-grid", style: { marginTop: "8px" } }); + const outcomeBanner = h("div", { + class: "mono", + style: { fontSize: "11px", marginTop: "6px" }, + }); + + function runAndDraw() { + if (!state.parts.length || !state.materials.length) { + outcomeBanner.textContent = "Catalogs still loading..."; + return; + } + const simDesign: RocketDesign = { + ...baseDesign, + flightParams: { ...fp }, + }; + const res = simulateAscent(simDesign, state.parts, state.materials, { + mission: currentContract(), + difficulty: state.agency?.difficulty ?? "explorer", + weather: state.world?.weather ?? "nominal", + unlockedTechs: state.agency?.unlockedTechs ?? [], + rollAnomalies: false, + sampleEvery: 2.0, + }); + + clear(stats); + stats.append( + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Final Pe × Ap"), + h( + "div", + { class: `v ${res.success ? "good" : "bad"}` }, + `${Math.round(res.periapsis / 1000)} × ${Math.round(res.apoapsis / 1000)} km`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Peak Max-Q / G"), + h( + "div", + { class: "v" }, + `${(res.maxQ / 1000).toFixed(1)} kPa • ${res.peakGLoad.toFixed(1)} G`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Burnout Speed"), + h("div", { class: "v" }, `${fmtNum(res.burnoutVelocity)} m/s`), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Reserve Δv"), + h( + "div", + { class: `v ${res.dvRemaining >= 0 ? "good" : "warn"}` }, + `${fmtNum(res.dvRemaining)} m/s`, + ), + ), + ); + outcomeBanner.className = `mono ${res.success ? "green" : "red"}`; + outcomeBanner.textContent = res.success + ? `Nominal ascent profile using ${simDesign.name} (${res.orbitGrade?.toUpperCase() ?? "ORBIT"}).` + : `Failure (${res.failureReason ?? "anomaly"}): ${res.failureDetail}`; + + const ctx = canvas.getContext("2d"); + if (!ctx) return; + const pal = getCanvasPalette(); + ctx.fillStyle = pal.bg; + ctx.fillRect(0, 0, canvas.width, canvas.height); + + const pts = res.telemetry; + if (!pts.length) return; + const padL = 44; + const padR = 16; + const padT = 18; + const padB = 26; + const w = canvas.width - padL - padR; + const hPx = canvas.height - padT - padB; + const maxDr = Math.max(400_000, ...pts.map((p) => p.downrange)); + const maxAlt = Math.max(220_000, ...pts.map((p) => p.altitude)); + + // Grid lines + ctx.strokeStyle = pal.border; + ctx.lineWidth = 1; + for (let i = 0; i <= 4; i++) { + const y = padT + (hPx * i) / 4; + ctx.beginPath(); + ctx.moveTo(padL, y); + ctx.lineTo(padL + w, y); + ctx.stroke(); + const altLbl = Math.round(((4 - i) / 4) * (maxAlt / 1000)); + ctx.fillStyle = pal.dim; + ctx.font = "9px monospace"; + ctx.fillText(`${altLbl}km`, 4, y + 3); + } + + // Karman 100km reference + if (maxAlt >= 100_000) { + const y100 = padT + hPx * (1 - 100_000 / maxAlt); + ctx.strokeStyle = pal.amber; + ctx.setLineDash([4, 4]); + ctx.beginPath(); + ctx.moveTo(padL, y100); + ctx.lineTo(padL + w, y100); + ctx.stroke(); + ctx.setLineDash([]); + ctx.fillStyle = pal.amber; + ctx.fillText("Kármán 100 km", padL + 6, y100 - 4); + } + + ctx.strokeStyle = res.success ? pal.green : pal.red; + ctx.lineWidth = 2.2; + ctx.beginPath(); + pts.forEach((p, idx) => { + const x = padL + (p.downrange / maxDr) * w; + const y = padT + hPx * (1 - Math.max(0, p.altitude) / maxAlt); + if (idx === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + }); + ctx.stroke(); + + ctx.fillStyle = pal.dim; + ctx.font = "9px monospace"; + ctx.fillText( + `Downrange: 0 → ${Math.round(maxDr / 1000)} km`, + padL, + canvas.height - 6, + ); + } + + let simTimer: number | undefined; + const scheduleRun = () => { + window.clearTimeout(simTimer); + simTimer = window.setTimeout(runAndDraw, 120); + }; + + const startVelCtrl = createLabSlider( + "Turn Start Vel", + 35, + 160, + 5, + fp.gravityTurnStartVel, + (v) => `${v} m/s`, + (v) => { + fp.gravityTurnStartVel = v; + scheduleRun(); + }, + ); + const kickCtrl = createLabSlider( + "Pitch-Over Kick", + 3, + 18, + 0.5, + fp.pitchOverDeg, + (v) => `${v}°`, + (v) => { + fp.pitchOverDeg = v; + scheduleRun(); + }, + ); + const endAltCtrl = createLabSlider( + "Level-Off Alt", + 65, + 130, + 1, + fp.turnEndAltKm, + (v) => `${v} km`, + (v) => { + fp.turnEndAltKm = v; + scheduleRun(); + }, + ); + const throttleCtrl = createLabSlider( + "Max-Q Throttle", + 0.5, + 1.0, + 0.02, + fp.maxQThrottle, + (v) => `${Math.round(v * 100)}%`, + (v) => { + fp.maxQThrottle = v; + scheduleRun(); + }, + ); + + const applyPreset = ( + vel: number, + kick: number, + altKm: number, + throttle: number, + ) => { + fp.gravityTurnStartVel = vel; + fp.pitchOverDeg = kick; + fp.turnEndAltKm = altKm; + fp.maxQThrottle = throttle; + startVelCtrl.setValue(vel); + kickCtrl.setValue(kick); + endAltCtrl.setValue(altKm); + throttleCtrl.setValue(throttle); + scheduleRun(); + }; + + runAndDraw(); + return h( + "div", + { class: "wiki-lab-card panel" }, + h( + "div", + { + class: "spread", + style: { marginBottom: "8px", gap: "8px", flexWrap: "wrap" }, + }, + h( + "h3", + { class: "accent" }, + "Interactive Lab: Real Ascent & Gravity Turn Simulator", + ), + h( + "div", + { class: "row", style: { gap: "6px", flexWrap: "wrap" } }, + h( + "button", + { + class: "btn xs primary", + onClick: () => applyPreset(75, 8, 92, 0.72), + }, + "Nominal LEO", + ), + h( + "button", + { + class: "btn xs ghost", + onClick: () => applyPreset(140, 3.5, 125, 1.0), + }, + "Too Steep", + ), + h( + "button", + { + class: "btn xs ghost", + onClick: () => applyPreset(40, 17, 68, 1.0), + }, + "Too Shallow", + ), + ), + ), + h( + "div", + { class: "wiki-lab-grid" }, + startVelCtrl.row, + kickCtrl.row, + endAltCtrl.row, + throttleCtrl.row, + ), + stats, + outcomeBanner, + canvas, + ); +} + +function renderComplianceDirectory(): HTMLElement { + const cats: Array<{ id: "all" | RuleCategory; label: string }> = [ + { id: "all", label: `All (${COMPLIANCE_RULES_META.length})` }, + { id: "propulsion", label: "Propulsion" }, + { id: "structures", label: "Structures" }, + { id: "aerodynamics", label: "Aero" }, + { id: "thermal", label: "Thermal" }, + { id: "payload", label: "Payload & Bus" }, + { id: "crew", label: "Crew" }, + { id: "orbital", label: "Orbital" }, + ]; + let activeCat: "all" | RuleCategory = "all"; + const filterRow = h("div", { + class: "row", + style: { gap: "6px", flexWrap: "wrap" }, + }); + const listEl = h("div", { + class: "col", + style: { gap: "6px", marginTop: "8px" }, + }); + + function redraw() { + clear(filterRow); + for (const c of cats) { + filterRow.appendChild( + h( + "button", + { + class: `btn xs ${activeCat === c.id ? "selected" : "ghost"}`, + onClick: () => { + activeCat = c.id; + redraw(); + }, + }, + c.label, + ), + ); + } + clear(listEl); + const items = + activeCat === "all" + ? COMPLIANCE_RULES_META + : COMPLIANCE_RULES_META.filter((r) => r.category === activeCat); + for (const r of items) { + listEl.appendChild( + h( + "div", + { class: "rule-item" }, + h( + "div", + { class: "spread", style: { gap: "8px" } }, + h( + "div", + { class: "row", style: { gap: "6px" } }, + h("span", { class: "badge info" }, r.code), + h("strong", {}, r.title), + ), + r.severity === "mandatory" + ? h("span", { class: "badge err" }, "MANDATORY") + : r.dynamicSeverity + ? h( + "span", + { + class: "badge warn", + title: + "Base severity is waiverable, but escalates to mandatory based on mission & vehicle context", + }, + "CONTEXT-DEPENDENT", + ) + : h( + "span", + { class: "badge warn" }, + `WAIVERABLE (${fmtMoney(r.waiverCost)} / +${r.riskPenaltyPct}% RISK)`, + ), + ), + h( + "div", + { class: "dim", style: { fontSize: "11px" } }, + r.description, + ), + ), + ); + } + } + + redraw(); + return h( + "div", + { class: "wiki-lab-card panel" }, + h( + "h3", + { class: "accent", style: { marginBottom: "8px" } }, + "Live NASA CML / TRL Rules Directory", + ), + filterRow, + listEl, + ); +} + +function renderGlossaryDirectory( + highlightKey?: GlossaryKey | string, +): HTMLElement { + const instanceId = `gloss-${++glossaryInstanceSeq}`; + const categories = [ + "All", + "Propulsion", + "Structures & Aero", + "Flight & Orbit", + "Avionics & Bus", + "Program & Compliance", + ] as const; + let activeCat: string = "All"; + let localFilter = ""; + const filterRow = h("div", { + class: "row", + style: { gap: "6px", flexWrap: "wrap" }, + }); + const searchInput = h("input", { + class: "input", + placeholder: "Filter glossary terms & formulas...", + onInput: () => { + localFilter = searchInput.value.trim().toLowerCase(); + redrawList(); + }, + }) as HTMLInputElement; + const listEl = h("div", { + class: "col", + style: { gap: "8px", marginTop: "8px" }, + }); + + function redrawFilters() { + clear(filterRow); + for (const cat of categories) { + filterRow.appendChild( + h( + "button", + { + class: `btn xs ${activeCat === cat ? "selected" : "ghost"}`, + onClick: () => { + activeCat = cat; + redrawFilters(); + redrawList(); + }, + }, + cat, + ), + ); + } + } + + function redrawList() { + clear(listEl); + const entries = Object.entries(TERMINOLOGY_GLOSSARY) as Array< + [GlossaryKey, (typeof TERMINOLOGY_GLOSSARY)[GlossaryKey]] + >; + const filtered = entries.filter(([, e]) => { + if (activeCat !== "All" && e.category !== activeCat) return false; + if (!localFilter) return true; + return ( + e.title.toLowerCase().includes(localFilter) || + e.summary.toLowerCase().includes(localFilter) || + (e.formula?.toLowerCase().includes(localFilter) ?? false) + ); + }); + for (const [key, entry] of filtered) { + const isHighlighted = highlightKey === key; + const card = h( + "div", + { + class: `wiki-glossary-card panel ${isHighlighted ? "highlighted" : ""}`, + id: `${instanceId}-glossary-${key}`, + }, + h( + "div", + { class: "spread", style: { gap: "8px", marginBottom: "4px" } }, + h( + "strong", + { class: "mono accent", style: { fontSize: "12px" } }, + entry.title, + ), + h("span", { class: "badge info" }, entry.category), + ), + h( + "p", + { class: "dim", style: { fontSize: "12px", lineHeight: "1.45" } }, + entry.summary, + ), + entry.formula + ? h("div", { class: "wiki-formula" }, entry.formula) + : null, + entry.wikipediaUrl + ? h( + "div", + { class: "row", style: { marginTop: "6px" } }, + h( + "a", + { + class: "btn xs ghost wiki-ext-link", + href: entry.wikipediaUrl, + target: "_blank", + rel: "noopener noreferrer", + }, + `Wikipedia: ${entry.wikipediaTitle ?? entry.title} ↗`, + ), + ) + : null, + ); + listEl.appendChild(card); + } + if (highlightKey) { + window.setTimeout(() => { + document + .getElementById(`${instanceId}-glossary-${highlightKey}`) + ?.scrollIntoView({ + behavior: "smooth", + block: "center", + }); + }, 60); + } + } + + redrawFilters(); + redrawList(); + + return h( + "div", + { class: "wiki-lab-card panel" }, + h("div", { class: "col", style: { gap: "8px" } }, searchInput, filterRow), + listEl, + ); +} + +function renderTechAndDifficultyDirectory(): HTMLElement { + const unlocked = new Set(state.agency?.unlockedTechs ?? ["starter"]); + const myDiff = state.agency + ? normalizeDifficulty(state.agency.difficulty) + : null; + + return h( + "div", + { class: "col", style: { gap: "12px" } }, + h( + "div", + { class: "wiki-lab-card panel" }, + h( + "h3", + { class: "accent", style: { marginBottom: "8px" } }, + "Difficulty Profiles Matrix", + ), + h( + "div", + { class: "col", style: { gap: "6px" } }, + ...Object.values(DIFFICULTY_PROFILES).map((p) => + h( + "div", + { class: `rule-item ${myDiff === p.id ? "pass" : ""}` }, + h( + "div", + { class: "spread" }, + h("strong", { class: "mono" }, `${p.label} (${p.audience})`), + myDiff === p.id + ? h("span", { class: "badge ok" }, "YOUR TIER") + : h( + "span", + { class: "badge info" }, + `±${p.orbitTolPct}% Ap / ±${p.incTolDeg}° Inc`, + ), + ), + h("div", { class: "dim", style: { fontSize: "11px" } }, p.tagline), + h( + "div", + { class: "mono faint", style: { fontSize: "10px" } }, + `Start ${fmtMoney(p.startingFunds)} • Max Bailouts ${p.maxBailouts} • Facility Upkeep ${fmtMoney(p.facilityCostPerPeriod)} • Defect Mult ${p.partDefectMult}×`, + ), + ), + ), + ), + ), + h( + "div", + { class: "wiki-lab-card panel" }, + h( + "h3", + { class: "accent", style: { marginBottom: "8px" } }, + `R&D Tech Tree Nodes (${TECH_TREE.length})`, + ), + h( + "div", + { class: "col", style: { gap: "6px" } }, + ...TECH_TREE.map((node) => + h( + "div", + { class: `rule-item ${unlocked.has(node.id) ? "pass" : ""}` }, + h( + "div", + { class: "spread" }, + h("strong", { class: "mono" }, node.name), + unlocked.has(node.id) + ? h("span", { class: "badge ok" }, "UNLOCKED") + : h( + "span", + { class: "badge warn" }, + `${fmtMoney(node.cost)} • ${node.minReputation} RP`, + ), + ), + h( + "div", + { class: "dim", style: { fontSize: "11px" } }, + node.description, + ), + h( + "div", + { class: "mono faint", style: { fontSize: "10px" } }, + `Category: ${node.category.toUpperCase()} • Unlocks ${node.unlocksIds.length} items (${node.unlocksIds.slice(0, 5).join(", ")}${node.unlocksIds.length > 5 ? ", ..." : ""})`, + ), + ), + ), + ), + ), + ); +} + +function renderVehicleInspector(cb: LabCallbacks): HTMLElement { + const agency = state.agency; + const contract = currentContract(); + if (!agency || !agency.rocketDesign?.stages?.length) { + return h( + "div", + { class: "wiki-lab-card panel" }, + h( + "h3", + { class: "accent", style: { marginBottom: "6px" } }, + "No Active Agency Vehicle Found", + ), + h( + "p", + { class: "dim", style: { fontSize: "12px", marginBottom: "10px" } }, + agency + ? "You have not saved a rocket design yet. Open Rocket Builder to generate or customize a launcher." + : "Sign into an agency to inspect your saved launch vehicle and live compliance status here.", + ), + agency + ? h( + "button", + { + class: "btn sm primary", + onClick: () => { + cb.onCloseDrawer?.(); + navigate("builder"); + }, + }, + "Open Rocket Builder →", + ) + : null, + ); + } + + const val = validateDesign( + agency.rocketDesign, + state.parts, + state.materials, + { + mission: contract, + simTime: state.world?.simTime ?? 0, + weather: state.world?.weather ?? "nominal", + activeHazards: state.world?.activeHazards ?? [], + unlockedTechs: agency.unlockedTechs ?? [], + difficulty: agency.difficulty, + crewedSeats: agency.crewConfig?.crewSize ?? 0, + eclssLevel: agency.crewConfig?.lifeSupport ?? 0, + }, + ); + + const codeToArticle = (code: string): WikiArticleId => { + if (code.startsWith("PROP")) return "propulsion-staging"; + if ( + code.startsWith("STR") || + code.startsWith("AERO") || + code.startsWith("THRM") + ) + return "structures-aero"; + if (code.startsWith("ORB")) return "guidance-orbit"; + if ( + code.startsWith("CREW") || + code.startsWith("AVN") || + code.startsWith("PAY") + ) + return "bus-avionics-crew"; + if (code.startsWith("ENV")) return "economy-world"; + return "compliance-qa"; + }; + + const failingRules = val.compliance.rules.filter((r) => !r.passed); + + return h( + "div", + { class: "wiki-lab-card panel col", style: { gap: "10px" } }, + h( + "div", + { class: "spread" }, + h( + "h3", + { class: "accent" }, + `${agency.rocketDesign.name} — Live Inspection`, + ), + h( + "span", + { class: `badge ${val.valid ? "ok" : "warn"}` }, + val.valid ? "COMPLIANT" : `${val.errors.length} BLOCKERS`, + ), + ), + h( + "div", + { class: "stat-grid" }, + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Total Δv / Required"), + h( + "div", + { class: `v ${val.dvMargin >= 0 ? "good" : "bad"}` }, + `${fmtNum(val.totalDv)} / ${fmtNum(val.effectiveRequiredDv)} m/s`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Liftoff TWR"), + h( + "div", + { + class: `v ${val.twr >= 1.22 ? "good" : val.twr >= 1.05 ? "warn" : "bad"}`, + }, + val.twr.toFixed(2), + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Stability Margin"), + h( + "div", + { + class: `v ${(val.assembly?.stabilityMarginCalibers ?? 0) >= 0.4 ? "good" : "warn"}`, + }, + `${(val.assembly?.stabilityMarginCalibers ?? 0).toFixed(2)} cal`, + ), + ), + h( + "div", + { class: "stat-box" }, + h("div", { class: "k" }, "Maturity / Cost"), + h( + "div", + { class: "v" }, + `${agency.rocketDesign.maturity.toUpperCase()} • ${fmtMoney(val.totalMissionCost)}`, + ), + ), + ), + failingRules.length + ? h( + "div", + { class: "col", style: { gap: "6px" } }, + h( + "strong", + { class: "mono amber", style: { fontSize: "11px" } }, + "Active Engineering Findings & Matching Guides:", + ), + ...failingRules.map((r) => + h( + "div", + { class: `rule-item ${r.waived ? "waived" : "fail"}` }, + h( + "div", + { class: "spread", style: { gap: "8px" } }, + h("span", {}, `[${r.code}] ${r.title}: ${r.detail}`), + h( + "button", + { + class: "btn xs ghost", + onClick: () => cb.onOpenArticle(codeToArticle(r.code)), + }, + "Learn Fix →", + ), + ), + ), + ), + ) + : h( + "p", + { class: "green mono", style: { fontSize: "12px" } }, + "All compliance rules pass! Verify FLIGHT-READY maturity and launch profile.", + ), + ); +} + +export function renderWikiLab( + kind: WikiLabKind | undefined, + cb: LabCallbacks, + highlightGlossaryKey?: string, +): HTMLElement | null { + switch (kind) { + case "checklist": + return renderMissionChecklist(cb); + case "dv-staging": + return renderDeltaVStagingLab(); + case "stability-maxq": + return renderStabilityMaxQLab(); + case "gravity-turn": + return renderGravityTurnLab(); + case "compliance-directory": + return renderComplianceDirectory(); + case "glossary-directory": + return renderGlossaryDirectory(highlightGlossaryKey); + case "tech-difficulty-directory": + return renderTechAndDifficultyDirectory(); + case "vehicle-inspector": + return renderVehicleInspector(cb); + default: + return null; + } +} diff --git a/src/client/wiki/walkthrough.ts b/src/client/wiki/walkthrough.ts new file mode 100644 index 0000000..1110f88 --- /dev/null +++ b/src/client/wiki/walkthrough.ts @@ -0,0 +1,490 @@ +// Cross-screen Guided Walkthrough coach bar and career milestone detector. +import { navigate } from "../router.js"; +import { + currentContract, + getCurrentScreen, + type ScreenName, + state, +} from "../state.js"; +import { + getDifficultyProfile, + TECH_TREE, + validateDesign, +} from "../../shared/physics.js"; +import type { AgencyState } from "../../shared/types.js"; +import { clear, h } from "../ui.js"; +import type { WikiArticleId } from "./wikiData.js"; + +const STORAGE_KEY = "spacegaem_wiki_walkthrough_v1"; + +interface WalkthroughStorage { + active: boolean; + stepIndex: number; + collapsed: boolean; + dismissedOffer: boolean; + manualChecks: Record; +} + +export interface WalkthroughStepDef { + id: string; + title: string; + targetScreen: ScreenName; + targetScreenLabel: string; + wikiArticleId: WikiArticleId; + summary: string; + actionHint: (screen: ScreenName, agency: AgencyState | null) => string; + isComplete: (agency: AgencyState | null) => boolean; +} + +function loadState(): WalkthroughStorage { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (raw) { + const parsed = JSON.parse(raw) as Partial; + return { + active: !!parsed.active, + stepIndex: Math.max( + 0, + Math.min(WALKTHROUGH_STEPS.length - 1, Number(parsed.stepIndex) || 0), + ), + collapsed: !!parsed.collapsed, + dismissedOffer: !!parsed.dismissedOffer, + manualChecks: + parsed.manualChecks && typeof parsed.manualChecks === "object" + ? parsed.manualChecks + : {}, + }; + } + } catch {} + return { + active: false, + stepIndex: 0, + collapsed: false, + dismissedOffer: false, + manualChecks: {}, + }; +} + +function saveState(st: WalkthroughStorage): void { + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(st)); + } catch {} +} + +function evaluateAgencyValidation(agency: AgencyState | null) { + if (!agency?.rocketDesign?.stages?.length || !state.parts.length) return null; + try { + return validateDesign(agency.rocketDesign, state.parts, state.materials, { + mission: currentContract(), + simTime: state.world?.simTime ?? 0, + weather: state.world?.weather ?? "nominal", + activeHazards: state.world?.activeHazards ?? [], + unlockedTechs: agency.unlockedTechs ?? [], + difficulty: agency.difficulty, + crewedSeats: agency.crewConfig?.crewSize ?? 0, + eclssLevel: agency.crewConfig?.lifeSupport ?? 0, + }); + } catch { + return null; + } +} + +export const WALKTHROUGH_STEPS: WalkthroughStepDef[] = [ + { + id: "contract", + title: "1. Sign an Active Mission Contract", + targetScreen: "contracts", + targetScreenLabel: "Contracts & Rank", + wikiArticleId: "getting-started", + summary: + "Every launch starts with a sponsor contract providing a 35% advance payout and defining payload mass, target orbit, and required Δv.", + actionHint: (screen, agency) => { + if (!agency) + return "Sign in or register an agency to accept a mission contract."; + if (currentContract()) { + return "Active contract signed! Advance to Step 2 or open Rocket Builder."; + } + return screen === "contracts" + ? "Pick a Tier-1 Low Earth Orbit offer on the left and click 'Sign Contract'." + : "Click 'Go to Contracts & Rank' to browse and sign an inaugural Tier-1 contract."; + }, + isComplete: () => !!currentContract(), + }, + { + id: "propulsion", + title: "2. Design Rocket & Meet Δv / TWR", + targetScreen: "builder", + targetScreenLabel: "Rocket Builder", + wikiArticleId: "propulsion-staging", + summary: + "Stack stages, compatible propellant tanks, and engines so total Δv meets the mission requirement and Liftoff TWR ≥ 1.22.", + actionHint: (screen, agency) => { + const val = evaluateAgencyValidation(agency); + if (val && val.dvMargin >= 0 && val.twr >= 1.22) { + return "Propulsion budget & TWR look solid! Save your design and move to Step 3."; + } + if (screen === "builder") { + return "Check the top summary pills & Diagnostics bar: pair matching engines/tanks, add a 2nd stage or drop tanks for Δv, and click 'Save Design'."; + } + return "Open Rocket Builder to assemble stages and verify Δv margin and Liftoff TWR."; + }, + isComplete: (agency) => { + const val = evaluateAgencyValidation(agency); + return !!val && val.dvMargin >= 0 && val.twr >= 1.05; + }, + }, + { + id: "compliance", + title: "3. Certify Compliance & Reach Flight-Ready", + targetScreen: "builder", + targetScreenLabel: "Rocket Builder", + wikiArticleId: "compliance-qa", + summary: + "Check CG/CP stability (add Grid Fins if < 0.40 calibers), ensure Fairing & Flight Computer fit, resolve NASA CML/TRL rules, and advance Maturity to FLIGHT-READY.", + actionHint: (screen, agency) => { + const val = evaluateAgencyValidation(agency); + const prof = getDifficultyProfile(agency?.difficulty); + const ready = + !!val?.valid && + (agency?.rocketDesign?.maturity === "flight-ready" || + prof.id === "sandbox"); + if (ready) { + return "Vehicle is certified FLIGHT-READY! Save Design and proceed to Param Config."; + } + if (screen === "builder") { + return "Open the 'NASA CML / TRL' tab to clear blockers, toggle 'CG / CP' in the viewport, advance Maturity to FLIGHT-READY, and click 'Save Design'."; + } + return "Open Rocket Builder → 'NASA CML / TRL' tab to resolve blockers and advance Maturity."; + }, + isComplete: (agency) => { + const val = evaluateAgencyValidation(agency); + const prof = getDifficultyProfile(agency?.difficulty); + return ( + !!val?.valid && + (agency?.rocketDesign?.maturity === "flight-ready" || + prof.id === "sandbox") + ); + }, + }, + { + id: "guidance", + title: "4. Tune Gravity Turn & Run Pre-Launch QA", + targetScreen: "config", + targetScreenLabel: "Param Config", + wikiArticleId: "guidance-orbit", + summary: + "Preview your 2D ascent trajectory, use 'Auto-Tune Flight Computer' if needed, verify Launch Window & Weather Hazards, and save your flight profile.", + actionHint: (screen) => { + if (screen === "config") { + return "Review the Ascent & Orbit preview. Try 'Auto-Tune Flight Computer', check Pre-Launch QA (Static Fire / Insurance), and click 'Save Profile' or 'Save & Proceed to Pad →'."; + } + return "Open 'Param Config' from the Dashboard (or Builder footer) to tune your Gravity Turn and save your launch profile."; + }, + isComplete: (agency) => + !!agency?.rocketDesign?.flightParams && + (agency.missionsCompleted > 0 || agency.missionsFailed > 0), + }, + { + id: "launch", + title: "5. Launch Mission & Review Debrief", + targetScreen: "dashboard", + targetScreenLabel: "Dashboard", + wikiArticleId: "guidance-orbit", + summary: + "Trigger 'Launch Mission' from the Dashboard (or Param Config), monitor staging/Max-Q/SECO in 3D, and study your After-Action Report.", + actionHint: (screen, agency) => { + if ( + (agency?.missionsCompleted ?? 0) + (agency?.missionsFailed ?? 0) > + 0 + ) { + return "First flight logged! Review your Debrief or proceed to Step 6."; + } + if (screen === "launch") { + return "Monitor Altitude, Dynamic Pressure (Max-Q), G-Load, and Flight Events through MECO/SECO."; + } + return "Head to Dashboard and click the highlighted 'Launch Mission' button (or launch from Param Config) when FLIGHT-READY."; + }, + isComplete: (agency) => + (agency?.missionsCompleted ?? 0) + (agency?.missionsFailed ?? 0) > 0, + }, + { + id: "rd", + title: "6. Invest in R&D Tech Lab", + targetScreen: "dashboard", + targetScreenLabel: "Dashboard", + wikiArticleId: "tech-tree-ref", + summary: + "Spend earned Reputation (RP) and treasury cash in the R&D Tech Lab to unlock Hydrolox, Methalox, Composites, and Tier-2/3 Telemetry & GMAT.", + actionHint: () => + "On Dashboard, open 'R&D Tech Lab' inside the Agency Telemetry panel to unlock new propulsion, alloys, or GMAT diagnostics.", + isComplete: (agency) => { + if (!agency) return false; + const prof = getDifficultyProfile(agency.difficulty); + if (prof.allTechUnlocked) return true; + return ( + (agency.unlockedTechs ?? []).length > 1 || + (agency.unlockedTechs ?? []).some( + (id) => id !== "starter" && TECH_TREE.some((t) => t.id === id), + ) + ); + }, + }, +]; + +let coachRootEl: HTMLElement | null = null; +let initialized = false; + +export function getManualChecklistState(): Record { + return { ...loadState().manualChecks }; +} + +export function setManualChecklistItem(stepId: string, checked: boolean): void { + const st = loadState(); + st.manualChecks[stepId] = checked; + saveState(st); +} + +export function resetWalkthroughProgress(): void { + const st = loadState(); + st.manualChecks = {}; + st.stepIndex = 0; + saveState(st); + syncWalkthroughOverlay(getCurrentScreen()); +} + +export function isWalkthroughActive(): boolean { + return loadState().active; +} + +export function shouldShowFirstRunTutorialOffer( + agency: AgencyState | null, +): boolean { + if (!agency) return false; + const st = loadState(); + if (st.active || st.dismissedOffer) return false; + return agency.missionsCompleted === 0 && agency.missionsFailed === 0; +} + +export function dismissFirstRunTutorialOffer(): void { + const st = loadState(); + st.dismissedOffer = true; + saveState(st); +} + +export function startWalkthrough(stepIndex = 0): void { + const st = loadState(); + st.active = true; + st.collapsed = false; + st.dismissedOffer = true; + st.stepIndex = Math.max(0, Math.min(WALKTHROUGH_STEPS.length - 1, stepIndex)); + saveState(st); + syncWalkthroughOverlay(getCurrentScreen()); +} + +export function stopWalkthrough(): void { + const st = loadState(); + st.active = false; + saveState(st); + syncWalkthroughOverlay(getCurrentScreen()); +} + +function requestOpenWikiArticle(articleId: WikiArticleId): void { + window.dispatchEvent( + new CustomEvent("sgywftp:open-wiki", { + detail: { articleId, preferDrawer: true }, + }), + ); +} + +export function initWalkthroughController(): void { + if (initialized) return; + initialized = true; + coachRootEl = document.getElementById("walkthrough-coach-root"); + if (!coachRootEl) { + coachRootEl = h("div", { id: "walkthrough-coach-root" }); + document.body.appendChild(coachRootEl); + } + window.addEventListener("sgywftp:agency-sync", () => { + syncWalkthroughOverlay(getCurrentScreen()); + }); + window.addEventListener("sgywftp:screen-changed", (ev) => { + const screen = (ev as CustomEvent<{ screen?: ScreenName }>).detail?.screen; + syncWalkthroughOverlay(screen ?? getCurrentScreen()); + }); + syncWalkthroughOverlay(getCurrentScreen()); +} + +export function syncWalkthroughOverlay(screen: ScreenName): void { + if (!coachRootEl) return; + clear(coachRootEl); + const st = loadState(); + if ( + !st.active || + screen === "mainMenu" || + screen === "auth" || + screen === "onboarding" + ) { + return; + } + const idx = Math.max(0, Math.min(WALKTHROUGH_STEPS.length - 1, st.stepIndex)); + const step = WALKTHROUGH_STEPS[idx]; + const agency = state.agency; + const done = step.isComplete(agency) || !!st.manualChecks[step.id]; + + if (st.collapsed) { + coachRootEl.appendChild( + h( + "div", + { class: "walkthrough-pill panel" }, + h( + "span", + { class: "badge info" }, + `TUTORIAL ${idx + 1}/${WALKTHROUGH_STEPS.length}`, + ), + h("span", { class: "mono", style: { fontSize: "11px" } }, step.title), + h( + "button", + { + class: "btn xs primary", + onClick: () => { + const next = loadState(); + next.collapsed = false; + saveState(next); + syncWalkthroughOverlay(screen); + }, + }, + "Expand", + ), + h( + "button", + { + class: "btn xs ghost", + onClick: () => stopWalkthrough(), + }, + "Exit", + ), + ), + ); + return; + } + + const hintText = step.actionHint(screen, agency); + const needsScreenSwitch = screen !== step.targetScreen && screen !== "wiki"; + + coachRootEl.appendChild( + h( + "div", + { class: "walkthrough-card panel" }, + h( + "div", + { class: "spread", style: { gap: "8px", marginBottom: "6px" } }, + h( + "div", + { class: "row", style: { gap: "6px" } }, + h( + "span", + { class: "badge info" }, + `WALKTHROUGH ${idx + 1}/${WALKTHROUGH_STEPS.length}`, + ), + done + ? h("span", { class: "badge ok" }, "STEP READY ✓") + : h("span", { class: "badge warn" }, "IN PROGRESS"), + ), + h( + "div", + { class: "row", style: { gap: "4px" } }, + h( + "button", + { + class: "btn xs ghost", + title: "Minimize walkthrough bar", + onClick: () => { + const next = loadState(); + next.collapsed = true; + saveState(next); + syncWalkthroughOverlay(screen); + }, + }, + "—", + ), + h( + "button", + { + class: "btn xs ghost", + title: "Close guided walkthrough", + onClick: () => stopWalkthrough(), + }, + "✕", + ), + ), + ), + h("div", { class: "walkthrough-title" }, step.title), + h("p", { class: "walkthrough-hint" }, hintText), + h( + "div", + { + class: "row", + style: { gap: "6px", marginTop: "8px", flexWrap: "wrap" }, + }, + idx > 0 + ? h( + "button", + { + class: "btn xs ghost", + onClick: () => { + const next = loadState(); + next.stepIndex = Math.max(0, idx - 1); + saveState(next); + syncWalkthroughOverlay(screen); + }, + }, + "← Prev", + ) + : null, + needsScreenSwitch + ? h( + "button", + { + class: "btn xs primary", + onClick: () => navigate(step.targetScreen), + }, + `Go to ${step.targetScreenLabel} →`, + ) + : null, + h( + "button", + { + class: "btn xs", + onClick: () => requestOpenWikiArticle(step.wikiArticleId), + }, + "Wiki Guide", + ), + idx < WALKTHROUGH_STEPS.length - 1 + ? h( + "button", + { + class: `btn xs ${done ? "primary" : "ghost"}`, + onClick: () => { + const next = loadState(); + next.stepIndex = Math.min( + WALKTHROUGH_STEPS.length - 1, + idx + 1, + ); + saveState(next); + syncWalkthroughOverlay(screen); + }, + }, + "Next Step →", + ) + : h( + "button", + { + class: "btn xs primary", + onClick: () => stopWalkthrough(), + }, + "Finish Tutorial ✓", + ), + ), + ), + ); +} diff --git a/src/client/wiki/wikiData.ts b/src/client/wiki/wikiData.ts new file mode 100644 index 0000000..9b1a5be --- /dev/null +++ b/src/client/wiki/wikiData.ts @@ -0,0 +1,687 @@ +// Wikipedia, but like, database + +export type WikiArticleId = + | "getting-started" + | "propulsion-staging" + | "structures-aero" + | "guidance-orbit" + | "bus-avionics-crew" + | "compliance-qa" + | "economy-world" + | "glossary-index" + | "tech-tree-ref" + | "my-vehicle-inspector"; + +export type WikiCategory = + | "Tutorial & Career Loop" + | "Engineering & Physics" + | "Operations & Systems" + | "Live Reference Directories"; + +export type WikiLabKind = + | "checklist" + | "dv-staging" + | "stability-maxq" + | "gravity-turn" + | "compliance-directory" + | "glossary-directory" + | "tech-difficulty-directory" + | "vehicle-inspector"; + +export interface WikipediaRef { + title: string; + url: string; + summary: string; +} + +export interface WikiSection { + heading: string; + paragraphs: string[]; + bullets?: string[]; + formula?: string; +} + +export interface WikiArticle { + id: WikiArticleId; + title: string; + shortTitle: string; + category: WikiCategory; + summary: string; + coachTip: string; + relatedScreens: Array<{ + screen: "dashboard" | "contracts" | "builder" | "config" | "worldMap"; + label: string; + }>; + sections: WikiSection[]; + labKind?: WikiLabKind; + wikipediaRefs: WikipediaRef[]; +} + +export const WIKI_CATEGORIES: WikiCategory[] = [ + "Tutorial & Career Loop", + "Engineering & Physics", + "Operations & Systems", + "Live Reference Directories", +]; + +export const WIKI_ARTICLES: WikiArticle[] = [ + { + id: "getting-started", + title: "Getting Started & Interactive Flight Tutorial", + shortTitle: "Interactive Tutorial & Career Loop", + category: "Tutorial & Career Loop", + summary: + "Learn the end-to-end agency loop from signing your first sponsor contract to building, certifying, configuring, launching, and upgrading via R&D.", + coachTip: + "Start with the interactive checklist below or hit 'Start Interactive Walkthrough' to keep a live step-by-step coach pinned while you jump across screens. -- ULTRACAT", + relatedScreens: [ + { screen: "contracts", label: "Contracts & Rank" }, + { screen: "builder", label: "Rocket Builder" }, + { screen: "config", label: "Param Config" }, + ], + labKind: "checklist", + sections: [ + { + heading: "1. The 5-Step Mission Loop", + paragraphs: [ + "Every orbital program in SGYWFTP follows a closed engineering-and-finance cycle. Signing a contract grants a 35% upfront advance, while the remaining payout (plus science, efficiency, and reusability bonuses) is settled only after orbital insertion.", + ], + bullets: [ + "1. Charter & Contract: Choose a space sponsor during onboarding or sign a mission in Contracts & Rank (Tier 1 LEO payloads first).", + "2. Rocket Builder: Stack propulsion stages, tanks, structures, fairings, flight computer, and spacecraft bus until Δv margin ≥ 0 and Liftoff TWR ≥ 1.22.", + "3. NASA CML/TRL Certification: Resolve or waive compliance blockers in the NASA CML / TRL tab and advance vehicle maturity from Concept → PDR → CDR → Flight-Ready.", + "4. Param Config & QA: Tune Gravity Turn parameters (or use Auto-Tune Flight Computer), inspect weather hazards & launch windows, and optionally buy Static Fire QA or Launch Insurance.", + "5. Launch & Debrief: Watch real-time 3D ascent & telemetry, then inspect your Mission After-Action Report and invest Reputation & Cash in the R&D Tech Lab.", + ], + }, + { + heading: "2. Difficulty Tiers, Bailouts & Stand-Downs", + paragraphs: [ + "Your agency's difficulty tier (Sandbox, Explorer, Enthusiast, Engineer, Flight Director) sets starting treasury, orbital insertion corridor tolerances (±50% down to ±4%), hardware defect multipliers, bailout allowance, and whether Loss of Crew (LOC) revokes your operating license.", + "If a pad explosion damages Launch Complex 39A or a crewed anomaly triggers a Safety Board grounding, you can wait out the simulation timer or pay for Expedited Clearance on the Dashboard.", + ], + }, + ], + wikipediaRefs: [ + { + title: "Spaceflight", + url: "https://en.wikipedia.org/wiki/Spaceflight", + summary: + "Overview of astronautics, launch operations, orbital regimes, and spacecraft engineering.", + }, + { + title: "Launch vehicle", + url: "https://en.wikipedia.org/wiki/Launch_vehicle", + summary: + "How multi-stage rockets deliver payloads from a planetary surface into Earth orbit or escape trajectories.", + }, + { + title: "Orbital spaceflight", + url: "https://en.wikipedia.org/wiki/Orbital_spaceflight", + summary: + "Why reaching orbit requires achieving horizontal orbital velocity (~7.8 km/s in LEO), not just altitude.", + }, + ], + }, + { + id: "propulsion-staging", + title: "Propulsion, Rocket Equation & Staging", + shortTitle: "Propulsion & Δv Staging Lab", + category: "Engineering & Physics", + summary: + "Master Tsiolkovsky's rocket equation, Specific Impulse (Isp), Thrust-to-Weight Ratio (TWR), propellant chemistries, and crossfeed drop tanks.", + coachTip: + "Adding more propellant to Stage 1 stops helping fast if Stage 2 is hauling heavy steel dead weight. Put high-Isp Hydrolox or Methalox Vacuum engines upstairs and drop empty tanks early! -- ULTRACAT", + relatedScreens: [{ screen: "builder", label: "Open Rocket Builder" }], + labKind: "dv-staging", + sections: [ + { + heading: "1. Tsiolkovsky Rocket Equation & Staging", + paragraphs: [ + "Delta-v (Δv) measures total velocity-change capability. Because propellant must accelerate both payload and remaining unburned propellant, Δv scales logarithmically with the wet-to-dry mass ratio. Dropping empty lower stages and disposable drop tanks dramatically shrinks dry mass mid-flight.", + ], + formula: "Δv = Isp × g0 × ln(m_wet / m_dry) | g0 = 9.80665 m/s²", + bullets: [ + "Mandatory PROP-03: Liftoff TWR must exceed 1.05 to clear the launch mount.", + "Recommended PROP-04: Liftoff TWR ≥ 1.22 minimizes gravity losses (typically 1.30–1.70 is ideal).", + "Upper Stages (PROP-05): Keep stage ignition TWR ≥ 0.45 so the upper stage climbs past apoapsis before gravity pulls it back.", + "Two-Phase Drop Tank Crossfeed: When external drop tanks feed the core engine, phase 1 burns drop-tank propellant, jettisons the empty external shells, and phase 2 burns the full core tank.", + ], + }, + { + heading: "2. Propellant Chemistries & Engine Controls", + paragraphs: [ + "Every engine must match its tank chemistry (PROP-02). Higher Isp extracts more velocity per kilogram of propellant, while denser fuels keep stages compact and structurally lighter.", + ], + bullets: [ + "Kerolox (RP-1/LOX): Dense, high-thrust booster workhorse (Merlin-1D / MVac). Low tank volume and cost.", + "Methalox (CH4/LOX): Balanced density, full-flow staged combustion efficiency (Raptor SL/Vac), clean reusability.", + "Hydrolox (LH2/LOX): Highest chemical vacuum Isp (RL-10C, J-2X, RS-25) for upper stages and deep-space injection, but low density requires larger cryo-insulated tanks (THRM-01).", + "Hypergolic (NTO/MMH): Instant restartable storable thrusters (AJ10) for reliable orbital circularization.", + "Solid (PBAN SRB): High liftoff thrust and cheap strap-on kick, but non-throttleable and prohibited as Stage 1 for crewed flights (CREW-04).", + "Xenon Hall Ion (NEXT-C): ~3,200 s Isp electric thruster producing zero thrust below 110 km; requires ≥ 8,800 m/s of chemical lower stages (PROP-07).", + "Nozzle Ratio & Gimbal: Narrower bells resist sea-level overexpansion at liftoff; wider bells boost vacuum Isp. Stage 1 requires ≥ ±3° TVC gimbal (AERO-04).", + ], + }, + ], + wikipediaRefs: [ + { + title: "Tsiolkovsky rocket equation", + url: "https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation", + summary: + "Derivation and implications of Δv = ve ln(m0/mf) governing all chemical and electric rockets.", + }, + { + title: "Delta-v", + url: "https://en.wikipedia.org/wiki/Delta-v", + summary: + "Orbital Δv budgets, gravity/drag losses, and transfer energy accounting.", + }, + { + title: "Specific impulse", + url: "https://en.wikipedia.org/wiki/Specific_impulse", + summary: + "Propellant efficiency in seconds, exhaust velocity, and sea-level vs vacuum nozzle performance.", + }, + { + title: "Thrust-to-weight ratio", + url: "https://en.wikipedia.org/wiki/Thrust-to-weight_ratio", + summary: + "Why boosters require TWR > 1.0 at liftoff while orbital stages operate effectively below 1.0.", + }, + { + title: "Multistage rocket", + url: "https://en.wikipedia.org/wiki/Multistage_rocket", + summary: + "Serial and parallel staging mechanics that shed structural dead weight during ascent.", + }, + { + title: "Propellant crossfeed", + url: "https://en.wikipedia.org/wiki/Propellant_crossfeed", + summary: + "Draining external boosters/drop tanks into the core engine first to jettison empty mass early.", + }, + { + title: "De Laval nozzle", + url: "https://en.wikipedia.org/wiki/De_Laval_nozzle", + summary: + "Convergent-divergent supersonic bell geometry and nozzle expansion ratio trade-offs.", + }, + { + title: "Liquid-propellant rocket", + url: "https://en.wikipedia.org/wiki/Liquid-propellant_rocket", + summary: + "Kerolox, Hydrolox, Methalox, and Hypergolic bipropellant systems and engine cycles.", + }, + { + title: "Hall-effect thruster", + url: "https://en.wikipedia.org/wiki/Hall-effect_thruster", + summary: + "High-Isp electrostatic xenon propulsion used exclusively in vacuum orbital regimes.", + }, + ], + }, + { + id: "structures-aero", + title: "Structures, Aerodynamics & Thermal", + shortTitle: "Structures, Aero & Stability Lab", + category: "Engineering & Physics", + summary: + "Balance Center of Gravity (CG) ahead of Center of Pressure (CP), prevent shell buckling and Max-Q breakup, and select optimal hull alloys and thermal protection.", + coachTip: + "Think of a dart or arrow: heavy mass at the nose (CG) and aerodynamic drag fins at the tail (CP). If CP climbs ahead of CG, your rocket wants to fly backwards under Max-Q! -- ULTRACAT", + relatedScreens: [{ screen: "builder", label: "Inspect CG/CP in Builder" }], + labKind: "stability-maxq", + sections: [ + { + heading: "1. CG vs CP Static Stability & Aerodynamics", + paragraphs: [ + "During atmospheric ascent, aerodynamic restoring/destabilizing forces act through the Center of Pressure (CP), while rotational inertia pivots around the Center of Gravity (CG). Static stability margin is measured in hull diameters ('calibers').", + ], + formula: + "Static Stability Margin (Calibers) = (CG_y − CP_y) / Max Diameter (Target ≥ +0.40)", + bullets: [ + "AERO-01: Keep CG ahead of (above) CP by ≥ 0.40 calibers. Enable Titanium Grid Fins on Stage 1 to pull CP downward.", + "Slenderness (STR-03): Keep Height / Max Diameter (L/D) ≤ 22 to avoid excessive bending loads.", + "Stage Taper (STR-04 & STR-05): Diameter steps > 25% need a Tapered Conical Adapter, and upper stages may never exceed 1.4× booster diameter.", + "Fairing (AERO-02 & PAY-02/03): Enclose satellites inside a fairing wider and taller than the payload; blunt exposed noses double drag.", + ], + }, + { + heading: "2. Max-Q, Buckling & Hull Materials", + paragraphs: [ + "Max-Q (Maximum Dynamic Pressure) occurs in the lower stratosphere where rising supersonic speed meets dense air. Compressive thrust and wind shear can buckle thin tank walls or exceed shell yield limits.", + ], + formula: + "q = ½ × ρ(altitude) × v² | Buckling Ratio = Axial Load / (0.65 × Yield Limit) < 1.0", + bullets: [ + "Aluminum 7075-T6 (1.0× mass, 503 MPa, 450 K): Cheap baseline starter alloy.", + "Aluminum-Lithium 2195 (0.88× mass, 560 MPa, 490 K): Cryo-ready lightweight upgrade from R&D.", + "IM7 Carbon-Epoxy (0.68× mass, 780 MPa, 430 K): Ultralight composite; pair with a heatshield on hot ascent profiles (THRM-04).", + "Cryo-Hardened 304L Steel (1.28× mass, 680 MPa, 1150 K) & Inconel-718 (1.55× mass, 1030 MPa, 1450 K): High thermal survival for reentry/recovery and extreme heat flux.", + "PICA-X Heatshield & Launch Abort System (LAS): Heatshields protect boosters for recovery bonus and deep-space thermal corridors; LAS saves crew lives (0 casualties) during abort events.", + ], + }, + ], + wikipediaRefs: [ + { + title: "Max Q", + url: "https://en.wikipedia.org/wiki/Max_Q", + summary: + "Peak atmospheric dynamic pressure during ascent and why rockets throttle down through the transonic bucket.", + }, + { + title: "Center of pressure (fluid mechanics)", + url: "https://en.wikipedia.org/wiki/Center_of_pressure_(fluid_mechanics)", + summary: + "Where aerodynamic lift and drag forces act on a launch vehicle airframe.", + }, + { + title: "Center of mass", + url: "https://en.wikipedia.org/wiki/Center_of_mass", + summary: + "How propellant consumption shifts a rocket's balance point relative to aerodynamic forces.", + }, + { + title: "Buckling", + url: "https://en.wikipedia.org/wiki/Buckling", + summary: + "Thin-walled cylindrical shell failure under axial compression and bending loads.", + }, + { + title: "Fineness ratio", + url: "https://en.wikipedia.org/wiki/Fineness_ratio", + summary: + "Length-to-diameter ratio (L/D) balancing supersonic wave drag against structural bending.", + }, + { + title: "Payload fairing", + url: "https://en.wikipedia.org/wiki/Payload_fairing", + summary: + "Clamshell nosecone shielding spacecraft from supersonic airloads and jettisoned above the dense atmosphere.", + }, + { + title: "Grid fin", + url: "https://en.wikipedia.org/wiki/Grid_fin", + summary: + "Lattice aerodynamic stabilizers that pull CP aft and enable booster recovery steering.", + }, + { + title: "Atmospheric entry", + url: "https://en.wikipedia.org/wiki/Atmospheric_entry", + summary: + "Aerothermal plasma heating, heat shields, and thermal protection systems (TPS).", + }, + { + title: "Launch escape system", + url: "https://en.wikipedia.org/wiki/Launch_escape_system", + summary: + "Solid-motor escape tower designed to pull crewed capsules clear of failing boosters.", + }, + ], + }, + { + id: "guidance-orbit", + title: "Flight Guidance, Gravity Turn & Orbital Mechanics", + shortTitle: "Guidance & Gravity Turn Lab", + category: "Engineering & Physics", + summary: + "Shape an efficient ascent trajectory using Gravity Turn parameters, Max-Q throttling, fairing separation, MECO/SECO, launch windows, and GMAT orbital analysis.", + coachTip: + "Going straight up doesn't keep you in space—moving sideways at ~7,800 m/s does! Let gravity naturally bend your velocity vector onto the horizon via a smooth pitch-over kick. -- ULTRACAT", + relatedScreens: [ + { screen: "config", label: "Open Param Config" }, + { screen: "worldMap", label: "Open World Map" }, + ], + labKind: "gravity-turn", + sections: [ + { + heading: "1. Shaping the Gravity Turn", + paragraphs: [ + "The Flight Parameter Configurator simulates your exact rocket along a curved-Earth 2D planar trajectory. Your goal is to leave the dense atmosphere cleanly while converting vertical speed into horizontal orbital speed before upper-stage burnout.", + ], + bullets: [ + "Gravity Turn Start Velocity (35–160 m/s): Airspeed where the rocket begins tilting east after clearing the pad tower.", + "Initial Pitch-Over Kick (3–18°): Small early angle tilt. Too small (< 5°) wastes Δv fighting gravity; too large (> 13°) plunges horizontally into thick air and spikes Max-Q & heat flux.", + "Gravity Turn Level-Off Alt (65–130 km): Altitude where guidance finishes flattening toward horizontal (0°).", + "Max-Q Throttle Bucket (0.50–1.00): Automatically throttles down near Mach 0.9–1.5 to tame peak dynamic pressure.", + "Fairing Jettison Alt (70–130 km): Must exceed the contract minimum (typically ≥ 80–90 km, AERO-03) to avoid payload aero loss.", + "Upper Burn Continuous Fraction (0.65–1.00): Controls coast vs continuous circularization burn split.", + ], + }, + { + heading: "2. Orbital Elements, Launch Windows & GMAT", + paragraphs: [ + "A stable parking orbit requires both Apoapsis (highest point) and Periapsis (lowest point) to stay within your difficulty's tolerance corridor, with Periapsis safely above Earth's dense atmosphere (≥ 90 km).", + "Higher target inclinations reduce Earth's rotational eastward boost and cost extra Δv. Launch Windows oscillate over synodic periods—launching off-peak adds a Window Δv Penalty (ORB-04). Unlocking Tier-3 Avionics unlocks NASA GMAT-backed 3D orbital propagation graphs.", + ], + }, + ], + wikipediaRefs: [ + { + title: "Gravity turn", + url: "https://en.wikipedia.org/wiki/Gravity_turn", + summary: + "Zero-lift trajectory optimization turning vertical launch velocity smoothly into horizontal orbital speed.", + }, + { + title: "Apsis", + url: "https://en.wikipedia.org/wiki/Apsis", + summary: + "Apoapsis (highest point) and periapsis (lowest point) defining an elliptical orbit.", + }, + { + title: "Orbital inclination", + url: "https://en.wikipedia.org/wiki/Orbital_inclination", + summary: + "Tilt of an orbital plane relative to the equator and plane-change Δv penalties.", + }, + { + title: "Low Earth orbit", + url: "https://en.wikipedia.org/wiki/Low_Earth_orbit", + summary: + "Orbital speeds (~7.8 km/s), atmospheric drag thresholds, and parking orbit mechanics.", + }, + { + title: "Hohmann transfer orbit", + url: "https://en.wikipedia.org/wiki/Hohmann_transfer_orbit", + summary: + "Two-impulse elliptical transfer maneuver between circular orbits and planetary targets.", + }, + { + title: "Launch window", + url: "https://en.wikipedia.org/wiki/Launch_window", + summary: + "Orbital alignment timing windows and the Δv penalty incurred outside optimal phase.", + }, + { + title: "General Mission Analysis Tool", + url: "https://en.wikipedia.org/wiki/General_Mission_Analysis_Tool", + summary: + "NASA's high-precision trajectory propagation and mission optimization software integrated into SGYWFTP Tier-3 diagnostics.", + }, + ], + }, + { + id: "bus-avionics-crew", + title: "Spacecraft Bus, Avionics & Crew Systems", + shortTitle: "Bus, Avionics & Crew", + category: "Operations & Systems", + summary: + "Size flight computers against CPU demand and radiation SEUs, balance spacecraft electrical power & deep-space comms links, and protect astronauts with ECLSS & LAS.", + coachTip: + "Solar arrays shrink dramatically past Mars (1/r²!). Switch to MMRTG or Kilopower fission and upgrade to X/Ka-Band + Global DSN before signing outer-planet contracts. -- ULTRACAT", + relatedScreens: [ + { screen: "builder", label: "Fairing & Payload Tab" }, + { screen: "config", label: "Crew & ECLSS Sliders" }, + ], + sections: [ + { + heading: "1. Flight Computer (GNC), CPU Load & SEUs", + paragraphs: [ + "Every rocket mounts a Guidance, Navigation & Control (GNC) flight computer in the Payload/Bus tab. Compute demand grows with stages, engine cluster count, science instruments, LAS, and split burns.", + "If peak CPU load approaches 100%, guidance can freeze mid-ascent (AVN-02). During solar/radiation storms or high-energy missions, cosmic particles trigger Single-Event Upsets (SEUs)—upgrade to RAD750, Aegis-IV, or Chronos-X for Triple/Quad Modular Redundancy and ECC fault scrubbing (AVN-03).", + ], + }, + { + heading: "2. Spacecraft Bus: Power, Comms & Science Instruments", + paragraphs: [ + "Your payload's spacecraft bus determines electrical power margin (PAY-06), telemetry signal health (PAY-07), and bonus science payouts/RP.", + ], + bullets: [ + "Power Systems: Standard & ROSA Solar Arrays scale with solar flux (1/r²) and suffer eclipse drains; MMRTG (900 W) and Kilopower Fission (4.2 kW) output constant power in deep space.", + "Comms & Ground Network: S-Band works in LEO; Lunar, Mars, and Jupiter targets require X-Band or Ka-Band/Optical dishes paired with Global DSN or Deep Space Optical Array tracking.", + "Science Instruments: Adding compatible imagers, magnetometers, spectrometers, or laser relays boosts Science Bonus payout and Research Points—provided your bus power and downlink bandwidth cover them.", + ], + }, + { + heading: "3. Crew Capacity, ECLSS & Launch Abort System", + paragraphs: [ + "Crewed contracts enforce strict human-rating rules: a crew-capable capsule (CREW-01), adequate ECLSS life support seats in Param Config (CREW-02), a Launch Abort System tower (CREW-03), and throttleable liquid Stage 1 engines (CREW-04).", + "Without LAS, a booster failure causes Loss of Crew (LOC), heavy inquiry fines, reputation collapse, and on Flight Director difficulty, permanent agency termination.", + ], + }, + ], + wikipediaRefs: [ + { + title: "Satellite bus", + url: "https://en.wikipedia.org/wiki/Satellite_bus", + summary: + "Spacecraft structural and service architecture supplying power, telemetry, thermal control, and attitude stability.", + }, + { + title: "Radiation hardening", + url: "https://en.wikipedia.org/wiki/Radiation_hardening", + summary: + "Redundant voting logic (TMR) and shielding protecting flight avionics against cosmic radiation.", + }, + { + title: "Single-event upset", + url: "https://en.wikipedia.org/wiki/Single-event_upset", + summary: + "Ionizing-particle bit flips causing transient resets or lockups in orbital processors.", + }, + { + title: "Radioisotope thermoelectric generator", + url: "https://en.wikipedia.org/wiki/Radioisotope_thermoelectric_generator", + summary: + "Nuclear decay power supplies enabling outer-planet exploration far from sunlight.", + }, + { + title: "NASA Deep Space Network", + url: "https://en.wikipedia.org/wiki/NASA_Deep_Space_Network", + summary: + "Global high-gain ground dish complexes sustaining telemetry across cislunar and interplanetary distances.", + }, + { + title: "Life-support system", + url: "https://en.wikipedia.org/wiki/Life-support_system", + summary: + "ECLSS oxygen regeneration, CO2 scrubbing, thermal regulation, and crew survival systems.", + }, + ], + }, + { + id: "compliance-qa", + title: "NASA CML/TRL Compliance, QA & Builder Modes", + shortTitle: "Compliance Rules & QA", + category: "Operations & Systems", + summary: + "Understand Concept → PDR → CDR → Flight-Ready maturity gates, mandatory vs waiverable compliance rules, Static Fire QA, Insurance, and Pro 3D Freeform mode.", + coachTip: + "Only grant a Waiver when a fix is genuinely out of reach—waivers add launch fees AND stack live anomaly risk! Static Fire QA in Param Config cuts hardware defect risk significantly. -- ULTRACAT", + relatedScreens: [ + { screen: "builder", label: "Compliance Tab" }, + { screen: "config", label: "Pre-Launch QA" }, + ], + labKind: "compliance-directory", + sections: [ + { + heading: "1. Design Maturity Gates & Waivers", + paragraphs: [ + "Except in Sandbox difficulty, a launch vehicle must reach FLIGHT-READY maturity before clearing the pad. Every design is evaluated against 42 engineering rules across Propulsion, Structures, Aerodynamics, Thermal, Payload & Bus, Crew, and Orbital rules.", + ], + bullets: [ + "Concept → PDR: Requires passing mandatory propulsion and payload rules.", + "PDR → CDR: Requires zero mandatory rule failures across the entire stack.", + "CDR → Flight-Ready: Requires zero unwaived advisory failures and zero locked R&D parts.", + "Waivers: Advisory ('waiverable') warnings can be waived for an added fee and +5% to +12% in-flight anomaly probability. Mandatory rules can never be waived.", + ], + }, + { + heading: "2. Guided vs Pro Freeform 3D & Blueprints", + paragraphs: [ + "Guided fidelity tiers (Casual, Standard, Expert) arrange stages vertically with structured slots and symmetric drop-tank controls (Expert unlocks custom tank fill ratios). PRO mode unlocks direct 3D viewport part placement, radial symmetry clusters, and arbitrary offsets.", + "Use Blueprints & Share in Rocket Builder to save hangar designs, exchange portable SGYW1 share codes, or inspect Undo/Redo edit history.", + ], + }, + { + heading: "3. Static Fire QA & Launch Insurance", + paragraphs: [ + "In Param Config's Pre-Launch QA box, you can run a Static Fire test (~4% of vehicle cost, min $450k) to verify the exact current design hash and cut hardware defect probability (-8% defect boost). Launch Insurance (8% premium on Enthusiast/Engineer/Director) reimburses 70% of vehicle hull cost on failure.", + ], + }, + ], + wikipediaRefs: [ + { + title: "Technology readiness level", + url: "https://en.wikipedia.org/wiki/Technology_readiness_level", + summary: + "NASA's 1–9 scale measuring flight maturity of spacecraft hardware and subsystems.", + }, + { + title: "Design review (U.S. government)", + url: "https://en.wikipedia.org/wiki/Design_review_(U.S._government)", + summary: + "Preliminary Design Review (PDR), Critical Design Review (CDR), and Flight Readiness milestones.", + }, + { + title: "Range safety", + url: "https://en.wikipedia.org/wiki/Range_safety", + summary: + "Pre-launch certification, flight termination safeguards, and waiver review procedures.", + }, + ], + }, + { + id: "economy-world", + title: "Contracts, Economy, Space Weather & Co-Op", + shortTitle: "Economy, Weather & Co-Op", + category: "Operations & Systems", + summary: + "Navigate Tier 1–5 contracts, Custom & Convoluted missions, dynamic commodity part pricing, live space weather hazards, the 3D World Map, and 4-station Co-Op engineering.", + coachTip: + "Keep an eye on the Launch Environment Forecast! Launching during a Radiation Storm or Jet-Stream Shear spikes SEU lockups and Max-Q loads unless your rocket carries countermeasures. -- ULTRACAT", + relatedScreens: [ + { screen: "contracts", label: "Contracts & Exchange" }, + { screen: "worldMap", label: "3D World Map" }, + ], + sections: [ + { + heading: "1. Contracts, Commodity Exchange & Reputation", + paragraphs: [ + "Contracts & Rank lists offers across sponsors (with loyalty bonuses for your home sponsor), alongside the Custom Mission Architect and procedural Convoluted Missions for high-stakes payouts.", + "Part prices fluctuate in real time on the Commodity Exchange driven by global agency demand. Check Value Chart in Rocket Builder to compare Projected Net EV, Risk-Adjusted EV, and $/kg payload cost before launching.", + ], + }, + { + heading: "2. Space Weather, Hazards & World Map", + paragraphs: [ + "Global space weather (Nominal, Solar Wind, Solar Storm, Radiation Storm, Micrometeoroid) and transient corridor hazards (Stray Radiation, Meteorite Streams, Jet-Stream Shear) shift dynamically via live server events.", + "Inspect active AI/player flights and 3D NASA probes (ISS, JWST, Hubble, Juno, Voyager, Parker Solar Probe, and more) in the Solar System Explorer (World Map), or spectate live launches from the Dashboard.", + ], + }, + { + heading: "3. Multi-Operator Co-Op Stations", + paragraphs: [ + "Multiple users logged into the same agency synchronize Rocket Builder edits live over SSE. Claim one of the 4 mission control stations—PROP (Propulsion), STRC (Structures), GUID (Guidance), PAYL (Payload/Comms)—and toggle Ready status together.", + ], + }, + ], + wikipediaRefs: [ + { + title: "Space weather", + url: "https://en.wikipedia.org/wiki/Space_weather", + summary: + "Solar wind, geomagnetic storms, and orbital radiation variations affecting launch operations.", + }, + { + title: "Solar particle event", + url: "https://en.wikipedia.org/wiki/Solar_particle_event", + summary: + "High-energy solar proton bursts that raise single-event upset (SEU) rates in spacecraft electronics.", + }, + { + title: "Micrometeoroid", + url: "https://en.wikipedia.org/wiki/Micrometeoroid", + summary: + "Hypervelocity space dust hazards requiring fairings, Whipple protection, or window timing.", + }, + { + title: "Ephemeris", + url: "https://en.wikipedia.org/wiki/Ephemeris", + summary: + "Time-indexed planetary and spacecraft position tables driving solar system trajectories.", + }, + ], + }, + { + id: "glossary-index", + title: "Searchable Aerospace Terminology Glossary", + shortTitle: "Glossary & Formulas", + category: "Live Reference Directories", + summary: + "Complete reference of every HUD '?' tooltip term, engineering formula, and direct Wikipedia deep-dive link.", + coachTip: + "Remember: clicking any '?' badge anywhere in the HUD and hitting 'Open in Wiki →' lands right on the exact term here without discarding your rocket draft! -- ULTRACAT", + relatedScreens: [ + { screen: "builder", label: "Rocket Builder" }, + { screen: "config", label: "Param Config" }, + ], + labKind: "glossary-directory", + sections: [], + wikipediaRefs: [ + { + title: "Rocket engine", + url: "https://en.wikipedia.org/wiki/Rocket_engine", + summary: + "General encyclopedia entry on rocket propulsion principles and terminology.", + }, + { + title: "Spacecraft thermal control", + url: "https://en.wikipedia.org/wiki/Spacecraft_thermal_control", + summary: + "Managing aero-heating, solar flux, and radiator heat rejection.", + }, + ], + }, + { + id: "tech-tree-ref", + title: "R&D Tech Tree & Difficulty Tier Reference", + shortTitle: "Tech Tree & Difficulty", + category: "Live Reference Directories", + summary: + "Live reference table generated directly from the game's R&D technology nodes and difficulty simulation profiles.", + coachTip: + "Prioritize Cryogenic Hydrolox and Telemetry & Fault-Scrubbing (Tier 2) early if you're aiming for GEO, Lunar, or severe weather windows! -- ULTRACAT", + relatedScreens: [{ screen: "dashboard", label: "Dashboard (Tech Lab)" }], + labKind: "tech-difficulty-directory", + sections: [], + wikipediaRefs: [ + { + title: "Technology readiness level", + url: "https://en.wikipedia.org/wiki/Technology_readiness_level", + summary: + "How aerospace R&D programs mature new engines, alloys, and avionics from concept to flight.", + }, + ], + }, + { + id: "my-vehicle-inspector", + title: "Live Agency & Rocket Diagnostic Inspector", + shortTitle: "My Rocket Inspector", + category: "Live Reference Directories", + summary: + "Inspect your agency's currently saved launch vehicle, active contract margins, compliance rule blockers, and jump straight to the matching Wiki fix guide.", + coachTip: + "Not sure why your rocket is stuck at Concept or failing insertion? Load your current ship here for plain-English links to the exact engineering rule! -- ULTRACAT", + relatedScreens: [ + { screen: "builder", label: "Fix in Rocket Builder" }, + { screen: "config", label: "Fix in Param Config" }, + ], + labKind: "vehicle-inspector", + sections: [], + wikipediaRefs: [ + { + title: "Orbital spaceflight", + url: "https://en.wikipedia.org/wiki/Orbital_spaceflight", + summary: + "Key orbital insertion metrics and launch vehicle performance budgets.", + }, + ], + }, +]; + +export function getWikiArticle(id?: string | null): WikiArticle { + return WIKI_ARTICLES.find((a) => a.id === id) ?? WIKI_ARTICLES[0]; +} diff --git a/src/client/wiki/wikiModal.ts b/src/client/wiki/wikiModal.ts new file mode 100644 index 0000000..3ea77e6 --- /dev/null +++ b/src/client/wiki/wikiModal.ts @@ -0,0 +1,55 @@ +// Modal? Like the runway ones? +import type { GlossaryKey } from "../glossary.js"; +import { h } from "../ui.js"; +import type { WikiArticleId } from "./wikiData.js"; +import { renderWikiWorkspace } from "./wikiWorkspace.js"; + +let activeDrawer: HTMLElement | null = null; +let activeCleanup: (() => void) | null = null; + +export function closeWikiDrawer(): void { + activeCleanup?.(); + activeCleanup = null; +} + +export function openWikiDrawer(opts: { + articleId?: WikiArticleId; + glossaryKey?: GlossaryKey | string; + query?: string; +} = {}): void { + closeWikiDrawer(); + const modalRoot = document.getElementById("modal-root") ?? document.body; + const overlay = h("div", { class: "modal-overlay wiki-drawer-overlay" }); + const drawerPanel = h("div", { class: "panel wiki-drawer-panel" }); + + const onKeyDown = (ev: KeyboardEvent) => { + if (ev.key === "Escape") { + ev.stopPropagation(); + close(); + } + }; + const close = () => { + window.removeEventListener("keydown", onKeyDown, true); + overlay.remove(); + if (activeDrawer === overlay) activeDrawer = null; + if (activeCleanup === close) activeCleanup = null; + }; + + renderWikiWorkspace(drawerPanel, { + initialArticleId: opts.articleId, + initialGlossaryKey: opts.glossaryKey, + initialQuery: opts.query, + mode: "drawer", + backLabel: "✕ Close Wiki", + onBack: close, + }); + + overlay.addEventListener("click", (ev) => { + if (ev.target === overlay) close(); + }); + window.addEventListener("keydown", onKeyDown, true); + overlay.appendChild(drawerPanel); + modalRoot.appendChild(overlay); + activeDrawer = overlay; + activeCleanup = close; +} diff --git a/src/client/wiki/wikiWorkspace.ts b/src/client/wiki/wikiWorkspace.ts new file mode 100644 index 0000000..68f1d09 --- /dev/null +++ b/src/client/wiki/wikiWorkspace.ts @@ -0,0 +1,441 @@ +// Cool thnigy +import { navigate } from "../router.js"; +import { TERMINOLOGY_GLOSSARY, type GlossaryKey } from "../glossary.js"; +import { COMPLIANCE_RULES_META } from "../../shared/compliance.js"; +import { TECH_TREE } from "../../shared/physics.js"; +import { clear, h } from "../ui.js"; +import { renderWikiLab } from "./interactiveLabs.js"; +import { + isWalkthroughActive, + startWalkthrough, + stopWalkthrough, +} from "./walkthrough.js"; +import { + getWikiArticle, + WIKI_ARTICLES, + WIKI_CATEGORIES, + type WikiArticleId, +} from "./wikiData.js"; + +export interface WikiWorkspaceOptions { + initialArticleId?: WikiArticleId; + initialGlossaryKey?: GlossaryKey | string; + initialQuery?: string; + mode: "page" | "drawer"; + backLabel: string; + onBack: () => void; +} + +interface SearchHit { + title: string; + subtitle: string; + badge: string; + onOpen: () => void; +} + +export function renderWikiWorkspace( + container: HTMLElement, + opts: WikiWorkspaceOptions, +): void { + let activeArticleId: WikiArticleId = getWikiArticle( + opts.initialArticleId ?? + (opts.initialGlossaryKey ? "glossary-index" : undefined), + ).id; + let highlightGlossaryKey = + activeArticleId === "glossary-index" ? opts.initialGlossaryKey : undefined; + let query = opts.initialQuery ?? ""; + + const searchInput = h("input", { + class: "input wiki-search-input", + placeholder: + "Search guides, Δv, Max-Q, compliance rules, R&D tech, Wikipedia...", + value: query, + onInput: () => { + query = searchInput.value; + renderSidebarAndResults(); + }, + }) as HTMLInputElement; + + const sidebarEl = h("aside", { class: "wiki-sidebar" }); + const mainEl = h("main", { class: "wiki-main" }); + const walkthroughBtn = h("button", { class: "btn xs primary" }, ""); + + function syncWalkthroughBtn(): void { + const active = isWalkthroughActive(); + walkthroughBtn.className = `btn xs ${active ? "warn" : "primary"}`; + walkthroughBtn.textContent = active + ? "Stop Walkthrough" + : "Start Interactive Walkthrough"; + } + + walkthroughBtn.addEventListener("click", () => { + if (isWalkthroughActive()) { + stopWalkthrough(); + } else { + startWalkthrough(0); + if (opts.mode === "drawer") opts.onBack(); + } + syncWalkthroughBtn(); + }); + + function openArticle(id: WikiArticleId, glossaryKey?: string): void { + activeArticleId = id; + highlightGlossaryKey = glossaryKey; + renderSidebarAndResults(); + renderArticleBody(); + mainEl.scrollTop = 0; + } + + function buildSearchHits(q: string): SearchHit[] { + const needle = q.trim().toLowerCase(); + if (!needle) return []; + const hits: SearchHit[] = []; + const clip = (s: string) => + s.length > 88 ? `${s.slice(0, 88)}...` : s; + + for (const art of WIKI_ARTICLES) { + const hay = + `${art.title} ${art.summary} ${art.sections.map((s) => `${s.heading} ${s.paragraphs.join(" ")} ${(s.bullets ?? []).join(" ")}`).join(" ")}`.toLowerCase(); + if (hay.includes(needle)) { + hits.push({ + title: art.shortTitle, + subtitle: clip(art.summary), + badge: "GUIDE", + onOpen: () => openArticle(art.id), + }); + } + } + + for (const [k, entry] of Object.entries(TERMINOLOGY_GLOSSARY)) { + const hay = + `${entry.title} ${entry.summary} ${entry.formula ?? ""}`.toLowerCase(); + if (hay.includes(needle)) { + hits.push({ + title: entry.title, + subtitle: clip(entry.summary), + badge: "GLOSSARY", + onOpen: () => openArticle("glossary-index", k), + }); + } + } + + for (const rule of COMPLIANCE_RULES_META) { + const hay = + `${rule.code} ${rule.title} ${rule.description}`.toLowerCase(); + if (hay.includes(needle)) { + hits.push({ + title: `[${rule.code}] ${rule.title}`, + subtitle: rule.description, + badge: "RULE", + onOpen: () => openArticle("compliance-qa"), + }); + } + } + + for (const tech of TECH_TREE) { + const hay = + `${tech.name} ${tech.description} ${tech.unlocksIds.join(" ")}`.toLowerCase(); + if (hay.includes(needle)) { + hits.push({ + title: tech.name, + subtitle: tech.description, + badge: "R&D", + onOpen: () => openArticle("tech-tree-ref"), + }); + } + } + + return hits.slice(0, 24); + } + + function renderSidebarAndResults(): void { + clear(sidebarEl); + const hits = buildSearchHits(query); + if (query.trim().length > 0) { + sidebarEl.appendChild( + h( + "div", + { class: "col", style: { gap: "6px" } }, + h( + "div", + { class: "spread" }, + h( + "span", + { class: "slot-title" }, + `Search Results (${hits.length})`, + ), + h( + "button", + { + class: "btn xs ghost", + onClick: () => { + query = ""; + searchInput.value = ""; + renderSidebarAndResults(); + }, + }, + "Clear", + ), + ), + hits.length + ? h( + "div", + { class: "col", style: { gap: "6px" } }, + ...hits.map((hit) => + h( + "button", + { + class: "wiki-search-hit", + onClick: hit.onOpen, + }, + h( + "div", + { class: "spread", style: { gap: "6px" } }, + h( + "strong", + { class: "mono", style: { fontSize: "11px" } }, + hit.title, + ), + h("span", { class: "badge info" }, hit.badge), + ), + h( + "span", + { class: "dim", style: { fontSize: "10px" } }, + hit.subtitle, + ), + ), + ), + ) + : h( + "p", + { class: "dim mono", style: { fontSize: "11px" } }, + "No matching articles, terms, or rules.", + ), + ), + ); + return; + } + + for (const cat of WIKI_CATEGORIES) { + const groupArticles = WIKI_ARTICLES.filter((a) => a.category === cat); + if (!groupArticles.length) continue; + sidebarEl.appendChild( + h( + "div", + { class: "wiki-nav-group" }, + h("div", { class: "wiki-nav-cat" }, cat), + ...groupArticles.map((art) => + h( + "button", + { + class: `wiki-nav-item ${art.id === activeArticleId ? "active" : ""}`, + onClick: () => openArticle(art.id), + }, + h("span", {}, art.shortTitle), + art.labKind ? h("span", { class: "badge info" }, "LAB") : null, + ), + ), + ), + ); + } + } + + function renderArticleBody(): void { + clear(mainEl); + const article = getWikiArticle(activeArticleId); + const idx = WIKI_ARTICLES.findIndex((a) => a.id === article.id); + const prevArt = idx > 0 ? WIKI_ARTICLES[idx - 1] : null; + const nextArt = + idx >= 0 && idx < WIKI_ARTICLES.length - 1 + ? WIKI_ARTICLES[idx + 1] + : null; + + const labEl = renderWikiLab( + article.labKind, + { + onOpenArticle: (id) => openArticle(id), + onCloseDrawer: opts.mode === "drawer" ? opts.onBack : undefined, + }, + highlightGlossaryKey, + ); + + const nodes: Array = [ + h( + "div", + { class: "wiki-article-header" }, + h( + "div", + { class: "spread", style: { gap: "8px", flexWrap: "wrap" } }, + h("span", { class: "badge info" }, article.category), + h( + "div", + { class: "row", style: { gap: "6px", flexWrap: "wrap" } }, + ...article.relatedScreens.map((rs) => + h( + "button", + { + class: "btn xs ghost", + onClick: () => { + if (opts.mode === "drawer") opts.onBack(); + navigate(rs.screen); + }, + }, + `${rs.label} →`, + ), + ), + ), + ), + h("h2", { style: { marginTop: "8px" } }, article.title), + h( + "p", + { + class: "dim", + style: { fontSize: "13px", lineHeight: "1.55", marginTop: "6px" }, + }, + article.summary, + ), + ), + h( + "div", + { class: "wiki-callout" }, + h( + "span", + { class: "badge ok", style: { flexShrink: "0" } }, + "COACH ULTRACAT", + ), + h( + "span", + { style: { fontSize: "12px", lineHeight: "1.5" } }, + article.coachTip, + ), + ), + ...article.sections.map((sec) => + h( + "section", + { class: "wiki-section panel" }, + h("h3", { class: "accent" }, sec.heading), + ...sec.paragraphs.map((p) => h("p", { class: "wiki-prose" }, p)), + sec.formula ? h("div", { class: "wiki-formula" }, sec.formula) : null, + sec.bullets?.length + ? h( + "ul", + { class: "wiki-bullets" }, + ...sec.bullets.map((b) => h("li", {}, b)), + ) + : null, + ), + ), + labEl, + article.wikipediaRefs.length + ? h( + "section", + { class: "wiki-refs-section" }, + h( + "div", + { class: "spread", style: { marginBottom: "8px" } }, + h("h3", { class: "accent" }, "Further Reading on Wikipedia ↗"), + h( + "span", + { class: "mono faint", style: { fontSize: "10px" } }, + "External reference links open in a new tab", + ), + ), + h( + "div", + { class: "wiki-ref-grid" }, + ...article.wikipediaRefs.map((ref) => + h( + "a", + { + class: "wiki-ref-card", + href: ref.url, + target: "_blank", + rel: "noopener noreferrer", + }, + h( + "div", + { class: "spread", style: { gap: "6px" } }, + h( + "strong", + { class: "mono brand", style: { fontSize: "12px" } }, + ref.title, + ), + h("span", { class: "badge info" }, "WIKIPEDIA ↗"), + ), + h( + "p", + { + class: "dim", + style: { + fontSize: "11px", + lineHeight: "1.45", + marginTop: "4px", + }, + }, + ref.summary, + ), + ), + ), + ), + ) + : null, + h( + "div", + { class: "spread wiki-footer-nav" }, + prevArt + ? h( + "button", + { class: "btn sm ghost", onClick: () => openArticle(prevArt.id) }, + `← ${prevArt.shortTitle}`, + ) + : h("span"), + nextArt + ? h( + "button", + { + class: "btn sm primary", + onClick: () => openArticle(nextArt.id), + }, + `${nextArt.shortTitle} →`, + ) + : h("span"), + ), + ]; + mainEl.append(...nodes.filter((n): n is Node => n !== null)); + } + + syncWalkthroughBtn(); + renderSidebarAndResults(); + renderArticleBody(); + + const topbar = h( + "header", + { class: "wiki-topbar" }, + h( + "div", + { class: "row", style: { gap: "10px" } }, + h("button", { class: "btn sm", onClick: opts.onBack }, opts.backLabel), + h("h2", {}, "Flight Wiki & Interactive Tutorial"), + ), + h( + "div", + { class: "row wiki-topbar-controls", style: { gap: "8px" } }, + searchInput, + h( + "button", + { + class: "btn xs", + onClick: () => openArticle("my-vehicle-inspector"), + }, + "My Rocket Inspector", + ), + walkthroughBtn, + ), + ); + + clear(container); + container.append( + topbar, + h("div", { class: "wiki-layout" }, sidebarEl, mainEl), + ); +} diff --git a/src/server/ai/runner.ts b/src/server/ai/runner.ts index 88b3628..b389e6e 100644 --- a/src/server/ai/runner.ts +++ b/src/server/ai/runner.ts @@ -100,16 +100,13 @@ function estimateAiMissionEconomics( ((validation.compliance.waivedCount ?? 0) === 0 ? 0.04 : 0), ) + gradeBonusRate; const grossPayout = Math.round(budget * (0.65 + effBonusRate)); - const scienceBonus = Math.round( - budget * ((bus?.scienceBonusPct ?? 0) / 100), - ); + const scienceBonus = Math.round(budget * ((bus?.scienceBonusPct ?? 0) / 100)); const canRecover = (contract.isReusable || (agency.unlockedTechs ?? []).includes("methalox-reusable")) && validation.dvMargin >= 450 && (!!design.stages?.[0]?.hasFins || (design.stages?.length ?? 0) >= 2); - const stage0Cost = - asm.stages?.[0]?.stageCost ?? Math.round(totalCost * 0.55); + const stage0Cost = asm.stages?.[0]?.stageCost ?? Math.round(totalCost * 0.55); const reusabilityBonus = canRecover ? Math.round(stage0Cost * 0.28) : 0; const successCash = grossPayout + scienceBonus + reusabilityBonus; @@ -121,11 +118,9 @@ function estimateAiMissionEconomics( const padRepairExpected = exempt ? 0 : Math.round( - (6_000_000 + Math.min(8_000_000, Math.round(totalCost * 0.22))) * - 0.45, + (6_000_000 + Math.min(8_000_000, Math.round(totalCost * 0.22))) * 0.45, ); - const crewInquiryExpected = - contract.crewed && !exempt ? 10_000_000 : 0; + const crewInquiryExpected = contract.crewed && !exempt ? 10_000_000 : 0; const failureCash = insurancePayout - breachPenalty - padRepairExpected - crewInquiryExpected; @@ -135,8 +130,7 @@ function estimateAiMissionEconomics( Math.min(0.97, 0.88 + skill * 0.08 - anomalyRiskPct / 140), ); const expectedCash = Math.round( - successProbability * successCash + - (1 - successProbability) * failureCash, + successProbability * successCash + (1 - successProbability) * failureCash, ); const abandonCost = Math.round(budget * 0.35) + Math.round(budget * profile.breachFineRate); @@ -204,8 +198,7 @@ function chooseContractForAi(agency: AgencyState): ContractOffer | null { const estCost = estimateAiMissionCost(agency, offer); const estMargin = expectedContractPayout(offer) - estCost; let score = - offer.budget / 1e6 + - Math.max(-25, Math.min(25, estMargin / 1e6)) * 0.5; + offer.budget / 1e6 + Math.max(-25, Math.min(25, estMargin / 1e6)) * 0.5; if (!feasible) { score -= 1000; } diff --git a/src/server/hazards.ts b/src/server/hazards.ts index e64ddb6..22fdcae 100644 --- a/src/server/hazards.ts +++ b/src/server/hazards.ts @@ -138,7 +138,10 @@ export function ensureHazards(simTime: number): void { } const prevActiveIds = (world.activeHazards ?? []).map((h) => h.id).join(","); const active = eventsForEpoch(curEpoch); - const upcoming = [...eventsForEpoch(curEpoch + 1), ...eventsForEpoch(curEpoch + 2)]; + const upcoming = [ + ...eventsForEpoch(curEpoch + 1), + ...eventsForEpoch(curEpoch + 2), + ]; world.activeHazards = active; world.upcomingHazards = upcoming; world.hazardEpoch = curEpoch; diff --git a/src/server/routes/agencyRoutes.ts b/src/server/routes/agencyRoutes.ts index 2b49c6a..8a90552 100644 --- a/src/server/routes/agencyRoutes.ts +++ b/src/server/routes/agencyRoutes.ts @@ -127,11 +127,9 @@ export function registerAgencyRoutes(router: Router): void { return; } if (agency.treasury >= 25_000_000 && !agency.bankrupt) { - res - .status(400) - .json({ - error: "Agency is solvent and ineligible for emergency bailout.", - }); + res.status(400).json({ + error: "Agency is solvent and ineligible for emergency bailout.", + }); return; } const sponsor = SPONSORS.find((s) => s.id === agency.sponsorId); @@ -260,12 +258,10 @@ export function registerAgencyRoutes(router: Router): void { const rawDesign = (req.body?.design as RocketDesign | undefined) ?? agency.rocketDesign; if (!rawDesign?.stages?.length) { - res - .status(400) - .json({ - error: - "Build and save a rocket design before running a static fire test.", - }); + res.status(400).json({ + error: + "Build and save a rocket design before running a static fire test.", + }); return; } try { diff --git a/src/server/routes/contractRoutes.ts b/src/server/routes/contractRoutes.ts index 0f4cf3b..7dd5568 100644 --- a/src/server/routes/contractRoutes.ts +++ b/src/server/routes/contractRoutes.ts @@ -36,11 +36,9 @@ export function registerContractRoutes(router: Router): void { agency.activeContract || (agency.activeMissions ?? []).some((m) => !m.settled) ) { - res - .status(409) - .json({ - error: "Already has an active contract. Complete it first.", - }); + res.status(409).json({ + error: "Already has an active contract. Complete it first.", + }); return; } if (agency.missionId) clearActiveContract(agency); @@ -83,11 +81,9 @@ export function registerContractRoutes(router: Router): void { agency.activeContract || (agency.activeMissions ?? []).some((m) => !m.settled) ) { - res - .status(409) - .json({ - error: "Already has an active contract. Complete it first.", - }); + res.status(409).json({ + error: "Already has an active contract. Complete it first.", + }); return; } if (agency.missionId) clearActiveContract(agency); diff --git a/src/server/routes/missionRoutes.ts b/src/server/routes/missionRoutes.ts index 058f822..2df495b 100644 --- a/src/server/routes/missionRoutes.ts +++ b/src/server/routes/missionRoutes.ts @@ -30,11 +30,9 @@ export function registerMissionRoutes(router: Router): void { if (!dryRun) { testFee = Math.max(120_000, Math.round(assembly.totalCost * 0.015)); if (agency.treasury < testFee) { - res - .status(400) - .json({ - error: `Insufficient funds for test flight ($${(testFee / 1e6).toFixed(2)}M needed).`, - }); + res.status(400).json({ + error: `Insufficient funds for test flight ($${(testFee / 1e6).toFixed(2)}M needed).`, + }); return; } agency.treasury -= testFee; @@ -91,12 +89,10 @@ export function registerMissionRoutes(router: Router): void { return; } if (agency.bankrupt) { - res - .status(409) - .json({ - error: - "Agency is bankrupt. Accept a Sponsor Restructuring Grant or Reset Agency first.", - }); + res.status(409).json({ + error: + "Agency is bankrupt. Accept a Sponsor Restructuring Grant or Reset Agency first.", + }); return; } const nowSim = getSimTime(); @@ -115,11 +111,9 @@ export function registerMissionRoutes(router: Router): void { return; } if ((agency.activeMissions ?? []).some((m) => !m.settled)) { - res - .status(409) - .json({ - error: "A mission is already in flight. Wait for settlement.", - }); + res.status(409).json({ + error: "A mission is already in flight. Wait for settlement.", + }); return; } const contract = resolveContract(agency); @@ -149,11 +143,9 @@ export function registerMissionRoutes(router: Router): void { design.maturity = "flight-ready"; } if (design.maturity !== "flight-ready") { - res - .status(400) - .json({ - error: `Design maturity is ${design.maturity.toUpperCase()}; advance to FLIGHT-READY in Rocket Builder.`, - }); + res.status(400).json({ + error: `Design maturity is ${design.maturity.toUpperCase()}; advance to FLIGHT-READY in Rocket Builder.`, + }); return; } const insurancePremium = diff --git a/src/shared/compliance.ts b/src/shared/compliance.ts index ce5e876..063ca9b 100644 --- a/src/shared/compliance.ts +++ b/src/shared/compliance.ts @@ -1,3 +1,7 @@ -// Export compliance evaluation entry point and context interface. +// Export compliance evaluation entry point, context interface, and read-only rule metadata. export type { ComplianceEvalContext } from "./compliance/context.js"; -export { evaluateCompliance } from "./compliance/evaluate.js"; +export { + COMPLIANCE_RULES_META, + type ComplianceRuleMeta, + evaluateCompliance, +} from "./compliance/evaluate.js"; diff --git a/src/shared/compliance/evaluate.ts b/src/shared/compliance/evaluate.ts index 911f5b6..cb13d5d 100644 --- a/src/shared/compliance/evaluate.ts +++ b/src/shared/compliance/evaluate.ts @@ -5,6 +5,8 @@ import type { MaturityLevel, RocketAssembly, RocketDesign, + RuleCategory, + RuleSeverity, } from "../types.js"; import type { ComplianceEvalContext, RuleDef } from "./context.js"; import { PROPULSION_RULES } from "./propulsionRules.js"; @@ -19,6 +21,30 @@ const RULES: RuleDef[] = [ ...CREW_ORBITAL_RULES, ]; +export interface ComplianceRuleMeta { + id: string; + code: string; + category: RuleCategory; + title: string; + description: string; + severity: RuleSeverity; + dynamicSeverity: boolean; + waiverCost: number; + riskPenaltyPct: number; +} + +export const COMPLIANCE_RULES_META: ComplianceRuleMeta[] = RULES.map((r) => ({ + id: r.id, + code: r.code, + category: r.category, + title: r.title, + description: r.description, + severity: r.severity, + dynamicSeverity: !!r.getSeverity, + waiverCost: r.waiverCost, + riskPenaltyPct: r.riskPenaltyPct, +})); + export function evaluateCompliance( design: RocketDesign, assembly: RocketAssembly,