Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(assembly): ship the Machine Atlas, two working machines generated from code with no model files
nirholas52c9f3e4bacc
diff --git a/pages/assembly.html b/pages/assembly.htmlnew file mode 100644index 000000000..7319bc236--- /dev/null+++ b/pages/assembly.html@@ -0,0 +1,182 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>Machine Atlas · Machines generated from code, not model files · three.ws</title>+ <meta+ name="description"+ content="Two working machines with no 3D model files behind them. A radial aero engine and a steam locomotive, generated in your browser from a handful of dimensions, with solved motion, explode views, live parameters and a GLB export."+ />+ <link rel="canonical" href="https://three.ws/assembly" />+ <meta property="og:type" content="website" />+ <meta property="og:title" content="Machine Atlas · three.ws" />+ <meta+ property="og:description"+ content="No model files. A radial aero engine and a steam locomotive built at runtime from dimensions, profiles and geometry functions, with solved linkages you can take apart."+ />+ <meta property="og:url" content="https://three.ws/assembly" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=labs&t=Machine+Atlas&d=Two+working+machines+generated+in+the+browser+from+code%3A+no+3D+model+files%2C+solved+linkages%2C+live+parameters%2C+GLB+export.&p=%2Fassembly" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Machine Atlas · three.ws" />+ <meta+ name="twitter:description"+ content="A radial engine and a steam locomotive, generated at runtime from dimensions and profiles. Move a slider and the geometry is rebuilt."+ />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=labs&t=Machine+Atlas&d=Two+working+machines+generated+in+the+browser+from+code%3A+no+3D+model+files%2C+solved+linkages%2C+live+parameters%2C+GLB+export.&p=%2Fassembly" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Machine Atlas — three.ws" />+ <meta name="twitter:site" content="@trythreews" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <link rel="stylesheet" href="/src/assembly.css" />+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Machine Atlas","description":"Two working machines generated in the browser from code: no 3D model files, solved linkages, live parameters, GLB export.","url":"https://three.ws/assembly","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=labs&t=Machine+Atlas&d=Two+working+machines+generated+in+the+browser+from+code%3A+no+3D+model+files%2C+solved+linkages%2C+live+parameters%2C+GLB+export.&p=%2Fassembly"}]}</script>+</head>+<body class="ma-body">+ <header class="site-header"><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="ma-stage" id="maStage">+ <div class="ma-canvas" id="maCanvas"></div>+ <div class="ma-label" id="maLabel" hidden></div>+ <div class="ma-loading" aria-hidden="true">+ <span></span><span></span><span></span>+ <p>Generating geometry</p>+ </div>++ <div class="ma-topbar">+ <div class="ma-brand">+ <span class="ma-mark" aria-hidden="true"></span>+ <span class="ma-brand-text">+ <strong>Machine Atlas</strong>+ <em>Interactive collection · no model files</em>+ </span>+ </div>+ <div class="ma-tabs" id="maTabs" role="group" aria-label="Machine"></div>+ </div>++ <section class="ma-intro">+ <p class="ma-kicker">Two machines. Two eras. Zero assets.</p>+ <h1 id="maName">Radial Nine</h1>+ <p class="ma-subtitle" id="maSubtitle">Air-cooled radial aero engine</p>+ <p class="ma-blurb" id="maBlurb"></p>+ <ul class="ma-facts" id="maFacts"></ul>+ <div class="ma-parts-wrap">+ <h2 class="ma-panel-title">Subassemblies</h2>+ <div class="ma-parts" id="maParts"></div>+ </div>+ </section>++ <aside class="ma-panel" aria-label="Dimensions">+ <header class="ma-panel-head">+ <h2 class="ma-panel-title">Dimensions</h2>+ <button type="button" class="ma-ghost-btn" id="maReset">Reset</button>+ </header>+ <div class="ma-params" id="maParams"></div>+ <h2 class="ma-panel-title ma-panel-title-sep">Derived</h2>+ <ul class="ma-readout" id="maReadout"></ul>+ <div class="ma-actions">+ <button type="button" class="ma-btn" id="maExport">Export GLB</button>+ <button type="button" class="ma-btn" id="maFrame">Save frame</button>+ <button type="button" class="ma-btn" id="maSpec">Copy spec</button>+ <button type="button" class="ma-btn" id="maLink">Copy link</button>+ <button type="button" class="ma-btn ma-btn-accent" id="maShare">Share on X</button>+ </div>+ </aside>++ <div class="ma-dock">+ <button type="button" class="ma-play" id="maPlay" aria-pressed="true">+ <span class="ma-play-icon" aria-hidden="true"></span>+ <span class="ma-play-text">+ <em>Motion</em>+ <strong class="ma-play-label">Running</strong>+ </span>+ </button>+ <label class="ma-slider">+ <span>Shaft speed</span>+ <input type="range" id="maSpeed" min="0" max="2.4" step="0.01" value="0.55" />+ <output id="maSpeedOut">0.55 rev/s</output>+ </label>+ <label class="ma-slider">+ <span>Explode</span>+ <input type="range" id="maExplode" min="0" max="1" step="0.01" value="0" />+ <output>E</output>+ </label>+ <button type="button" class="ma-toggle" id="maStructure" aria-pressed="false">Structure</button>+ <button type="button" class="ma-toggle" id="maSourceToggle" aria-expanded="false">Source</button>+ <dl class="ma-stats">+ <div><dt>Parts</dt><dd id="maStatParts">0</dd></div>+ <div><dt>Triangles</dt><dd id="maStatTris">0</dd></div>+ <div><dt>FPS</dt><dd id="maStatFps">60</dd></div>+ </dl>+ </div>++ <aside class="ma-source" aria-label="Generating code">+ <h2 class="ma-panel-title">The calls behind this frame</h2>+ <p class="ma-source-note">+ Generated from the values on the right, so it always matches what is on screen.+ </p>+ <div class="ma-code" id="maCode"></div>+ </aside>++ <p class="ma-hint">Drag to orbit · scroll to zoom · hover a part to name it · space, E and S</p>+ <div class="ma-toast" id="maToast" role="status" hidden></div>+ </main>++ <section class="ma-explain">+ <div class="ma-explain-grid">+ <article>+ <h2>Nothing here was downloaded</h2>+ <p>+ Both machines are built when the page loads. Dimensions become profiles, profiles get+ revolved or extruded, and the results are merged into the parts you can see. A cylinder+ barrel is one revolved sawtooth, a rail is one closed cross-section swept down the track,+ and a propeller blade is a stack of NACA sections lofted with twist.+ </p>+ </article>+ <article>+ <h2>The motion is solved, not keyframed</h2>+ <p>+ Pistons come from the exact planar slider-crank. The valve gear closes a four-bar chain by+ intersecting circles every frame. That is why a longer rod visibly dwells at top dead+ centre, and why a rod length that cannot physically reach refuses to move rather than+ stretching.+ </p>+ </article>+ <article>+ <h2>A spec an agent can write</h2>+ <p>+ Every machine is a small JSON object of numbers. Copy the spec, hand it to an agent, get a+ different machine back. Export the result as GLB and it drops straight into an avatar+ scene, a product page, or the glTF viewer.+ </p>+ </article>+ </div>+ <div class="ma-next">+ <a class="ma-next-card" href="/create">+ <strong>Generate a 3D model</strong>+ <span>Describe an object in words and get a textured GLB back.</span>+ </a>+ <a class="ma-next-card" href="/viewer">+ <strong>glTF / GLB viewer</strong>+ <span>Drop the export in and inspect materials, meshes and animations.</span>+ </a>+ <a class="ma-next-card" href="/labs">+ <strong>Labs</strong>+ <span>The rest of the experiments running live on three.ws.</span>+ </a>+ </div>+ </section>++ <script type="module" src="/src/assembly.js"></script>+ <script type="module" src="/i18n.js"></script>+</body>+</html>diff --git a/src/assembly.css b/src/assembly.cssnew file mode 100644index 000000000..958357320--- /dev/null+++ b/src/assembly.css@@ -0,0 +1,823 @@+/* Machine Atlas (/assembly).+ The stage is one full-height canvas with panels floating over it. Everything+ below the fold is ordinary page flow, so the surface reads as a document that+ happens to open with a machine rather than as an app that swallowed a page. */++.ma-body {+ margin: 0;+ background: var(--bg-0);+ color: var(--ink);+ font-family: var(--font-body);+}++.ma-stage {+ position: relative;+ height: calc(100svh - 57px);+ min-height: 560px;+ overflow: hidden;+ isolation: isolate;+ --ma-panel: color-mix(in srgb, var(--bg-1) 74%, transparent);+ --ma-edge: var(--stroke);+}++.ma-canvas {+ position: absolute;+ inset: 0;+ cursor: grab;+}+.ma-canvas:active {+ cursor: grabbing;+}+.ma-canvas canvas {+ display: block;+ width: 100%;+ height: 100%;+ opacity: 0;+ transition: opacity 0.6s ease;+}+.ma-stage.is-ready .ma-canvas canvas {+ opacity: 1;+}++/* Loading state: three bars that settle, replaced the instant the first frame+ lands. It says "building" rather than "downloading", which is the truth. */+.ma-loading {+ position: absolute;+ inset: 0;+ display: grid;+ place-content: center;+ gap: var(--space-sm);+ justify-items: center;+ color: var(--ink-faint);+ font: 500 0.72rem/1 var(--font-mono);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ transition: opacity 0.4s ease;+}+.ma-loading span {+ position: absolute;+ width: 46px;+ height: 2px;+ background: var(--ink-faint);+ transform-origin: left center;+ animation: ma-build 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;+}+.ma-loading span:nth-child(1) { top: calc(50% - 16px); }+.ma-loading span:nth-child(2) { top: 50%; animation-delay: 0.14s; }+.ma-loading span:nth-child(3) { top: calc(50% + 16px); animation-delay: 0.28s; }+.ma-loading p { margin: 46px 0 0; }+@keyframes ma-build {+ 0% { transform: scaleX(0.06); opacity: 0.25; }+ 55% { transform: scaleX(1); opacity: 0.85; }+ 100% { transform: scaleX(0.06); opacity: 0.25; }+}+.ma-stage.is-ready .ma-loading {+ opacity: 0;+ pointer-events: none;+}++/* ── top bar ─────────────────────────────────────────────────────────── */++.ma-topbar {+ position: absolute;+ inset: var(--space-md) var(--space-lg) auto;+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: var(--space-md);+ pointer-events: none;+}+.ma-topbar > * { pointer-events: auto; }++.ma-brand {+ display: flex;+ align-items: center;+ gap: var(--space-sm);+}+.ma-mark {+ width: 26px;+ height: 26px;+ border: 1px solid var(--ink-faint);+ border-radius: 3px;+ position: relative;+ flex: none;+}+.ma-mark::before,+.ma-mark::after {+ content: '';+ position: absolute;+ background: var(--ink-faint);+}+.ma-mark::before { inset: 6px 6px auto; height: 1px; }+.ma-mark::after { inset: 6px auto 6px 50%; width: 1px; }++.ma-brand-text {+ display: grid;+ line-height: 1.25;+}+.ma-brand-text strong {+ font: 600 0.78rem/1.2 var(--font-display);+ letter-spacing: 0.16em;+ text-transform: uppercase;+ color: var(--ink-bright);+}+.ma-brand-text em {+ font: 400 0.66rem/1.3 var(--font-mono);+ font-style: normal;+ letter-spacing: 0.06em;+ color: var(--ink-faint);+}++.ma-tabs {+ display: flex;+ gap: var(--space-3xs);+ padding: var(--space-3xs);+ border: 1px solid var(--ma-edge);+ border-radius: var(--radius-md);+ background: var(--ma-panel);+ backdrop-filter: blur(18px) saturate(140%);+ -webkit-backdrop-filter: blur(18px) saturate(140%);+}+.ma-tab {+ display: grid;+ grid-template-columns: auto auto;+ align-items: baseline;+ gap: 0 var(--space-2xs);+ padding: var(--space-2xs) var(--space-sm);+ border: 0;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--ink-dim);+ cursor: pointer;+ text-align: left;+ transition: background 0.18s ease, color 0.18s ease;+}+.ma-tab-no {+ grid-row: 1 / span 2;+ font: 500 0.62rem/1 var(--font-mono);+ color: var(--ink-faint);+}+.ma-tab-name { font: 600 0.82rem/1.25 var(--font-display); }+.ma-tab-era {+ grid-column: 2;+ font: 400 0.62rem/1.2 var(--font-mono);+ color: var(--ink-faint);+ letter-spacing: 0.08em;+}+.ma-tab:hover { background: var(--surface-1); color: var(--ink); }+.ma-tab[aria-pressed='true'] {+ background: var(--surface-2);+ color: var(--ink-bright);+}+.ma-tab[aria-pressed='true'] .ma-tab-no { color: var(--ink); }+.ma-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++/* ── intro column ────────────────────────────────────────────────────── */++.ma-intro {+ position: absolute;+ left: var(--space-lg);+ top: calc(var(--space-md) + 62px);+ width: min(23rem, 34vw);+ display: grid;+ gap: var(--space-xs);+ pointer-events: none;+}+.ma-intro > * { pointer-events: auto; }++.ma-kicker {+ margin: 0;+ font: 500 0.66rem/1.3 var(--font-mono);+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--ink-faint);+}+.ma-intro h1 {+ margin: 0;+ font: 600 clamp(1.9rem, 3.2vw, 2.9rem) / 1.02 var(--font-display);+ letter-spacing: -0.02em;+ color: var(--ink-bright);+}+.ma-subtitle {+ margin: 0;+ font: 400 0.86rem/1.4 var(--font-body);+ color: var(--ink-dim);+}+.ma-blurb {+ margin: var(--space-2xs) 0 0;+ max-width: 30ch;+ font: 400 0.82rem/1.6 var(--font-body);+ color: var(--ink-dim);+}++.ma-facts {+ list-style: none;+ margin: var(--space-xs) 0 0;+ padding: 0;+ display: grid;+ gap: var(--space-3xs);+ max-width: 30ch;+}+.ma-facts li {+ display: flex;+ justify-content: space-between;+ gap: var(--space-sm);+ padding: var(--space-2xs) 0;+ border-bottom: 1px solid var(--stroke);+ font: 400 0.72rem/1.4 var(--font-mono);+}+.ma-facts span { color: var(--ink-faint); white-space: nowrap; }+.ma-facts strong { color: var(--ink); font-weight: 500; text-align: right; }++.ma-parts-wrap { margin-top: var(--space-md); }+.ma-panel-title {+ margin: 0 0 var(--space-xs);+ font: 500 0.64rem/1 var(--font-mono);+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--ink-faint);+}+.ma-panel-title-sep { margin-top: var(--space-md); }++.ma-parts {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-3xs);+}+.ma-part {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2xs);+ padding: var(--space-3xs) var(--space-xs);+ border: 1px solid var(--ma-edge);+ border-radius: var(--radius-pill);+ background: var(--ma-panel);+ color: var(--ink-dim);+ font: 500 0.7rem/1.4 var(--font-body);+ cursor: pointer;+ transition: color 0.16s ease, border-color 0.16s ease, opacity 0.16s ease;+}+.ma-part:hover { color: var(--ink-bright); border-color: var(--stroke-strong); }+.ma-part:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.ma-part[aria-pressed='false'] { opacity: 0.42; }+.ma-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--ink);+ flex: none;+}+.ma-part[aria-pressed='false'] .ma-dot { background: transparent; box-shadow: inset 0 0 0 1px var(--ink-faint); }+.ma-part-n { color: var(--ink-faint); font-family: var(--font-mono); font-size: 0.66rem; }++/* ── dimensions panel ────────────────────────────────────────────────── */++.ma-panel {+ position: absolute;+ right: var(--space-lg);+ top: calc(var(--space-md) + 62px);+ width: min(19rem, 30vw);+ max-height: calc(100% - 200px);+ overflow-y: auto;+ overscroll-behavior: contain;+ padding: var(--space-md);+ border: 1px solid var(--ma-edge);+ border-radius: var(--radius-lg);+ background: var(--ma-panel);+ backdrop-filter: blur(20px) saturate(140%);+ -webkit-backdrop-filter: blur(20px) saturate(140%);+}+.ma-panel-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-sm);+}+.ma-ghost-btn {+ border: 0;+ background: transparent;+ color: var(--ink-faint);+ font: 500 0.68rem/1 var(--font-body);+ padding: var(--space-3xs) var(--space-2xs);+ border-radius: var(--radius-sm);+ cursor: pointer;+ transition: color 0.16s ease, background 0.16s ease;+}+.ma-ghost-btn:hover { color: var(--ink-bright); background: var(--surface-1); }+.ma-ghost-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++.ma-params { display: grid; gap: var(--space-sm); }+.ma-param {+ display: grid;+ grid-template-columns: 1fr auto;+ gap: var(--space-3xs) var(--space-sm);+ align-items: baseline;+}+.ma-param label {+ font: 400 0.76rem/1.3 var(--font-body);+ color: var(--ink-dim);+}+.ma-param output {+ font: 500 0.72rem/1.3 var(--font-mono);+ color: var(--ink-bright);+ font-variant-numeric: tabular-nums;+}+.ma-param input[type='range'] { grid-column: 1 / -1; }++input[type='range'] {+ -webkit-appearance: none;+ appearance: none;+ width: 100%;+ height: 18px;+ background: transparent;+ cursor: pointer;+ margin: 0;+}+input[type='range']::-webkit-slider-runnable-track {+ height: 2px;+ background: var(--stroke-strong);+ border-radius: 2px;+}+input[type='range']::-moz-range-track {+ height: 2px;+ background: var(--stroke-strong);+ border-radius: 2px;+}+input[type='range']::-webkit-slider-thumb {+ -webkit-appearance: none;+ appearance: none;+ width: 12px;+ height: 12px;+ margin-top: -5px;+ border-radius: 50%;+ background: var(--ink-bright);+ border: 0;+ transition: transform 0.14s ease, box-shadow 0.14s ease;+}+input[type='range']::-moz-range-thumb {+ width: 12px;+ height: 12px;+ border-radius: 50%;+ background: var(--ink-bright);+ border: 0;+}+input[type='range']:hover::-webkit-slider-thumb { transform: scale(1.18); }+input[type='range']:focus-visible::-webkit-slider-thumb {+ box-shadow: 0 0 0 3px var(--accent-soft);+}++.ma-readout {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: var(--space-3xs);+}+.ma-readout li {+ display: flex;+ justify-content: space-between;+ gap: var(--space-sm);+ font: 400 0.72rem/1.5 var(--font-mono);+ font-variant-numeric: tabular-nums;+}+.ma-readout span { color: var(--ink-faint); }+.ma-readout strong { color: var(--ink); font-weight: 500; }++.ma-actions {+ margin-top: var(--space-md);+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2xs);+}+.ma-btn {+ flex: 1 1 auto;+ padding: var(--space-2xs) var(--space-sm);+ border: 1px solid var(--ma-edge);+ border-radius: var(--radius-sm);+ background: var(--surface-1);+ color: var(--ink);+ font: 500 0.74rem/1.4 var(--font-body);+ cursor: pointer;+ transition: background 0.16s ease, color 0.16s ease, border-color 0.16s ease;+ white-space: nowrap;+}+.ma-btn:hover { background: var(--surface-2); color: var(--ink-bright); border-color: var(--stroke-strong); }+.ma-btn:active { transform: translateY(1px); }+.ma-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.ma-btn:disabled { opacity: 0.5; cursor: progress; }+.ma-btn[data-busy]::after {+ content: '';+ display: inline-block;+ width: 8px;+ height: 8px;+ margin-left: 6px;+ border-radius: 50%;+ border: 1px solid currentColor;+ border-top-color: transparent;+ animation: ma-spin 0.7s linear infinite;+ vertical-align: -1px;+}+@keyframes ma-spin { to { transform: rotate(360deg); } }+.ma-btn-accent {+ background: var(--ink-bright);+ color: var(--bg-0);+ border-color: transparent;+}+.ma-btn-accent:hover { background: var(--ink); color: var(--bg-0); }++/* ── dock ────────────────────────────────────────────────────────────── */++.ma-dock {+ position: absolute;+ left: 50%;+ bottom: var(--space-md);+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: var(--space-md);+ padding: var(--space-2xs) var(--space-md);+ border: 1px solid var(--ma-edge);+ border-radius: var(--radius-lg);+ background: var(--ma-panel);+ backdrop-filter: blur(20px) saturate(140%);+ -webkit-backdrop-filter: blur(20px) saturate(140%);+ max-width: calc(100% - var(--space-lg) * 2);+}++.ma-play {+ display: flex;+ align-items: center;+ gap: var(--space-xs);+ padding: var(--space-2xs);+ border: 0;+ border-radius: var(--radius-md);+ background: transparent;+ color: var(--ink);+ cursor: pointer;+}+.ma-play:hover { background: var(--surface-1); }+.ma-play:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.ma-play-icon {+ width: 26px;+ height: 26px;+ border-radius: 50%;+ border: 1px solid var(--stroke-strong);+ position: relative;+ flex: none;+}+.ma-play-icon::before,+.ma-play-icon::after {+ content: '';+ position: absolute;+ top: 50%;+ width: 2px;+ height: 9px;+ background: var(--ink);+ transform: translateY(-50%);+}+.ma-play-icon::before { left: 9px; }+.ma-play-icon::after { right: 9px; }+.ma-play[aria-pressed='false'] .ma-play-icon::before {+ left: 9px;+ width: 0;+ height: 0;+ border-left: 8px solid var(--ink);+ border-top: 5px solid transparent;+ border-bottom: 5px solid transparent;+ background: transparent;+}+.ma-play[aria-pressed='false'] .ma-play-icon::after { display: none; }+.ma-play-text { display: grid; text-align: left; line-height: 1.2; }+.ma-play-text em {+ font: 400 0.6rem/1.2 var(--font-mono);+ font-style: normal;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--ink-faint);+}+.ma-play-text strong { font: 500 0.78rem/1.2 var(--font-body); color: var(--ink-bright); }++.ma-slider {+ display: grid;+ grid-template-columns: 1fr auto;+ align-items: center;+ gap: 0 var(--space-sm);+ min-width: 8.5rem;+}+.ma-slider > span {+ font: 400 0.6rem/1.2 var(--font-mono);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--ink-faint);+}+.ma-slider > output {+ font: 500 0.68rem/1.2 var(--font-mono);+ color: var(--ink);+ font-variant-numeric: tabular-nums;+ text-align: right;+}+.ma-slider input { grid-column: 1 / -1; }++.ma-toggle {+ padding: var(--space-2xs) var(--space-sm);+ border: 1px solid var(--ma-edge);+ border-radius: var(--radius-pill);+ background: transparent;+ color: var(--ink-dim);+ font: 500 0.72rem/1.4 var(--font-body);+ cursor: pointer;+ white-space: nowrap;+ transition: background 0.16s ease, color 0.16s ease;+}+.ma-toggle:hover { color: var(--ink-bright); background: var(--surface-1); }+.ma-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.ma-toggle[aria-pressed='true'],+.ma-toggle[aria-expanded='true'] {+ background: var(--ink-bright);+ color: var(--bg-0);+ border-color: transparent;+}++.ma-stats {+ display: flex;+ gap: var(--space-md);+ margin: 0;+ padding-left: var(--space-md);+ border-left: 1px solid var(--stroke);+}+.ma-stats div { display: grid; }+.ma-stats dt {+ font: 400 0.58rem/1.2 var(--font-mono);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--ink-faint);+}+.ma-stats dd {+ margin: 0;+ font: 500 0.8rem/1.2 var(--font-mono);+ color: var(--ink-bright);+ font-variant-numeric: tabular-nums;+}++/* ── source drawer ───────────────────────────────────────────────────── */++.ma-source {+ position: absolute;+ left: var(--space-lg);+ bottom: calc(var(--space-md) + 4.6rem);+ width: min(26rem, 40vw);+ max-height: min(52%, 26rem);+ overflow-y: auto;+ overscroll-behavior: contain;+ padding: var(--space-md);+ border: 1px solid var(--ma-edge);+ border-radius: var(--radius-lg);+ background: var(--ma-panel);+ backdrop-filter: blur(20px) saturate(140%);+ -webkit-backdrop-filter: blur(20px) saturate(140%);+ opacity: 0;+ transform: translateY(12px);+ pointer-events: none;+ transition: opacity 0.24s ease, transform 0.24s ease;+}+.ma-source-open .ma-source {+ opacity: 1;+ transform: none;+ pointer-events: auto;+}+.ma-source-open .ma-intro .ma-parts-wrap { display: none; }+.ma-source-note {+ margin: 0 0 var(--space-sm);+ font: 400 0.72rem/1.5 var(--font-body);+ color: var(--ink-dim);+}+.ma-code { display: grid; gap: var(--space-sm); }+.ma-code-block { margin: 0; }+.ma-code-block figcaption {+ font: 500 0.64rem/1 var(--font-mono);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--ink-faint);+ margin-bottom: var(--space-3xs);+}+.ma-code-block pre {+ margin: 0;+ padding: var(--space-sm);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm);+ background: var(--surface-1);+ overflow-x: auto;+ font: 400 0.7rem/1.55 var(--font-mono);+ color: var(--ink);+ white-space: pre;+}++/* ── overlays ────────────────────────────────────────────────────────── */++.ma-label {+ position: absolute;+ top: 0;+ left: 0;+ display: grid;+ gap: 1px;+ padding: var(--space-3xs) var(--space-xs);+ border: 1px solid var(--on-scrim-stroke);+ border-radius: var(--radius-sm);+ background: var(--scrim-strong);+ pointer-events: none;+ z-index: 3;+}+.ma-label strong { font: 500 0.72rem/1.3 var(--font-body); color: var(--on-scrim-bright); }+.ma-label span {+ font: 400 0.6rem/1.2 var(--font-mono);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--on-scrim-dim);+}++.ma-hint {+ position: absolute;+ right: var(--space-lg);+ bottom: var(--space-sm);+ margin: 0;+ font: 400 0.62rem/1.3 var(--font-mono);+ letter-spacing: 0.06em;+ color: var(--ink-faint);+ pointer-events: none;+}++.ma-toast {+ position: absolute;+ left: 50%;+ bottom: calc(var(--space-md) + 88px);+ transform: translateX(-50%);+ padding: var(--space-2xs) var(--space-md);+ border-radius: var(--radius-pill);+ background: var(--ink-bright);+ color: var(--bg-0);+ font: 500 0.76rem/1.4 var(--font-body);+ z-index: 4;+ animation: ma-toast-in 0.24s ease;+}+@keyframes ma-toast-in {+ from { opacity: 0; transform: translate(-50%, 8px); }+ to { opacity: 1; transform: translate(-50%, 0); }+}++/* ── below the fold ──────────────────────────────────────────────────── */++.ma-explain {+ max-width: 1180px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg) var(--space-2xl);+ display: grid;+ gap: var(--space-xl);+}+.ma-explain-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(17rem, 1fr));+ gap: var(--space-lg);+}+.ma-explain h2 {+ margin: 0 0 var(--space-xs);+ font: 600 1.05rem/1.3 var(--font-display);+ color: var(--ink-bright);+}+.ma-explain p {+ margin: 0;+ font: 400 0.88rem/1.65 var(--font-body);+ color: var(--ink-dim);+}+.ma-next {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));+ gap: var(--space-sm);+}+.ma-next-card {+ display: grid;+ gap: var(--space-3xs);+ padding: var(--space-md);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ text-decoration: none;+ transition: border-color 0.18s ease, transform 0.18s ease, background 0.18s ease;+}+.ma-next-card:hover {+ border-color: var(--stroke-strong);+ background: var(--surface-2);+ transform: translateY(-2px);+}+.ma-next-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.ma-next-card strong { font: 600 0.92rem/1.3 var(--font-display); color: var(--ink-bright); }+.ma-next-card span { font: 400 0.8rem/1.5 var(--font-body); color: var(--ink-dim); }++/* ── responsive ──────────────────────────────────────────────────────── */++@media (max-width: 1180px) {+ .ma-intro { width: min(19rem, 40vw); }+ .ma-panel { width: min(16.5rem, 34vw); }+ .ma-source { width: min(22rem, 46vw); }+ .ma-hint { display: none; }+}++@media (max-width: 900px) {+ /* The stage stops being a viewport-sized canvas with panels floating on it+ and becomes an ordinary column: canvas first, then the panels, with the+ transport docked to the bottom of the window where a thumb can reach it. */+ .ma-stage {+ display: block;+ height: auto;+ min-height: 0;+ overflow: visible;+ padding-bottom: 7rem;+ }+ .ma-canvas {+ position: relative;+ inset: auto;+ height: 58svh;+ min-height: 340px;+ }+ .ma-loading {+ height: 58svh;+ min-height: 340px;+ inset: 0 0 auto;+ }+ .ma-topbar {+ inset: var(--space-sm) var(--space-md) auto;+ align-items: center;+ }+ .ma-brand-text em { display: none; }+ .ma-intro,+ .ma-panel,+ .ma-source {+ position: static;+ width: auto;+ max-width: none;+ max-height: none;+ margin: var(--space-lg) var(--space-md) 0;+ opacity: 1;+ transform: none;+ pointer-events: auto;+ overflow: visible;+ backdrop-filter: none;+ -webkit-backdrop-filter: none;+ }+ .ma-intro { display: grid; }+ .ma-source { display: none; }+ .ma-source-open .ma-source { display: block; }+ .ma-source-open .ma-intro .ma-parts-wrap { display: block; }+ .ma-blurb,+ .ma-facts { max-width: none; }+ .ma-dock {+ position: fixed;+ left: 0;+ right: 0;+ bottom: 0;+ transform: none;+ max-width: none;+ border-radius: 0;+ border-left: 0;+ border-right: 0;+ border-bottom: 0;+ padding: var(--space-2xs) var(--space-md) calc(var(--space-2xs) + env(safe-area-inset-bottom));+ gap: var(--space-sm);+ flex-wrap: wrap;+ z-index: 5;+ }+ .ma-play { flex: 0 0 auto; }+ .ma-slider { flex: 1 1 7rem; min-width: 6.5rem; }+ .ma-toggle { flex: 0 0 auto; }+ .ma-stats {+ flex: 1 1 100%;+ order: 5;+ justify-content: space-between;+ padding-left: 0;+ border-left: 0;+ border-top: 1px solid var(--stroke);+ padding-top: var(--space-3xs);+ }+ .ma-label { display: none; }+ .ma-hint { display: none; }+ .ma-toast { position: fixed; bottom: 7.5rem; }+ .ma-explain { padding-top: var(--space-xl); }+}++@media (max-width: 520px) {+ .ma-canvas,+ .ma-loading { height: 50svh; min-height: 280px; }+ .ma-tab-era { display: none; }+ .ma-tab { padding: var(--space-2xs) var(--space-xs); }+ .ma-btn { flex: 1 1 42%; }+ .ma-stats { gap: var(--space-sm); }+ .ma-stage { padding-bottom: 8.5rem; }+ .ma-toast { bottom: 9rem; }+}++@media (prefers-reduced-motion: reduce) {+ .ma-canvas canvas,+ .ma-next-card,+ .ma-source,+ .ma-btn { transition: none; }+ .ma-loading span { animation: none; transform: scaleX(1); }+}diff --git a/src/assembly.js b/src/assembly.jsnew file mode 100644index 000000000..e4ab7f611--- /dev/null+++ b/src/assembly.js@@ -0,0 +1,659 @@+// Machine Atlas (/assembly): two working machines with no model files behind+// them. Both are generated from their parameters when the page loads, and+// regenerated whenever a slider moves, so what you see is always the geometry+// those numbers describe. The motion is solved from the same dimensions rather+// than played back.+//+// Structure:+// src/assembly/parts.js profiles, revolves, extrusions, lofts+// src/assembly/rig.js explode runtime and the linkage solvers+// src/assembly/materials.js one palette shared by every machine+// src/assembly/*.js one module per machine++import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import * as radial from './assembly/radial-engine.js';+import * as locomotive from './assembly/locomotive.js';+import { applyExplode, groupsOf, setGroupVisible } from './assembly/rig.js';+import { disposeTree, ghostMaterial } from './assembly/materials.js';+import { triangleCount } from './assembly/parts.js';+import { track, ANALYTICS_EVENTS } from './analytics.js';++const MACHINES = [radial, locomotive];+const byId = new Map(MACHINES.map((m) => [m.spec.id, m]));+const $ = (id) => document.getElementById(id);++const state = {+ machine: null,+ values: {},+ built: null,+ angle: 0,+ speed: 0.55,+ playing: true,+ explode: 0,+ explodeTarget: 0,+ structure: false,+ hidden: new Set(),+};++/* ── renderer ───────────────────────────────────────────────────────── */++const host = $('maCanvas');+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false, preserveDrawingBuffer: true });+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+renderer.outputColorSpace = THREE.SRGBColorSpace;+renderer.toneMapping = THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure = 1.05;+renderer.shadowMap.enabled = true;+renderer.shadowMap.type = THREE.PCFShadowMap;+host.appendChild(renderer.domElement);++const scene = new THREE.Scene();+const camera = new THREE.PerspectiveCamera(38, 1, 0.05, 400);+const controls = new OrbitControls(camera, renderer.domElement);+controls.enableDamping = true;+controls.dampingFactor = 0.07;+controls.minDistance = 0.6;+controls.maxDistance = 60;+controls.maxPolarAngle = Math.PI * 0.495;++const pmrem = new THREE.PMREMGenerator(renderer);+scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++const key = new THREE.DirectionalLight(0xffffff, 2.1);+key.position.set(4.2, 6.4, 3.6);+key.castShadow = true;+key.shadow.mapSize.set(2048, 2048);+key.shadow.bias = -0.0012;+key.shadow.normalBias = 0.02;+scene.add(key);+const rim = new THREE.DirectionalLight(0x9fc4ff, 0.7);+rim.position.set(-5, 2.4, -4.5);+scene.add(rim);+scene.add(new THREE.AmbientLight(0xffffff, 0.35));++const shadowPlane = new THREE.Mesh(+ new THREE.PlaneGeometry(80, 80),+ new THREE.ShadowMaterial({ opacity: 0.3 }),+);+shadowPlane.rotation.x = -Math.PI / 2;+shadowPlane.receiveShadow = true;+scene.add(shadowPlane);++// The stage follows the site theme instead of pinning one background, so the+// atlas does not glare in light mode or wash out in dark.+function applyTheme() {+ const light = document.documentElement.getAttribute('data-theme') === 'light';+ const bg = light ? 0xeceef0 : 0x0c0d0f;+ scene.background = new THREE.Color(bg);+ scene.fog = new THREE.Fog(bg, 14, 46);+ shadowPlane.material.opacity = light ? 0.22 : 0.34;+}+applyTheme();+new MutationObserver(applyTheme).observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['data-theme'],+});++function resize() {+ const w = host.clientWidth || 1;+ const h = host.clientHeight || 1;+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+}+new ResizeObserver(resize).observe(host);+resize();++/* ── build and rebuild ──────────────────────────────────────────────── */++let current = null;++// Fit the machine in frame. `keepDirection` preserves whatever angle the user+// has orbited to and changes only the distance, which is what a refit after an+// explode should do: the view is theirs, the framing is ours.+function frameMachine(spec, root, { animate = false, keepDirection = false, explode = null } = {}) {+ const restore = explode !== null && explode !== state.explode;+ if (restore) applyExplode(root, explode);+ // Frame the machine, not the scenery. The locomotive's track runs well past+ // both ends of it; including that would push the camera into the next county.+ const box = new THREE.Box3();+ const ground = new THREE.Box3().setFromObject(root);+ root.traverse((o) => {+ if (!o.isMesh || !o.visible) return;+ if (o.userData.group === 'track') return;+ box.expandByObject(o);+ });+ if (restore) applyExplode(root, state.explode);+ if (box.isEmpty()) box.copy(ground);+ const size = box.getSize(new THREE.Vector3());+ const centre = box.getCenter(new THREE.Vector3());+ const radiusOf = Math.max(size.x, size.y, size.z) * 0.5;+ // Fit the bounding sphere in the vertical field of view, with room to spare+ // so a propeller tip or a chimney never touches the frame edge.+ const dist = (radiusOf / Math.sin(THREE.MathUtils.degToRad(camera.fov * 0.5))) * 1.16;+ const dir = keepDirection+ ? camera.position.clone().sub(controls.target).normalize()+ : new THREE.Vector3(...spec.camera.position).normalize();+ const target = new THREE.Vector3(centre.x, centre.y * 0.9, centre.z);+ const eye = target.clone().addScaledVector(dir, dist);+ if (animate) {+ tweenCamera(eye, target);+ } else {+ camera.position.copy(eye);+ controls.target.copy(target);+ controls.update();+ }+ shadowPlane.position.y = ground.min.y + 0.002;+}++let tween = null;+function tweenCamera(eye, target) {+ tween = {+ fromEye: camera.position.clone(),+ fromTarget: controls.target.clone(),+ eye,+ target,+ t: 0,+ };+}++// `frame` decides what happens to the camera: 'reset' flies to the machine's+// signature angle, 'keep' leaves the user exactly where they were. Dragging a+// dimension slider rebuilds geometry many times a second, and snapping the+// camera back on each rebuild would make the sliders unusable.+function build(machineId, values, { frame = 'keep' } = {}) {+ const machine = byId.get(machineId);+ if (!machine) return;+ if (current) {+ scene.remove(current.root);+ disposeTree(current.root);+ }+ const built = machine.build(values);+ scene.add(built.root);+ current = built;+ state.machine = machine;+ state.built = built;+ built.update(state.angle);+ applyExplode(built.root, state.explode);+ for (const g of state.hidden) setGroupVisible(built.root, g, false);+ if (state.structure) setStructure(true);+ if (frame === 'reset') frameMachine(machine.spec, built.root, { animate: true });+ else frameMachine(machine.spec, built.root, { keepDirection: true, animate: false, explode: null, ...(frame === 'hold' ? {} : {}) });+ renderStats();+ renderParts();+ renderCode();+ renderReadout();+}++/* ── structure view ─────────────────────────────────────────────────── */++const ghost = ghostMaterial();+function setStructure(on) {+ state.structure = on;+ if (!current) return;+ current.root.traverse((o) => {+ if (!o.isMesh) return;+ if (on) {+ if (!o.userData.solidMaterial) o.userData.solidMaterial = o.material;+ o.material = ghost;+ o.castShadow = false;+ } else if (o.userData.solidMaterial) {+ o.material = o.userData.solidMaterial;+ o.castShadow = true;+ }+ });+ $('maStructure').setAttribute('aria-pressed', String(on));+}++/* ── url state ──────────────────────────────────────────────────────── */++function readUrl() {+ const q = new URLSearchParams(location.search);+ const id = q.get('m');+ const machine = byId.get(id) || MACHINES[0];+ const values = {};+ for (const p of machine.spec.params) {+ const raw = q.get(p.key);+ const n = raw === null ? p.value : Number(raw);+ values[p.key] = Number.isFinite(n) ? clampStep(n, p) : p.value;+ }+ return { machine, values };+}++// Snap to the slider's own grid, which starts at `min` and not at zero. Off by+// one step is the difference between a nine-cylinder radial and a ten.+function clampStep(n, p) {+ const clamped = Math.min(p.max, Math.max(p.min, n));+ const snapped = p.min + Math.round((clamped - p.min) / p.step) * p.step;+ return Number(snapped.toFixed(4));+}++function writeUrl() {+ const q = new URLSearchParams();+ q.set('m', state.machine.spec.id);+ for (const p of state.machine.spec.params) {+ const v = state.values[p.key];+ if (v !== p.value) q.set(p.key, String(v));+ }+ const url = `${location.pathname}?${q.toString()}`;+ history.replaceState(null, '', url);+ return new URL(url, location.origin).toString();+}++/* ── panels ─────────────────────────────────────────────────────────── */++function renderTabs() {+ const wrap = $('maTabs');+ wrap.innerHTML = '';+ for (const m of MACHINES) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'ma-tab';+ b.setAttribute('aria-pressed', String(m === state.machine));+ b.innerHTML = `<span class="ma-tab-no">${String(MACHINES.indexOf(m) + 1).padStart(2, '0')}</span><span class="ma-tab-name">${m.spec.name}</span><span class="ma-tab-era">${m.spec.era}</span>`;+ b.addEventListener('click', () => selectMachine(m.spec.id));+ wrap.appendChild(b);+ }+}++function renderHeader() {+ const s = state.machine.spec;+ $('maName').textContent = s.name;+ $('maSubtitle').textContent = s.subtitle;+ $('maBlurb').textContent = s.blurb;+ const facts = $('maFacts');+ facts.innerHTML = '';+ for (const [k, v] of s.facts) {+ const li = document.createElement('li');+ li.innerHTML = `<span>${k}</span><strong>${v}</strong>`;+ facts.appendChild(li);+ }+}++function renderParams() {+ const wrap = $('maParams');+ wrap.innerHTML = '';+ for (const p of state.machine.spec.params) {+ const row = document.createElement('div');+ row.className = 'ma-param';+ const id = `ma-p-${p.key}`;+ row.innerHTML = `+ <label for="${id}">${p.label}</label>+ <output id="${id}-out">${format(state.values[p.key], p)}</output>+ <input id="${id}" type="range" min="${p.min}" max="${p.max}" step="${p.step}" value="${state.values[p.key]}" />`;+ const input = row.querySelector('input');+ const out = row.querySelector('output');+ input.addEventListener('input', () => {+ state.values[p.key] = Number(input.value);+ out.textContent = format(state.values[p.key], p);+ scheduleRebuild();+ });+ input.addEventListener('change', () => {+ track(ANALYTICS_EVENTS.CTA_CLICKED, { cta: `assembly_param_${p.key}`, location: 'assembly' });+ });+ wrap.appendChild(row);+ }+}++function format(v, p) {+ const n = p.step < 1 ? v.toFixed(2) : String(Math.round(v));+ return p.unit ? `${n} ${p.unit}`.trim() : n;+}++let rebuildQueued = false;+let lastRebuild = 0;+function scheduleRebuild() {+ if (rebuildQueued) return;+ rebuildQueued = true;+ const wait = Math.max(0, 70 - (performance.now() - lastRebuild));+ setTimeout(() => {+ rebuildQueued = false;+ lastRebuild = performance.now();+ build(state.machine.spec.id, state.values);+ writeUrl();+ }, wait);+}++function renderReadout() {+ const wrap = $('maReadout');+ wrap.innerHTML = '';+ for (const [k, v] of current.readout) {+ const li = document.createElement('li');+ li.innerHTML = `<span>${k}</span><strong>${v}</strong>`;+ wrap.appendChild(li);+ }+}++function renderParts() {+ const wrap = $('maParts');+ wrap.innerHTML = '';+ const counts = new Map();+ current.root.traverse((o) => {+ if (!o.isMesh) return;+ const g = o.userData.group || 'frame';+ counts.set(g, (counts.get(g) || 0) + 1);+ });+ for (const g of groupsOf(current.root)) {+ if (!counts.has(g)) continue;+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'ma-part';+ const on = !state.hidden.has(g);+ b.setAttribute('aria-pressed', String(on));+ b.innerHTML = `<span class="ma-dot" aria-hidden="true"></span><span class="ma-part-name">${g}</span><span class="ma-part-n">${counts.get(g)}</span>`;+ b.addEventListener('click', () => {+ const nowOn = state.hidden.has(g);+ if (nowOn) state.hidden.delete(g);+ else state.hidden.add(g);+ setGroupVisible(current.root, g, nowOn);+ b.setAttribute('aria-pressed', String(nowOn));+ renderStats();+ });+ wrap.appendChild(b);+ }+}++function renderCode() {+ const wrap = $('maCode');+ wrap.innerHTML = '';+ for (const { label, code } of state.machine.codeFor(state.values)) {+ const block = document.createElement('figure');+ block.className = 'ma-code-block';+ const cap = document.createElement('figcaption');+ cap.textContent = label;+ const pre = document.createElement('pre');+ pre.textContent = code;+ block.append(cap, pre);+ wrap.appendChild(block);+ }+}++function renderStats() {+ let meshes = 0;+ current.root.traverse((o) => {+ if (o.isMesh && o.visible) meshes++;+ });+ $('maStatParts').textContent = String(meshes);+ $('maStatTris').textContent = formatCount(triangleCount(current.root));+}++function formatCount(n) {+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;+ return String(Math.round(n));+}++function selectMachine(id) {+ if (state.machine && state.machine.spec.id === id) return;+ const machine = byId.get(id);+ state.values = {};+ for (const p of machine.spec.params) state.values[p.key] = p.value;+ state.hidden.clear();+ state.angle = 0;+ build(id, state.values, { animate: true });+ renderTabs();+ renderHeader();+ renderParams();+ writeUrl();+ track(ANALYTICS_EVENTS.SURFACE_OPENED, { surface: `visualizer:assembly:${id}` });+}++/* ── hover inspection ───────────────────────────────────────────────── */++const ray = new THREE.Raycaster();+const pointer = new THREE.Vector2();+const label = $('maLabel');+let hovered = null;++host.addEventListener('pointermove', (e) => {+ const r = host.getBoundingClientRect();+ pointer.x = ((e.clientX - r.left) / r.width) * 2 - 1;+ pointer.y = -((e.clientY - r.top) / r.height) * 2 + 1;+ label.style.transform = `translate(${e.clientX - r.left + 14}px, ${e.clientY - r.top + 14}px)`;+ pickPending = true;+});+host.addEventListener('pointerleave', () => {+ setHovered(null);+ pickPending = false;+});++let pickPending = false;+function pick() {+ if (!current) return;+ ray.setFromCamera(pointer, camera);+ const hit = ray.intersectObject(current.root, true).find((h) => h.object.visible);+ setHovered(hit ? hit.object : null);+}++function setHovered(obj) {+ if (obj === hovered) return;+ if (hovered && hovered.userData.hoverMaterial) {+ hovered.material = hovered.userData.hoverMaterial;+ hovered.userData.hoverMaterial = null;+ }+ hovered = obj;+ if (!obj) {+ label.hidden = true;+ return;+ }+ if (!state.structure) {+ obj.userData.hoverMaterial = obj.material;+ const m = obj.material.clone();+ m.emissive = new THREE.Color(0x2f6fff);+ m.emissiveIntensity = 0.55;+ obj.material = m;+ }+ label.hidden = false;+ label.innerHTML = `<strong>${obj.name}</strong><span>${obj.userData.group || 'frame'}</span>`;+}++/* ── actions ────────────────────────────────────────────────────────── */++function toast(message) {+ const el = $('maToast');+ el.textContent = message;+ el.hidden = false;+ clearTimeout(toast.timer);+ toast.timer = setTimeout(() => {+ el.hidden = true;+ }, 2600);+}++async function copy(text, message) {+ try {+ await navigator.clipboard.writeText(text);+ toast(message);+ } catch {+ const ta = document.createElement('textarea');+ ta.value = text;+ document.body.appendChild(ta);+ ta.select();+ document.execCommand('copy');+ ta.remove();+ toast(message);+ }+}++function specJson() {+ return JSON.stringify(+ {+ machine: state.machine.spec.id,+ name: state.machine.spec.name,+ units: 'mm and count, as labelled',+ params: state.values,+ },+ null,+ 2,+ );+}++function download(blob, filename) {+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ setTimeout(() => URL.revokeObjectURL(url), 4000);+}++async function exportGlb() {+ const btn = $('maExport');+ btn.disabled = true;+ btn.dataset.busy = '1';+ try {+ const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');+ const exporter = new GLTFExporter();+ const buffer = await exporter.parseAsync(current.root, { binary: true, onlyVisible: true });+ download(new Blob([buffer], { type: 'model/gltf-binary' }), `${state.machine.spec.id}.glb`);+ toast('GLB exported. Drop it on /viewer to inspect it.');+ track(ANALYTICS_EVENTS.CTA_CLICKED, { cta: 'assembly_export_glb', location: 'assembly' });+ } catch (err) {+ toast(`Export failed: ${err && err.message ? err.message : 'unknown error'}`);+ } finally {+ btn.disabled = false;+ delete btn.dataset.busy;+ }+}++function saveFrame() {+ const w = host.clientWidth;+ const h = host.clientHeight;+ const ratio = renderer.getPixelRatio();+ renderer.setPixelRatio(Math.min(3, ratio * 2));+ renderer.setSize(w, h, false);+ renderer.render(scene, camera);+ renderer.domElement.toBlob((blob) => {+ if (blob) download(blob, `${state.machine.spec.id}-frame.png`);+ renderer.setPixelRatio(ratio);+ resize();+ }, 'image/png');+ track(ANALYTICS_EVENTS.CTA_CLICKED, { cta: 'assembly_save_frame', location: 'assembly' });+}++function share() {+ const url = writeUrl();+ const text = `${state.machine.spec.name}: no model file, generated in the browser from ${state.machine.spec.params.length} numbers.`;+ const intent = `https://x.com/intent/post?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`;+ window.open(intent, '_blank', 'noopener');+ track(ANALYTICS_EVENTS.CTA_CLICKED, { cta: 'assembly_share', location: 'assembly' });+}++/* ── transport ──────────────────────────────────────────────────────── */++function setPlaying(on) {+ state.playing = on;+ const b = $('maPlay');+ b.setAttribute('aria-pressed', String(on));+ b.querySelector('.ma-play-label').textContent = on ? 'Running' : 'Held';+}++function wire() {+ $('maPlay').addEventListener('click', () => setPlaying(!state.playing));+ $('maSpeed').addEventListener('input', (e) => {+ state.speed = Number(e.target.value);+ $('maSpeedOut').textContent = `${state.speed.toFixed(2)} rev/s`;+ });+ $('maExplode').addEventListener('input', (e) => {+ state.explodeTarget = Number(e.target.value);+ });+ $('maStructure').addEventListener('click', () => setStructure(!state.structure));+ $('maReset').addEventListener('click', () => {+ for (const p of state.machine.spec.params) state.values[p.key] = p.value;+ renderParams();+ build(state.machine.spec.id, state.values, { animate: true });+ writeUrl();+ toast('Back to the reference dimensions.');+ });+ $('maExport').addEventListener('click', exportGlb);+ $('maFrame').addEventListener('click', saveFrame);+ $('maSpec').addEventListener('click', () => copy(specJson(), 'Spec JSON copied.'));+ $('maLink').addEventListener('click', () => copy(writeUrl(), 'Shareable link copied.'));+ $('maShare').addEventListener('click', share);+ $('maSourceToggle').addEventListener('click', () => {+ const open = document.body.classList.toggle('ma-source-open');+ $('maSourceToggle').setAttribute('aria-expanded', String(open));+ });+ addEventListener('keydown', (e) => {+ if (e.target instanceof HTMLInputElement) return;+ if (e.key === ' ') {+ e.preventDefault();+ setPlaying(!state.playing);+ } else if (e.key === 'e' || e.key === 'E') {+ state.explodeTarget = state.explodeTarget > 0.5 ? 0 : 1;+ $('maExplode').value = String(state.explodeTarget);+ } else if (e.key === 's' || e.key === 'S') {+ setStructure(!state.structure);+ } else if (e.key >= '1' && e.key <= String(MACHINES.length)) {+ selectMachine(MACHINES[Number(e.key) - 1].spec.id);+ }+ });+}++/* ── loop ───────────────────────────────────────────────────────────── */++const timer = new THREE.Timer();+let frames = 0;+let fpsAt = performance.now();++function loop() {+ requestAnimationFrame(loop);+ timer.update();+ const dt = Math.min(timer.getDelta(), 0.05);++ if (state.playing) {+ state.angle += dt * state.speed * Math.PI * 2;+ current.update(state.angle);+ }++ if (Math.abs(state.explode - state.explodeTarget) > 0.0005) {+ state.explode += (state.explodeTarget - state.explode) * Math.min(1, dt * 7);+ applyExplode(current.root, state.explode);+ } else if (state.explode !== state.explodeTarget) {+ state.explode = state.explodeTarget;+ applyExplode(current.root, state.explode);+ } else if (state.playing) {+ applyExplode(current.root, state.explode);+ }++ if (tween) {+ tween.t = Math.min(1, tween.t + dt * 1.6);+ const k = 1 - (1 - tween.t) ** 3;+ camera.position.lerpVectors(tween.fromEye, tween.eye, k);+ controls.target.lerpVectors(tween.fromTarget, tween.target, k);+ if (tween.t >= 1) tween = null;+ }++ if (pickPending) {+ pickPending = false;+ pick();+ }++ controls.update();+ renderer.render(scene, camera);++ frames++;+ const now = performance.now();+ if (now - fpsAt > 500) {+ $('maStatFps').textContent = String(Math.round((frames * 1000) / (now - fpsAt)));+ frames = 0;+ fpsAt = now;+ }+}++/* ── boot ───────────────────────────────────────────────────────────── */++const start = readUrl();+state.machine = start.machine;+state.values = start.values;+renderTabs();+renderHeader();+renderParams();+wire();+build(start.machine.spec.id, start.values);+setPlaying(true);+$('maSpeedOut').textContent = `${state.speed.toFixed(2)} rev/s`;+$('maStage').classList.add('is-ready');+track(ANALYTICS_EVENTS.SURFACE_OPENED, { surface: `visualizer:assembly:${start.machine.spec.id}` });+loop();diff --git a/src/assembly/locomotive.js b/src/assembly/locomotive.jsnew file mode 100644index 000000000..9ea15d70b--- /dev/null+++ b/src/assembly/locomotive.js@@ -0,0 +1,757 @@+// Machine 02: a narrow-gauge-era steam locomotive, generated from six numbers.+//+// The interesting half of a locomotive is the half that moves, so that is the+// half that is solved rather than posed. Coupled wheels share one crank angle;+// the crosshead is the exact slider-crank solution for the main rod; and the+// valve gear is a real four-bar chain, closed every frame by circle+// intersection (rig.js `circleIntersect`).+//+// One detail falls out of the maths rather than out of a reference photo: the+// return crank has to be nearly as long as the main crank and set well past a+// right angle, because the eccentric throw the valve gear needs is the vector+// sum of the two, and that sum has to be small. Change `RETURN_CRANK_ANGLE`+// and the valve motion changes the way it would on the real engine.++import * as THREE from 'three';+import {+ lathe,+ roundedBox,+ rodGeometry,+ arcSector,+ railGeometry,+ spokedWheel,+ bentPipe,+ boltRing,+ mergeGeometries,+} from './parts.js';+import { MATERIALS } from './materials.js';+import { part, joint, placeLink, slideOnLine, circleIntersect } from './rig.js';++const GAUGE = 1.435;+const RETURN_CRANK_RATIO = 0.9;+const RETURN_CRANK_ANGLE = 145;++export const spec = {+ id: 'locomotive',+ name: 'Coupled Six',+ subtitle: 'Outside-cylinder steam locomotive',+ era: '1901',+ blurb:+ 'Coupled drivers, outside cylinders and a full return-crank valve gear. The linkage is closed by solving circles every frame, so every rod length you set below has to physically work.',+ facts: [+ ['Gauge', '1435 mm standard'],+ ['Valve gear', 'Return crank, eccentric rod, rocking lever'],+ ['Motion', 'Solved four-bar chain, not baked animation'],+ ],+ params: [+ { key: 'drivers', label: 'Coupled axles', min: 2, max: 5, step: 1, value: 3, unit: '' },+ { key: 'driverDia', label: 'Driver diameter', min: 1200, max: 2100, step: 10, value: 1680, unit: 'mm' },+ { key: 'spacing', label: 'Axle spacing', min: 1900, max: 2900, step: 10, value: 2350, unit: 'mm' },+ { key: 'stroke', label: 'Piston stroke', min: 460, max: 800, step: 10, value: 610, unit: 'mm' },+ { key: 'boilerDia', label: 'Boiler diameter', min: 1200, max: 1900, step: 10, value: 1520, unit: 'mm' },+ { key: 'spokes', label: 'Spokes per wheel', min: 10, max: 24, step: 1, value: 18, unit: '' },+ ],+ camera: { position: [5.4, 2.6, 6.6], target: [0.4, 0.7, 0], radius: 8.4 },+};++export function derive(v) {+ const R = v.driverDia / 2000;+ const s = v.spacing / 1000;+ const crankR = v.stroke / 2000;+ const n = v.drivers;+ const axles = [];+ for (let j = 0; j < n; j++) axles.push((j - (n - 1) / 2) * s);+ const mainIndex = Math.min(n - 1, Math.floor(n / 2));+ const mainX = axles[mainIndex];+ const yC = R * 0.1;+ const mainRod = s * 1.28;+ const crossMax = mainX + crankR + Math.sqrt(Math.max(mainRod * mainRod - yC * yC, 0));+ const cylRear = crossMax + 0.22;+ const cylLen = crankR * 2 + 0.62;+ const boilerR = v.boilerDia / 2000;+ const yB = R * 1.08 + boilerR;+ const zMotion = GAUGE / 2 + 0.16;+ const zWheel = GAUGE / 2;+ const rE = crankR * RETURN_CRANK_RATIO;+ const psi = THREE.MathUtils.degToRad(RETURN_CRANK_ANGLE);+ // The eccentric the valve gear actually sees: the vector sum of main crank+ // and return crank, which rotates with the wheel at a constant radius.+ const rho = Math.hypot(crankR + rE * Math.cos(psi), rE * Math.sin(psi));+ const rockPivot = new THREE.Vector2(mainX + s * 0.72, yC + R * 0.62);+ const armLow = Math.max(R * 0.3, rho * 1.5);+ const armHigh = R * 0.3;+ const eccRod = Math.hypot(rockPivot.x - mainX, rockPivot.y);+ return {+ R,+ s,+ n,+ crankR,+ axles,+ mainIndex,+ mainX,+ yC,+ mainRod,+ crossMax,+ cylRear,+ cylLen,+ cylFront: cylRear + cylLen,+ boilerR,+ yB,+ zMotion,+ zWheel,+ rE,+ psi,+ rho,+ rockPivot,+ armLow,+ armHigh,+ eccRod,+ yValve: yC + R * 0.56,+ valveLink: R * 0.9,+ // The crankpin radius IS half the piston stroke. Deriving it from the+ // wheel instead would let the stroke slider lie about what it controls.+ pinR: crankR,+ rear: axles[0] - s * 0.62,+ cabBack: axles[0] - s * 0.95,+ wheelbase: axles[n - 1] - axles[0],+ };+}++export function codeFor(v) {+ const d = derive(v);+ const f = (n) => n.toFixed(3);+ return [+ {+ label: 'Driving wheel',+ code: `spokedWheel({+ radius: ${f(d.R)},+ spokes: ${v.spokes},+ crankRadius: ${f(d.pinR)},+ counterweight: true,+})`,+ },+ {+ label: 'Coupled axles',+ code: `const axles = [${d.axles.map((x) => f(x)).join(', ')}];+// every coupled wheel shares one crank angle, so the+// side rod stays horizontal and simply orbits+placeLink(sideRod, pin(axles[0]), pin(axles.at(-1)));`,+ },+ {+ label: 'Crosshead',+ code: `// exact slider-crank on the cylinder centreline+const pin = crankpin(theta, ${f(d.pinR)});+const cross = slideOnLine(pin, ${f(d.yC)}, ${f(d.mainRod)});`,+ },+ {+ label: 'Valve gear',+ code: `// close the four-bar: eccentric rod meets rocking lever+const low = circleIntersect(+ eccentricPin, ${f(d.eccRod)},+ pivot, ${f(d.armLow)}, branch);+const top = pivot.clone().sub(+ low.clone().sub(pivot).setLength(${f(d.armHigh)}));`,+ },+ {+ label: 'Rail section',+ code: `// head, web and foot as one closed profile,+// extruded along the track+railGeometry(${f(d.s * (d.n + 3))}, 1)`,+ },+ ];+}++const SLEEPER_PITCH = 0.62;++function trackGroup(d) {+ const g = new THREE.Group();+ g.name = 'track';+ const length = d.s * (d.n + 3.4) + 6;+ const railY = -d.R;+ for (const z of [-GAUGE / 2, GAUGE / 2]) {+ const rail = railGeometry(length, 1);+ rail.translate(0, railY - 0.185, z);+ g.add(part(rail, MATERIALS.steel, { name: 'rail', group: 'track' }));+ }+ const sleepers = [];+ const pitch = SLEEPER_PITCH;+ const count = Math.floor(length / pitch);+ for (let i = 0; i < count; i++) {+ const x = -length / 2 + (i + 0.5) * pitch;+ const sl = roundedBox(0.26, 0.16, 2.6, 0.02, false);+ sl.translate(x, railY - 0.27, 0);+ sleepers.push(sl);+ }+ g.add(part(mergeGeometries(sleepers), MATERIALS.timber, { name: 'sleepers', group: 'track' }));+ const ballast = roundedBox(length, 0.2, 3.6, 0.04, false);+ ballast.translate(0, railY - 0.45, 0);+ g.add(part(ballast, MATERIALS.ballast, { name: 'ballast', group: 'track' }));+ return g;+}++// Bar frame: one plate per side, with the axle openings cut out of the profile+// rather than modelled as separate blocks.+function frameGeometry(d) {+ const front = d.cylFront - 0.1;+ const back = d.cabBack;+ const top = d.R * 0.34;+ const bottom = -d.R * 0.62;+ const s = new THREE.Shape();+ s.moveTo(back, bottom);+ s.lineTo(front, bottom);+ s.lineTo(front, top);+ s.lineTo(back, top);+ s.closePath();+ for (const x of d.axles) {+ const hole = new THREE.Path();+ hole.absarc(x, -d.R * 0.16, d.R * 0.2, 0, Math.PI * 2, true);+ s.holes.push(hole);+ }+ const g = new THREE.ExtrudeGeometry(s, { depth: 0.05, bevelEnabled: false, curveSegments: 20 });+ g.translate(0, 0, -0.025);+ g.computeVertexNormals();+ return g;+}++function boilerGroup(d, v) {+ const g = new THREE.Group();+ g.name = 'boiler';+ const grp = 'boiler';+ const r = d.boilerR;+ const smokeboxFront = d.cylFront - 0.08;+ const fireboxBack = d.axles[0] - d.s * 0.34;+ // One turned profile from the smokebox door to the firebox throat.+ const barrel = lathe(+ [+ [0, fireboxBack], [r * 1.02, fireboxBack], [r * 1.02, fireboxBack + 0.12],+ [r * 0.98, fireboxBack + 0.14], [r * 0.98, smokeboxFront - 1.05],+ [r * 1.04, smokeboxFront - 1.02], [r * 1.04, smokeboxFront - 0.08],+ [r * 0.96, smokeboxFront - 0.01], [r * 0.6, smokeboxFront + 0.03],+ [0, smokeboxFront + 0.05],+ ],+ 56,+ );+ barrel.rotateZ(-Math.PI / 2);+ barrel.translate(0, d.yB, 0);+ g.add(part(barrel, MATERIALS.paintDark, { name: 'boiler barrel', group: grp, explode: new THREE.Vector3(0, 1.5, 0) }));++ // Bands, dome, safety valves and chimney: all revolves on the same axis.+ const bands = [];+ for (let i = 0; i < 4; i++) {+ const x = fireboxBack + 0.5 + i * ((smokeboxFront - 1.6 - fireboxBack) / 3);+ const b = new THREE.CylinderGeometry(r * 1.005, r * 1.005, 0.05, 48);+ b.rotateZ(Math.PI / 2);+ b.translate(x, d.yB, 0);+ bands.push(b);+ }+ g.add(part(mergeGeometries(bands), MATERIALS.brass, { name: 'boiler bands', group: grp, explode: new THREE.Vector3(0, 1.9, 0) }));++ // These three stand upright on the boiler, and `lathe` already revolves about+ // +Y, so they need no reorientation at all.+ const domeX = fireboxBack + (smokeboxFront - fireboxBack) * 0.42;+ const dome = lathe(+ [+ [0, 0], [r * 0.34, 0], [r * 0.36, 0.16], [r * 0.33, 0.32],+ [r * 0.24, 0.4], [r * 0.1, 0.42], [0, 0.42],+ ],+ 36,+ );+ dome.translate(domeX, d.yB + r * 0.93, 0);+ g.add(part(dome, MATERIALS.brass, { name: 'steam dome', group: grp, explode: new THREE.Vector3(0, 2.4, 0) }));++ const stack = lathe(+ [+ [0, 0], [r * 0.28, 0], [r * 0.26, 0.06], [r * 0.2, 0.2],+ [r * 0.2, 0.44], [r * 0.3, 0.5], [r * 0.31, 0.58], [r * 0.22, 0.58],+ [r * 0.13, 0.5], [0, 0.5],+ ],+ 36,+ );+ stack.translate(smokeboxFront - 0.55, d.yB + r * 0.9, 0);+ g.add(part(stack, MATERIALS.graphite, { name: 'chimney', group: grp, explode: new THREE.Vector3(0, 2.7, 0) }));++ const safety = [];+ for (const z of [-0.16, 0.16]) {+ const sv = lathe([[0, 0], [0.06, 0], [0.058, 0.14], [0.075, 0.16], [0.03, 0.2], [0, 0.2]], 20);+ sv.translate(fireboxBack + 0.45, d.yB + r * 0.94, z);+ safety.push(sv);+ }+ g.add(part(mergeGeometries(safety), MATERIALS.brass, { name: 'safety valves', group: grp, explode: new THREE.Vector3(0, 2.5, 0) }));++ // Handrails: bent pipe, not a stretched cylinder.+ for (const z of [-1, 1]) {+ const pts = [+ new THREE.Vector3(smokeboxFront - 0.02, d.yB + r * 0.52, z * r * 0.86),+ new THREE.Vector3(smokeboxFront - 0.5, d.yB + r * 0.72, z * r * 1.0),+ new THREE.Vector3(fireboxBack + 0.9, d.yB + r * 0.72, z * r * 1.0),+ new THREE.Vector3(fireboxBack + 0.25, d.yB + r * 0.66, z * r * 0.98),+ ];+ g.add(+ part(bentPipe(pts, 0.022, { radialSegments: 8, tubularSegments: 32 }), MATERIALS.brass, {+ name: 'handrail',+ group: grp,+ explode: new THREE.Vector3(0, 2.1, z * 0.4),+ }),+ );+ }++ const door = boltRing({ count: 14, radius: r * 0.7, head: 0.03, height: 0.05 });+ door.rotateY(Math.PI / 2);+ door.translate(smokeboxFront + 0.04, d.yB, 0);+ g.add(part(door, MATERIALS.steel, { name: 'smokebox dogs', group: grp, explode: new THREE.Vector3(1.4, 0.4, 0) }));+ return g;+}++function cabGroup(d, v) {+ const g = new THREE.Group();+ g.name = 'cab';+ const grp = 'cab';+ const r = d.boilerR;+ const fireboxBack = d.axles[0] - d.s * 0.34;+ const cabFront = fireboxBack - 0.06;+ const cabBack = d.cabBack;+ const halfW = Math.max(1.06, r * 1.28);+ const floorY = d.R * 0.42;+ const roofY = floorY + 2.15;++ // Firebox: the wide box the boiler sits on top of, ahead of the cab.+ const fb = roundedBox(1.35, r * 1.62, halfW * 1.62, 0.05);+ fb.translate(fireboxBack + 0.62, d.yB - r * 0.1, 0);+ g.add(part(fb, MATERIALS.paintDark, { name: 'firebox', group: grp, explode: new THREE.Vector3(0, 1.3, 0) }));++ // Side sheets, with the window cut out of the profile.+ for (const z of [-1, 1]) {+ const s = new THREE.Shape();+ s.moveTo(cabBack, floorY);+ s.lineTo(cabFront, floorY);+ s.lineTo(cabFront, roofY - 0.2);+ s.lineTo(cabBack, roofY - 0.2);+ s.closePath();+ const win = new THREE.Path();+ const wx = cabBack + 0.36;+ const wy = floorY + 1.06;+ const ww = cabFront - cabBack - 0.72;+ const wh = 0.72;+ win.moveTo(wx, wy);+ win.lineTo(wx + ww, wy);+ win.lineTo(wx + ww, wy + wh);+ win.lineTo(wx, wy + wh);+ win.closePath();+ s.holes.push(win);+ const geo = new THREE.ExtrudeGeometry(s, { depth: 0.05, bevelEnabled: false });+ geo.translate(0, 0, z * halfW - z * 0.025);+ geo.computeVertexNormals();+ g.add(+ part(geo, MATERIALS.paintRed, {+ name: 'cab side',+ group: grp,+ explode: new THREE.Vector3(-0.6, 0.5, z * 1.5),+ }),+ );+ }++ const back = roundedBox(halfW * 2, roofY - 0.2 - floorY, 0.06, 0.03);+ back.rotateY(Math.PI / 2);+ back.translate(cabBack + 0.03, (roofY - 0.2 + floorY) / 2, 0);+ g.add(part(back, MATERIALS.paintRed, { name: 'cab back', group: grp, explode: new THREE.Vector3(-1.8, 0.3, 0) }));++ const floor = roundedBox(cabFront - cabBack, 0.08, halfW * 2, 0.02, false);+ floor.translate((cabFront + cabBack) / 2, floorY, 0);+ g.add(part(floor, MATERIALS.timber, { name: 'cab floor', group: grp, explode: new THREE.Vector3(-0.4, -0.3, 0) }));++ // Arched roof: an annular sector, extruded along the cab.+ const roof = arcSector({+ rInner: halfW * 2.5,+ rOuter: halfW * 2.5 + 0.06,+ from: Math.PI / 2 - 0.24,+ to: Math.PI / 2 + 0.24,+ thickness: cabFront - cabBack + 0.3,+ segments: 24,+ });+ // The sector is drawn in XY and extruded in Z; the cab needs it arching+ // across the track, so swap those two axes.+ roof.rotateY(Math.PI / 2);+ roof.translate((cabFront + cabBack) / 2, roofY - halfW * 2.5 - 0.2, 0);+ g.add(part(roof, MATERIALS.paintDark, { name: 'cab roof', group: grp, explode: new THREE.Vector3(0, 1.4, 0) }));+ return g;+}++function chassisGroup(d, v) {+ const g = new THREE.Group();+ g.name = 'chassis';+ const grp = 'frame';+ for (const z of [-1, 1]) {+ g.add(+ part(frameGeometry(d), MATERIALS.graphite, {+ name: 'frame plate',+ group: grp,+ position: new THREE.Vector3(0, 0, z * 0.5),+ explode: new THREE.Vector3(0, 0, z * 0.85),+ }),+ );+ }+ const halfW = Math.max(1.06, d.boilerR * 1.28);+ for (const z of [-1, 1]) {+ const board = roundedBox(d.cylFront - d.cabBack - 0.2, 0.06, 0.34, 0.02, false);+ board.translate((d.cylFront + d.cabBack) / 2, d.R * 0.98, z * (halfW - 0.1));+ g.add(+ part(board, MATERIALS.graphite, {+ name: 'running board',+ group: grp,+ explode: new THREE.Vector3(0, 0.7, z * 0.7),+ }),+ );+ }+ // Pilot: angled bars, the one part of the machine that is pure repetition.+ const bars = [];+ for (let i = -3; i <= 3; i++) {+ const bar = roundedBox(0.06, 1.05, 0.06, 0.02, false);+ bar.rotateZ(-0.34);+ bar.translate(d.cylFront + 0.42 + Math.abs(i) * 0.03, -d.R * 0.42, i * 0.18);+ bars.push(bar);+ }+ g.add(+ part(mergeGeometries(bars), MATERIALS.graphite, {+ name: 'pilot',+ group: grp,+ explode: new THREE.Vector3(2.1, 0, 0),+ }),+ );+ const beam = roundedBox(0.18, 0.3, 2.1, 0.03);+ beam.translate(d.cylFront + 0.3, -d.R * 0.02, 0);+ g.add(part(beam, MATERIALS.paintRed, { name: 'buffer beam', group: grp, explode: new THREE.Vector3(2.4, 0, 0) }));+ return g;+}++// One side's wheels, rods, crosshead and valve gear. Built twice, mirrored,+// with the quartering phase that stops a two-cylinder engine dead-centring.+function sideGroup(d, v, side, phase) {+ const z = side * d.zMotion;+ const zw = side * d.zWheel;+ const g = new THREE.Group();+ g.name = side > 0 ? 'right motion' : 'left motion';+ const wheels = [];+ for (let j = 0; j < d.n; j++) {+ const geo = spokedWheel({+ radius: d.R,+ tyreWidth: 0.14,+ hubRadius: d.R * 0.19,+ hubWidth: 0.3,+ spokes: v.spokes,+ spokeWidth: d.R * 0.055,+ crankRadius: d.pinR,+ pinSide: side,+ });+ const mesh = part(geo, MATERIALS.castIron, {+ name: `driver ${j + 1}`,+ group: 'wheels',+ position: new THREE.Vector3(d.axles[j], 0, zw * 1),+ explode: new THREE.Vector3(0, 0, side * 0.9),+ });+ g.add(mesh);+ wheels.push(mesh);+ }++ const sideRodLen = d.axles[d.n - 1] - d.axles[0];+ const sideRod = part(+ rodGeometry({+ length: sideRodLen,+ bigEndR: d.R * 0.1,+ smallEndR: d.R * 0.1,+ waist: d.R * 0.055,+ thickness: 0.06,+ }),+ MATERIALS.steel,+ { name: 'coupling rod', group: 'motion', explode: new THREE.Vector3(0, 0, side * 1.35) },+ );+ g.add(sideRod);++ const mainRodMesh = part(+ rodGeometry({+ length: d.mainRod,+ bigEndR: d.R * 0.11,+ smallEndR: d.R * 0.075,+ waist: d.R * 0.05,+ thickness: 0.07,+ }),+ MATERIALS.steel,+ { name: 'main rod', group: 'motion', explode: new THREE.Vector3(0, 0, side * 1.6) },+ );+ g.add(mainRodMesh);++ const crosshead = part(roundedBox(0.34, d.R * 0.26, 0.22, 0.02), MATERIALS.steel, {+ name: 'crosshead',+ group: 'motion',+ explode: new THREE.Vector3(0, 0, side * 1.6),+ });+ g.add(crosshead);++ const pistonRod = part(+ (() => {+ const c = new THREE.CylinderGeometry(0.05, 0.05, 1, 16);+ c.rotateZ(-Math.PI / 2);+ return c;+ })(),+ MATERIALS.steel,+ { name: 'piston rod', group: 'motion', explode: new THREE.Vector3(0, 0, side * 1.6) },+ );+ g.add(pistonRod);++ // Guide bars are fixed: two flats the crosshead slides between.+ for (const dy of [-1, 1]) {+ const bar = roundedBox(d.crankR * 2 + 0.5, 0.05, 0.16, 0.015, false);+ bar.translate(d.cylRear - (d.crankR * 2 + 0.5) / 2 - 0.03, d.yC + dy * d.R * 0.16, 0);+ g.add(+ part(bar, MATERIALS.graphite, {+ name: 'guide bar',+ group: 'motion',+ position: new THREE.Vector3(0, 0, z),+ explode: new THREE.Vector3(0, dy * 0.35, side * 1.2),+ }),+ );+ }++ // Cylinder and valve chest.+ const cyl = lathe(+ [+ [0, 0], [d.R * 0.36, 0], [d.R * 0.36, 0.06], [d.R * 0.3, 0.08],+ [d.R * 0.3, d.cylLen - 0.08], [d.R * 0.36, d.cylLen - 0.06],+ [d.R * 0.36, d.cylLen], [0, d.cylLen],+ ],+ 36,+ );+ cyl.rotateZ(-Math.PI / 2);+ cyl.translate(d.cylRear, d.yC, 0);+ g.add(+ part(cyl, MATERIALS.castIron, {+ name: 'cylinder',+ group: 'cylinders',+ position: new THREE.Vector3(0, 0, z),+ explode: new THREE.Vector3(1.1, 0, side * 1.1),+ }),+ );+ const chest = lathe(+ [+ [0, 0], [d.R * 0.19, 0], [d.R * 0.19, d.cylLen * 0.92], [0, d.cylLen * 0.92],+ ],+ 28,+ );+ chest.rotateZ(-Math.PI / 2);+ chest.translate(d.cylRear + 0.04, d.yValve, 0);+ g.add(+ part(chest, MATERIALS.castIron, {+ name: 'valve chest',+ group: 'cylinders',+ position: new THREE.Vector3(0, 0, z),+ explode: new THREE.Vector3(1.1, 0.6, side * 1.1),+ }),+ );+ const cover = roundedBox(0.12, d.R * 0.82, d.R * 0.82, 0.03);+ cover.translate(d.cylFront + 0.02, d.yC, 0);+ g.add(+ part(cover, MATERIALS.castIron, {+ name: 'cylinder cover',+ group: 'cylinders',+ position: new THREE.Vector3(0, 0, z),+ explode: new THREE.Vector3(1.9, 0, side * 1.1),+ }),+ );++ const piston = part(+ (() => {+ const p = new THREE.CylinderGeometry(d.R * 0.29, d.R * 0.29, 0.16, 28);+ p.rotateZ(Math.PI / 2);+ return p;+ })(),+ MATERIALS.brass,+ { name: 'piston', group: 'motion', explode: new THREE.Vector3(0, 0, side * 2.1) },+ );+ g.add(piston);++ // Valve gear links.+ const returnCrank = part(+ rodGeometry({ length: d.rE, bigEndR: 0.075, smallEndR: 0.055, thickness: 0.05 }),+ MATERIALS.steel,+ { name: 'return crank', group: 'valve gear', explode: new THREE.Vector3(0, 0, side * 1.9) },+ );+ g.add(returnCrank);++ const eccRodMesh = part(+ rodGeometry({ length: d.eccRod, bigEndR: 0.06, smallEndR: 0.05, waist: 0.032, thickness: 0.045 }),+ MATERIALS.steel,+ { name: 'eccentric rod', group: 'valve gear', explode: new THREE.Vector3(0, 0.2, side * 1.9) },+ );+ g.add(eccRodMesh);++ const lever = part(+ rodGeometry({+ length: d.armLow + d.armHigh,+ bigEndR: 0.065,+ smallEndR: 0.06,+ waist: 0.04,+ thickness: 0.05,+ }),+ MATERIALS.steel,+ { name: 'rocking lever', group: 'valve gear', explode: new THREE.Vector3(0, 0.5, side * 1.9) },+ );+ g.add(lever);++ const valveLinkMesh = part(+ rodGeometry({ length: d.valveLink, bigEndR: 0.05, smallEndR: 0.045, waist: 0.03, thickness: 0.04 }),+ MATERIALS.steel,+ { name: 'valve link', group: 'valve gear', explode: new THREE.Vector3(0.3, 0.5, side * 1.9) },+ );+ g.add(valveLinkMesh);++ const valveRod = part(+ (() => {+ const c = new THREE.CylinderGeometry(0.035, 0.035, 1, 14);+ c.rotateZ(-Math.PI / 2);+ return c;+ })(),+ MATERIALS.steel,+ { name: 'valve spindle', group: 'valve gear', explode: new THREE.Vector3(0, 0.55, side * 1.9) },+ );+ g.add(valveRod);++ const bracket = joint('lever bracket', {+ group: 'valve gear',+ position: new THREE.Vector3(d.rockPivot.x, d.rockPivot.y, z),+ });+ const brGeo = roundedBox(0.12, d.R * 0.5, 0.1, 0.02, false);+ brGeo.translate(0, -d.R * 0.25, 0);+ bracket.add(part(brGeo, MATERIALS.graphite, { name: 'bracket', group: 'valve gear' }));+ g.add(bracket);++ return {+ group: g,+ side,+ phase,+ z,+ wheels,+ sideRod,+ mainRodMesh,+ crosshead,+ pistonRod,+ piston,+ returnCrank,+ eccRodMesh,+ lever,+ valveLinkMesh,+ valveRod,+ branch: 0,+ };+}++export function build(v) {+ const d = derive(v);+ const root = new THREE.Group();+ root.name = 'coupled-six';++ const track = trackGroup(d);+ root.add(track);+ root.add(chassisGroup(d, v));+ root.add(boilerGroup(d, v));+ root.add(cabGroup(d, v));++ const sides = [sideGroup(d, v, 1, 0), sideGroup(d, v, -1, Math.PI / 2)];+ for (const s of sides) root.add(s.group);++ const pin = new THREE.Vector2();+ const ecc = new THREE.Vector2();+ const lastPin = new THREE.Vector2(d.rockPivot.x, d.rockPivot.y - d.armLow);++ // Pick the solution branch once, at build time: the one that hangs the+ // lever's lower end below its pivot. Locking it here is what keeps the+ // linkage from snapping through itself at a dead centre.+ {+ const a = 0;+ ecc.set(+ d.mainX + d.pinR * Math.cos(a) + d.rE * Math.cos(a + d.psi),+ d.pinR * Math.sin(a) + d.rE * Math.sin(a + d.psi),+ );+ for (const s of sides) {+ const up = circleIntersect(ecc, d.eccRod, d.rockPivot, d.armLow, 1);+ const down = circleIntersect(ecc, d.eccRod, d.rockPivot, d.armLow, -1);+ if (up && down) s.branch = up.y < down.y ? 1 : -1;+ else s.branch = up ? 1 : -1;+ }+ }++ const p2 = new THREE.Vector2();+ const q2 = new THREE.Vector2();+ // Distance from the crosshead pin to the piston face, fixed by the rod.+ const pistonOffset = d.cylRear + d.cylLen * 0.5 - (d.crossMax - d.crankR);++ function update(theta) {+ // The engine stays put and the track runs under it. Wrapping the offset+ // at one sleeper pitch makes that loop seamless, because the track is+ // periodic at exactly that interval.+ const travelled = theta * d.R;+ track.position.x = -(((travelled % SLEEPER_PITCH) + SLEEPER_PITCH) % SLEEPER_PITCH);+ for (const s of sides) {+ // Rolling forward turns the wheel clockwise in this view.+ const a = -theta + s.phase;+ for (let j = 0; j < d.n; j++) s.wheels[j].rotation.z = a;++ const cos = Math.cos(a);+ const sin = Math.sin(a);+ const pinY = d.pinR * sin;+ p2.set(d.axles[0] + d.pinR * cos, pinY);+ q2.set(d.axles[d.n - 1] + d.pinR * cos, pinY);+ placeLink(s.sideRod, p2, q2, s.z + 0.02 * s.side);++ pin.set(d.mainX + d.pinR * cos, pinY);+ const cross = slideOnLine(pin, d.yC, d.mainRod, 1);+ if (cross) {+ placeLink(s.mainRodMesh, pin, cross, s.z + 0.09 * s.side);+ s.crosshead.position.set(cross.x + 0.12, d.yC, s.z + 0.09 * s.side);+ s.crosshead.userData.rest.copy(s.crosshead.position);+ const rodBack = cross.x + 0.2;+ const rodFront = d.cylRear + 0.12;+ s.pistonRod.position.set((rodBack + rodFront) / 2, d.yC, s.z);+ s.pistonRod.userData.rest.copy(s.pistonRod.position);+ s.pistonRod.scale.x = Math.max(rodFront - rodBack, 0.02);+ // The piston is on the far end of the same rod, so it inherits the+ // crosshead's motion exactly, offset into the bore.+ s.piston.position.set(cross.x + pistonOffset, d.yC, s.z);+ s.piston.userData.rest.copy(s.piston.position);+ }++ ecc.set(+ d.mainX + d.pinR * cos + d.rE * Math.cos(a + d.psi),+ pinY + d.rE * Math.sin(a + d.psi),+ );+ placeLink(s.returnCrank, pin, ecc, s.z + 0.15 * s.side);++ const low = circleIntersect(ecc, d.eccRod, d.rockPivot, d.armLow, s.branch) || lastPin;+ lastPin.copy(low);+ placeLink(s.eccRodMesh, ecc, low, s.z + 0.15 * s.side);++ const dir = low.clone().sub(d.rockPivot).normalize();+ const top = d.rockPivot.clone().addScaledVector(dir, -d.armHigh);+ placeLink(s.lever, low, top, s.z + 0.2 * s.side);++ const valvePin = slideOnLine(top, d.yValve, d.valveLink, 1);+ if (valvePin) {+ placeLink(s.valveLinkMesh, top, valvePin, s.z + 0.24 * s.side);+ const back = valvePin.x;+ const front = d.cylRear + d.cylLen * 0.55;+ s.valveRod.position.set((back + front) / 2, d.yValve, s.z);+ s.valveRod.userData.rest.copy(s.valveRod.position);+ s.valveRod.scale.x = Math.max(front - back, 0.02);+ }+ }+ }++ update(0);++ const readout = [+ ['Coupled wheelbase', `${d.wheelbase.toFixed(2)} m`],+ ['Driver diameter', `${v.driverDia} mm`],+ ['Piston stroke', `${v.stroke} mm`],+ ['Eccentric throw', `${(d.rho * 1000).toFixed(0)} mm`],+ ];++ return { root, update, readout, cyclesPerTurn: 1, rollingRadius: d.R };+}diff --git a/src/assembly/materials.js b/src/assembly/materials.jsnew file mode 100644index 000000000..d5724aa27--- /dev/null+++ b/src/assembly/materials.js@@ -0,0 +1,83 @@+// Shared material palette for the Machine Atlas.+//+// One palette across both machines is what makes them read as one collection.+// Values are physically plausible (roughness/metalness, not hand-tuned tints)+// so the same set survives a lighting change without a re-grade.++import * as THREE from 'three';++const cache = new Map();++function mat(name, params) {+ if (cache.has(name)) return cache.get(name);+ const m = new THREE.MeshStandardMaterial({ name, ...params });+ cache.set(name, m);+ return m;+}++export const MATERIALS = {+ // Machined steel: bright, tight highlight. Rods, pins, guide bars.+ get steel() {+ return mat('steel', { color: 0xb9bdc4, metalness: 0.95, roughness: 0.24 });+ },+ // Sand-cast aluminium: the crankcase and cylinder heads.+ get castAlloy() {+ return mat('castAlloy', { color: 0x9aa0a6, metalness: 0.72, roughness: 0.58 });+ },+ // Grey iron: cylinder barrels, wheel centres.+ get castIron() {+ return mat('castIron', { color: 0x4c5257, metalness: 0.62, roughness: 0.7 });+ },+ get brass() {+ return mat('brass', { color: 0xc9a447, metalness: 0.95, roughness: 0.3 });+ },+ get copper() {+ return mat('copper', { color: 0xb87333, metalness: 0.95, roughness: 0.34 });+ },+ // Boiler cladding and bodywork: the only painted surfaces on the atlas.+ get paintDark() {+ return mat('paintDark', { color: 0x1d2427, metalness: 0.2, roughness: 0.45 });+ },+ get paintRed() {+ return mat('paintRed', { color: 0x7c2b22, metalness: 0.2, roughness: 0.5 });+ },+ get graphite() {+ return mat('graphite', { color: 0x2a2d30, metalness: 0.55, roughness: 0.62 });+ },+ get timber() {+ return mat('timber', { color: 0x6b5745, metalness: 0.02, roughness: 0.88 });+ },+ get ballast() {+ return mat('ballast', { color: 0x55585c, metalness: 0.05, roughness: 0.95 });+ },+ get glass() {+ return mat('glass', {+ color: 0xa8c6cf,+ metalness: 0.1,+ roughness: 0.08,+ transparent: true,+ opacity: 0.32,+ });+ },+};++// The wireframe overlay used by the "structure" view: one shared material so+// toggling it costs a single uniform change, not a per-part rebuild.+export function ghostMaterial() {+ return mat('ghost', {+ color: 0x7fd4ff,+ wireframe: true,+ transparent: true,+ opacity: 0.22,+ metalness: 0,+ roughness: 1,+ });+}++// Machines own their geometry but never their materials, so a rebuild frees+// only what it allocated.+export function disposeTree(root) {+ root.traverse((o) => {+ if (o.isMesh && o.geometry) o.geometry.dispose();+ });+}diff --git a/src/assembly/parts.js b/src/assembly/parts.jsnew file mode 100644index 000000000..458cbc576--- /dev/null+++ b/src/assembly/parts.js@@ -0,0 +1,390 @@+// Parametric part vocabulary for the Machine Atlas (/assembly).+//+// Nothing here loads a file. Every export turns a handful of dimensions into+// real BufferGeometry: profiles get revolved, cross-sections get extruded,+// airfoil stations get lofted. The machines in this folder are assembled+// entirely out of these calls, which is why changing a slider rebuilds actual+// geometry instead of scaling a mesh.+//+// Conventions:+// - Units are metres. A driving wheel really is 1.6 m across.+// - Wheels, rods and any planar linkage live in the XY plane and spin about+// +Z, so the kinematics in the machine modules stay 2D and exact.+// - Every builder returns geometry with normals computed and nothing shared,+// so a rebuild can dispose the old tree without touching the new one.++import * as THREE from 'three';++/* ── profiles and revolves ──────────────────────────────────────────── */++// A profile is an array of [radius, axial] pairs. Revolving it about +Y is the+// cheapest way to describe a turned part: shafts, domes, stacks, bosses.+export function profilePoints(pairs) {+ return pairs.map(([r, y]) => new THREE.Vector2(r, y));+}++export function lathe(pairs, segments = 48) {+ const g = new THREE.LatheGeometry(profilePoints(pairs), segments);+ g.computeVertexNormals();+ return g;+}++// A finned air-cooled barrel: one revolve of a sawtooth profile, so the fins+// are part of the same surface a real casting would have, not stacked rings.+export function finnedBarrel({+ bore,+ wall = 0.008,+ finRoot,+ finTip,+ length,+ fins,+ finThickness = 0.004,+ segments = 40,+}) {+ const rBore = bore / 2;+ const rRoot = finRoot ?? rBore + wall;+ const rTip = finTip ?? rRoot + 0.035;+ const pairs = [[rBore, 0], [rRoot, 0]];+ const pitch = fins > 1 ? (length - finThickness) / (fins - 1) : 0;+ for (let i = 0; i < fins; i++) {+ const y = i * pitch;+ pairs.push([rRoot, y], [rTip, y], [rTip, y + finThickness], [rRoot, y + finThickness]);+ }+ pairs.push([rRoot, length], [rBore, length], [rBore, 0]);+ return lathe(pairs, segments);+}++/* ── extruded cross-sections ────────────────────────────────────────── */++function roundedRectShape(w, h, r) {+ const x = -w / 2;+ const y = -h / 2;+ const k = Math.min(r, w / 2, h / 2);+ const s = new THREE.Shape();+ s.moveTo(x + k, y);+ s.lineTo(x + w - k, y);+ s.quadraticCurveTo(x + w, y, x + w, y + k);+ s.lineTo(x + w, y + h - k);+ s.quadraticCurveTo(x + w, y + h, x + w - k, y + h);+ s.lineTo(x + k, y + h);+ s.quadraticCurveTo(x, y + h, x, y + h - k);+ s.lineTo(x, y + k);+ s.quadraticCurveTo(x, y, x + k, y);+ return s;+}++// A box with softened edges. Every hard-edged casting on the atlas uses this+// instead of BoxGeometry so highlights read as metal rather than as a cube.+export function roundedBox(w, h, d, r = 0.01, bevel = true) {+ const bs = bevel ? Math.min(r * 0.6, d / 4) : 0;+ const g = new THREE.ExtrudeGeometry(roundedRectShape(w, h, r), {+ depth: d - bs * 2,+ bevelEnabled: bevel,+ bevelThickness: bs,+ bevelSize: bs,+ bevelSegments: 2,+ curveSegments: 6,+ });+ g.translate(0, 0, -(d - bs * 2) / 2 - bs);+ g.computeVertexNormals();+ return g;+}++// A connecting or coupling rod: a waisted stadium running +X from a big end at+// the origin to a small end at `length`, extruded through its thickness in Z.+export function rodGeometry({ length, bigEndR, smallEndR, waist, thickness, boss = 0 }) {+ const w = waist ?? Math.min(bigEndR, smallEndR) * 0.62;+ const s = new THREE.Shape();+ s.moveTo(0, bigEndR);+ s.quadraticCurveTo(length * 0.5, w, length, smallEndR);+ s.absarc(length, 0, smallEndR, Math.PI / 2, -Math.PI / 2, true);+ s.quadraticCurveTo(length * 0.5, -w, 0, -bigEndR);+ s.absarc(0, 0, bigEndR, -Math.PI / 2, -Math.PI * 1.5, true);+ const g = new THREE.ExtrudeGeometry(s, {+ depth: thickness,+ bevelEnabled: true,+ bevelThickness: thickness * 0.12,+ bevelSize: thickness * 0.12,+ bevelSegments: 1,+ curveSegments: 18,+ });+ g.translate(0, 0, -thickness / 2);+ if (boss > 0) {+ const bosses = [];+ for (const [x, r] of [[0, bigEndR], [length, smallEndR]]) {+ const b = new THREE.CylinderGeometry(r * 0.98, r * 0.98, thickness + boss * 2, 24);+ b.rotateX(Math.PI / 2);+ b.translate(x, 0, 0);+ bosses.push(b);+ }+ return mergeGeometries([g, ...bosses]);+ }+ g.computeVertexNormals();+ return g;+}++// An annular sector extruded in Z: counterweights, brackets, expansion links.+export function arcSector({ rInner, rOuter, from, to, thickness, segments = 28 }) {+ const s = new THREE.Shape();+ s.absarc(0, 0, rOuter, from, to, false);+ s.absarc(0, 0, rInner, to, from, true);+ const g = new THREE.ExtrudeGeometry(s, {+ depth: thickness,+ bevelEnabled: false,+ curveSegments: segments,+ });+ g.translate(0, 0, -thickness / 2);+ g.computeVertexNormals();+ return g;+}++// Flat-bottom rail section (head, web, foot), extruded along +Z as the track+// direction. The web taper is what makes a rail read as a rail at a glance.+export function railShape(scale = 1) {+ const s = new THREE.Shape();+ const p = (x, y) => [x * scale, y * scale];+ const pts = [+ p(-0.076, 0), p(0.076, 0), p(0.076, 0.014), p(0.020, 0.036),+ p(0.016, 0.116), p(0.037, 0.130), p(0.037, 0.166), p(0.020, 0.185),+ p(-0.020, 0.185), p(-0.037, 0.166), p(-0.037, 0.130), p(-0.016, 0.116),+ p(-0.020, 0.036), p(-0.076, 0.014),+ ];+ s.moveTo(pts[0][0], pts[0][1]);+ for (let i = 1; i < pts.length; i++) s.lineTo(pts[i][0], pts[i][1]);+ s.closePath();+ return s;+}++export function railGeometry(length, scale = 1) {+ const g = new THREE.ExtrudeGeometry(railShape(scale), {+ depth: length,+ bevelEnabled: false,+ });+ g.translate(0, 0, -length / 2);+ g.rotateY(Math.PI / 2);+ g.computeVertexNormals();+ return g;+}++/* ── swept and lofted surfaces ──────────────────────────────────────── */++// A pipe bent through a list of points. Used for induction pipes and handrails,+// where a straight cylinder would look like a placeholder.+export function bentPipe(points, radius, { radialSegments = 12, tubularSegments = 48 } = {}) {+ const curve = new THREE.CatmullRomCurve3(points.map((p) => p.clone()), false, 'catmullrom', 0.35);+ const g = new THREE.TubeGeometry(curve, tubularSegments, radius, radialSegments, false);+ g.computeVertexNormals();+ return g;+}++// NACA 4-digit section, closed loop, chord along +X, thickness in +Y.+function nacaSection(code, n) {+ const m = Number(code[0]) / 100;+ const p = Number(code[1]) / 10;+ const t = Number(code.slice(2)) / 100;+ const upper = [];+ const lower = [];+ for (let i = 0; i <= n; i++) {+ // Cosine spacing packs points into the leading edge, where curvature is.+ const x = 0.5 * (1 - Math.cos((Math.PI * i) / n));+ const yt =+ 5 * t * (0.2969 * Math.sqrt(x) - 0.126 * x - 0.3516 * x * x + 0.2843 * x ** 3 - 0.1015 * x ** 4);+ let yc = 0;+ let dyc = 0;+ if (m > 0 && p > 0) {+ if (x < p) {+ yc = (m / (p * p)) * (2 * p * x - x * x);+ dyc = ((2 * m) / (p * p)) * (p - x);+ } else {+ yc = (m / ((1 - p) ** 2)) * (1 - 2 * p + 2 * p * x - x * x);+ dyc = ((2 * m) / ((1 - p) ** 2)) * (p - x);+ }+ }+ const th = Math.atan(dyc);+ upper.push([x - yt * Math.sin(th), yc + yt * Math.cos(th)]);+ lower.push([x + yt * Math.sin(th), yc - yt * Math.cos(th)]);+ }+ lower.reverse();+ return upper.concat(lower.slice(1, -1));+}++// Loft a twisting, tapering airfoil along +Z: a propeller or turbine blade+// described by root chord, tip chord and the twist between them.+export function loftedBlade({+ span,+ chordRoot,+ chordTip,+ twistRoot,+ twistTip,+ code = '2412',+ stations = 14,+ resolution = 18,+ rake = 0,+}) {+ const section = nacaSection(code, resolution);+ const ring = section.length;+ const pos = [];+ const idx = [];+ for (let s = 0; s < stations; s++) {+ const u = s / (stations - 1);+ const chord = chordRoot + (chordTip - chordRoot) * u;+ const twist = THREE.MathUtils.degToRad(twistRoot + (twistTip - twistRoot) * u);+ const z = u * span;+ const x0 = rake * u * u;+ const cos = Math.cos(twist);+ const sin = Math.sin(twist);+ // Taper toward a rounded tip so the last station is not a flat cut.+ const shrink = u > 0.94 ? Math.sqrt(Math.max(0, 1 - ((u - 0.94) / 0.06) ** 2)) : 1;+ for (const [sx, sy] of section) {+ const cx = (sx - 0.28) * chord * shrink;+ const cy = sy * chord * shrink;+ pos.push(cx * cos - cy * sin + x0, cx * sin + cy * cos, z);+ }+ }+ for (let s = 0; s < stations - 1; s++) {+ for (let i = 0; i < ring; i++) {+ const a = s * ring + i;+ const b = s * ring + ((i + 1) % ring);+ const c = a + ring;+ const d = b + ring;+ idx.push(a, c, b, b, c, d);+ }+ }+ // Fan-cap the root; the tip closes on itself through `shrink`.+ const rootCentre = pos.length / 3;+ pos.push(0, 0, 0);+ for (let i = 0; i < ring; i++) idx.push(rootCentre, (i + 1) % ring, i);+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));+ g.setIndex(idx);+ g.computeVertexNormals();+ return g;+}++/* ── assemblies ─────────────────────────────────────────────────────── */++// A spoked driving wheel in the XY plane, axle along Z: tyre, flange, spokes,+// crescent counterweight and a crankpin boss at `crankRadius`.+export function spokedWheel({+ radius,+ tyreWidth = 0.14,+ flange = 0.028,+ hubRadius = 0.16,+ hubWidth = 0.26,+ spokes = 18,+ spokeWidth = 0.05,+ crankRadius = 0,+ counterweight = true,+ pinSide = 1,+}) {+ const parts = [];+ const rimInner = radius - 0.09;+ const w = tyreWidth / 2;+ // Tyre and flange as one revolved section, the way a tyre is actually+ // turned. A pair of cones would close the wheel face and bury the spokes.+ const tyre = lathe(+ [+ [rimInner, -w], [radius + flange, -w], [radius + flange, -w + 0.022],+ [radius, -w + 0.034], [radius, w], [rimInner, w], [rimInner, -w],+ ],+ 64,+ );+ tyre.rotateX(Math.PI / 2);+ parts.push(tyre);+ const hub = new THREE.CylinderGeometry(hubRadius, hubRadius, hubWidth, 32);+ hub.rotateX(Math.PI / 2);+ parts.push(hub);++ const spokeLen = rimInner - hubRadius * 0.7;+ for (let i = 0; i < spokes; i++) {+ const a = (i / spokes) * Math.PI * 2;+ // Spokes are tapered plates, thicker at the hub, like a cast wheel centre.+ const s = new THREE.CylinderGeometry(spokeWidth * 0.72, spokeWidth, spokeLen, 10);+ s.translate(0, spokeLen / 2 + hubRadius * 0.7, 0);+ s.rotateZ(a);+ s.scale(1, 1, 0.55);+ parts.push(s);+ }+ if (counterweight) {+ const cw = arcSector({+ rInner: hubRadius + 0.06,+ rOuter: rimInner - 0.01,+ from: Math.PI * 0.72,+ to: Math.PI * 1.28,+ thickness: tyreWidth * 0.58,+ segments: 24,+ });+ parts.push(cw);+ }+ if (crankRadius > 0) {+ // The pin sits outboard, so which way that is depends on the side of the+ // locomotive. Mirroring the mesh instead would invert its normals.+ const pin = new THREE.CylinderGeometry(0.052, 0.052, tyreWidth * 1.5, 20);+ pin.rotateX(Math.PI / 2);+ pin.translate(crankRadius, 0, pinSide * tyreWidth * 0.62);+ parts.push(pin);+ const boss = new THREE.CylinderGeometry(0.086, 0.086, tyreWidth * 0.5, 20);+ boss.rotateX(Math.PI / 2);+ boss.translate(crankRadius, 0, pinSide * tyreWidth * 0.28);+ parts.push(boss);+ }+ return mergeGeometries(parts);+}++// A ring of identical fasteners around +Z, baked into one geometry.+export function boltRing({ count, radius, head = 0.014, height = 0.012, z = 0 }) {+ const parts = [];+ for (let i = 0; i < count; i++) {+ const a = (i / count) * Math.PI * 2;+ const b = new THREE.CylinderGeometry(head, head, height, 6);+ b.rotateX(Math.PI / 2);+ b.translate(Math.cos(a) * radius, Math.sin(a) * radius, z);+ parts.push(b);+ }+ return mergeGeometries(parts);+}++/* ── merging ────────────────────────────────────────────────────────── */++// Minimal non-indexed merge. three's BufferGeometryUtils needs every input to+// carry identical attribute sets; these builders mix indexed and non-indexed+// primitives, so normalising to raw position/normal/uv triangles here is both+// simpler and cheaper than reconciling them.+export function mergeGeometries(geometries) {+ const pos = [];+ const nor = [];+ const uv = [];+ for (const g of geometries) {+ const src = g.index ? g.toNonIndexed() : g;+ const p = src.getAttribute('position');+ const n = src.getAttribute('normal') || null;+ const t = src.getAttribute('uv') || null;+ for (let i = 0; i < p.count; i++) {+ pos.push(p.getX(i), p.getY(i), p.getZ(i));+ if (n) nor.push(n.getX(i), n.getY(i), n.getZ(i));+ uv.push(t ? t.getX(i) : 0, t ? t.getY(i) : 0);+ }+ if (src !== g) src.dispose();+ g.dispose();+ }+ const out = new THREE.BufferGeometry();+ out.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));+ out.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));+ if (nor.length === pos.length) {+ out.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));+ } else {+ out.computeVertexNormals();+ }+ return out;+}++export function triangleCount(object) {+ let n = 0;+ object.traverse((o) => {+ if (!o.isMesh || !o.geometry) return;+ const g = o.geometry;+ const count = g.index ? g.index.count : g.getAttribute('position').count;+ n += (count / 3) * (o.isInstancedMesh ? o.count : 1);+ });+ return n;+}diff --git a/src/assembly/radial-engine.js b/src/assembly/radial-engine.jsnew file mode 100644index 000000000..f9cf7b010--- /dev/null+++ b/src/assembly/radial-engine.js@@ -0,0 +1,465 @@+// Machine 01: an air-cooled radial aero engine, generated from nine numbers.+//+// There is no model file behind this. Bore and stroke set the crank throw, the+// crank throw sets the crankcase diameter, the crankcase diameter sets where+// the cylinders bolt on, and the cylinder count divides the circle. Move the+// bore slider and every downstream dimension is recomputed and re-lofted.+//+// The motion is solved, not keyframed: pistons come from the exact planar+// slider-crank (rig.js `slider`), so a long rod really does dwell at top dead+// centre longer than a short one.++import * as THREE from 'three';+import {+ finnedBarrel,+ lathe,+ roundedBox,+ rodGeometry,+ loftedBlade,+ boltRing,+ mergeGeometries,+} from './parts.js';+import { MATERIALS } from './materials.js';+import { part, joint, alignSegment, slider } from './rig.js';++export const spec = {+ id: 'radial',+ name: 'Radial Nine',+ subtitle: 'Air-cooled radial aero engine',+ era: '1932',+ blurb:+ 'A single row of air-cooled cylinders around one crank throw. Every fin, pushrod and blade section below is computed at load time from the parameters on the right.',+ facts: [+ ['Layout', 'Single-row radial, four-stroke'],+ ['Cooling', 'Direct air, integral head and barrel fins'],+ ['Valve gear', 'Cam ring, pushrod, overhead rocker'],+ ],+ params: [+ { key: 'cylinders', label: 'Cylinders', min: 5, max: 11, step: 2, value: 9, unit: '' },+ { key: 'bore', label: 'Bore', min: 110, max: 175, step: 1, value: 155, unit: 'mm' },+ { key: 'stroke', label: 'Stroke', min: 120, max: 200, step: 1, value: 175, unit: 'mm' },+ { key: 'rodRatio', label: 'Rod / stroke', min: 1.6, max: 2.6, step: 0.05, value: 2, unit: ':1' },+ { key: 'fins', label: 'Barrel fins', min: 8, max: 40, step: 1, value: 30, unit: '' },+ { key: 'blades', label: 'Prop blades', min: 2, max: 5, step: 1, value: 3, unit: '' },+ { key: 'propDia', label: 'Prop diameter', min: 1.8, max: 3.2, step: 0.05, value: 2.2, unit: 'm' },+ ],+ camera: { position: [2.7, 1.15, 1.55], target: [0, 0, 0.15], radius: 2.1 },+};++// Every dimension the builder needs, derived from the seven the user controls.+// Keeping this pure makes the readout, the code panel and the geometry agree+// by construction rather than by remembering to update three places.+export function derive(v) {+ const bore = v.bore / 1000;+ const stroke = v.stroke / 1000;+ const throwR = stroke / 2;+ const rod = stroke * v.rodRatio;+ const caseR = throwR + bore * 0.62;+ const baseR = caseR + 0.012;+ // The deck has to clear the piston crown at top dead centre, which sits at+ // (throw + rod) from the engine axis plus the crown height. Deriving it+ // rather than guessing is why a long-rod setting lengthens the barrel.+ const crown = bore * 0.34;+ const deck = throwR + rod + crown + bore * 0.1;+ const displacement = (Math.PI / 4) * bore * bore * stroke * v.cylinders * 1000;+ return {+ bore,+ stroke,+ throwR,+ rod,+ caseR,+ baseR,+ deck,+ crown,+ barrelLen: deck - baseR,+ headH: bore * 0.42,+ finTip: bore * 0.5 + 0.028,+ finRoot: bore * 0.5 + 0.009,+ displacement,+ propR: v.propDia / 2,+ };+}++// The code panel is generated from the live values, so it cannot drift away+// from the geometry the way a pasted snippet would.+export function codeFor(v) {+ const d = derive(v);+ const mm = (n) => n.toFixed(3);+ return [+ {+ label: 'Cylinder barrel',+ code: `finnedBarrel({+ bore: ${mm(d.bore)},+ finRoot: ${mm(d.finRoot)},+ finTip: ${mm(d.finTip)},+ length: ${mm(d.barrelLen)},+ fins: ${v.fins},+})`,+ },+ {+ label: 'Cylinder placement',+ code: `for (let i = 0; i < ${v.cylinders}; i++) {+ const theta = (i / ${v.cylinders}) * Math.PI * 2;+ cylinder.position.set(+ Math.cos(theta) * ${mm(d.baseR)},+ Math.sin(theta) * ${mm(d.baseR)}, 0);+ cylinder.rotation.z = theta - Math.PI / 2;+}`,+ },+ {+ label: 'Piston motion',+ code: `// exact planar slider-crank, no keyframes+const pin = crankpin(phi, ${mm(d.throwR)});+const c = slider(pin, axis, ${mm(d.rod)});+piston.position.copy(axis).multiplyScalar(c);`,+ },+ {+ label: 'Propeller blade',+ code: `loftedBlade({+ span: ${mm(d.propR - 0.11)},+ chordRoot: ${mm(d.propR * 0.17)},+ chordTip: ${mm(d.propR * 0.09)},+ twistRoot: 34, twistTip: 8,+ code: '2412', // NACA 4-digit sections+})`,+ },+ ];+}++function crankcase(d) {+ // Rear accessory case, main case, front nose case: one turned profile.+ const rear = lathe(+ [+ [0, -0.16], [d.caseR * 0.44, -0.16], [d.caseR * 0.5, -0.14],+ [d.caseR * 0.72, -0.115], [d.caseR * 0.78, -0.075], [d.caseR, -0.045],+ [d.caseR, 0], [0, 0],+ ],+ 56,+ );+ const front = lathe(+ [+ [0, 0], [d.caseR, 0], [d.caseR, 0.05], [d.caseR * 0.82, 0.085],+ [d.caseR * 0.5, 0.1], [d.caseR * 0.34, 0.13], [d.caseR * 0.3, 0.2],+ [d.caseR * 0.22, 0.215], [0, 0.215],+ ],+ 56,+ );+ // The crankshaft runs along +Z and the profiles are revolved about +Y, so a+ // quarter turn about X puts the nose case forward and the accessory case aft.+ for (const g of [rear, front]) g.rotateX(Math.PI / 2);+ return { rear, front };+}++function cylinderAssembly(d, v, index) {+ const g = new THREE.Group();+ g.name = `cylinder-${index + 1}`;+ const grp = 'cylinders';++ const barrel = finnedBarrel({+ bore: d.bore,+ finRoot: d.finRoot,+ finTip: d.finTip,+ length: d.barrelLen,+ fins: v.fins,+ finThickness: Math.min(0.005, (d.barrelLen / v.fins) * 0.42),+ segments: 36,+ });+ g.add(part(barrel, MATERIALS.castIron, { name: 'barrel', group: grp }));++ // Head: finned casting plus the rocker box that carries the valve gear.+ const headY = d.barrelLen + d.headH / 2;+ const headGeoms = [];+ const headBody = roundedBox(d.bore * 1.24, d.headH, d.bore * 1.34, 0.016);+ headBody.rotateX(Math.PI / 2);+ headBody.translate(0, headY, 0);+ headGeoms.push(headBody);+ const headFins = 5;+ for (let i = 0; i < headFins; i++) {+ const y = d.barrelLen + 0.008 + (i * (d.headH - 0.016)) / headFins;+ const f = roundedBox(d.bore * 1.4, 0.005, d.bore * 1.5, 0.01, false);+ f.rotateX(Math.PI / 2);+ f.translate(0, y, 0);+ headGeoms.push(f);+ }+ const rockerBox = roundedBox(d.bore * 0.66, d.bore * 0.34, d.bore * 1.1, 0.014);+ rockerBox.rotateX(Math.PI / 2);+ rockerBox.translate(0, headY + d.headH / 2 + d.bore * 0.15, 0);+ headGeoms.push(rockerBox);+ g.add(+ part(mergeGeometries(headGeoms), MATERIALS.castAlloy, {+ name: 'head',+ group: grp,+ explode: new THREE.Vector3(0, 0.16, 0),+ }),+ );++ // Two rockers, front and rear, pivoting about the tangential axis.+ const rockers = [];+ for (const side of [-1, 1]) {+ const pivot = joint(`rocker-${side < 0 ? 'in' : 'ex'}`, {+ group: grp,+ position: new THREE.Vector3(0, headY + d.headH / 2 + d.bore * 0.14, side * d.bore * 0.3),+ });+ const arm = roundedBox(d.bore * 0.13, d.bore * 0.1, d.bore * 0.5, 0.008);+ arm.rotateX(Math.PI / 2);+ pivot.add(part(arm, MATERIALS.steel, { name: 'rocker arm', group: grp }));+ g.add(pivot);+ rockers.push({ pivot, side });+ }++ // Pushrod tubes running from the cam ring up the side of the barrel.+ const rods = [];+ for (const side of [-1, 1]) {+ const tube = new THREE.CylinderGeometry(0.017, 0.017, 1, 12);+ const mesh = part(tube, MATERIALS.steel, {+ name: 'pushrod tube',+ group: grp,+ explode: new THREE.Vector3(0, 0.05, side * 0.08),+ });+ const a = new THREE.Vector3(d.bore * 0.34 * (side < 0 ? -1 : 1), -0.02, side * d.bore * 0.24);+ const b = new THREE.Vector3(0, headY + d.headH / 2 + d.bore * 0.1, side * d.bore * 0.3);+ alignSegment(mesh, a, b);+ g.add(mesh);+ rods.push(mesh);+ }++ // Induction pipe: a bent tube, because a straight cylinder reads as a stub.+ g.add(+ part(bentInduction(d), MATERIALS.steel, {+ name: 'induction pipe',+ group: grp,+ explode: new THREE.Vector3(0, 0.1, -0.12),+ }),+ );++ return { group: g, rockers };+}++function bentInduction(d) {+ const headY = d.barrelLen + d.headH / 2;+ const pts = [+ new THREE.Vector3(0, 0.02, -d.bore * 0.62),+ new THREE.Vector3(0, d.barrelLen * 0.35, -d.bore * 0.9),+ new THREE.Vector3(0, d.barrelLen * 0.78, -d.bore * 0.86),+ new THREE.Vector3(0, headY - 0.01, -d.bore * 0.66),+ ];+ const curve = new THREE.CatmullRomCurve3(pts, false, 'catmullrom', 0.4);+ const g = new THREE.TubeGeometry(curve, 28, d.bore * 0.13, 14, false);+ g.computeVertexNormals();+ return g;+}++function propeller(d, v) {+ const g = new THREE.Group();+ g.name = 'propeller';+ const grp = 'propeller';+ const hub = lathe(+ [+ [0, 0], [d.propR * 0.13, 0], [d.propR * 0.15, 0.05],+ [d.propR * 0.12, 0.09], [d.propR * 0.07, 0.1], [0, 0.1],+ ],+ 40,+ );+ hub.rotateX(Math.PI / 2);+ g.add(part(hub, MATERIALS.steel, { name: 'hub', group: grp }));++ const spinner = lathe(+ [+ [0, 0], [d.propR * 0.115, 0], [d.propR * 0.108, 0.09],+ [d.propR * 0.075, 0.15], [d.propR * 0.03, 0.185], [0, 0.19],+ ],+ 40,+ );+ spinner.rotateX(Math.PI / 2);+ g.add(+ part(spinner, MATERIALS.paintRed, {+ name: 'spinner',+ group: grp,+ position: new THREE.Vector3(0, 0, 0.06),+ explode: new THREE.Vector3(0, 0, 0.42),+ }),+ );++ for (let i = 0; i < v.blades; i++) {+ const a = (i / v.blades) * Math.PI * 2;+ const blade = loftedBlade({+ span: d.propR - 0.11,+ chordRoot: d.propR * 0.17,+ chordTip: d.propR * 0.09,+ twistRoot: 34,+ twistTip: 8,+ rake: d.propR * 0.02,+ stations: 16,+ resolution: 16,+ });+ blade.rotateX(-Math.PI / 2);+ blade.translate(0, 0.11, 0);+ blade.rotateZ(a);+ g.add(+ part(blade, MATERIALS.graphite, {+ name: `blade ${i + 1}`,+ group: grp,+ explode: new THREE.Vector3(Math.cos(a) * 0.3, Math.sin(a) * 0.3, 0.2),+ }),+ );+ }+ const collar = boltRing({ count: v.blades * 3, radius: d.propR * 0.1, head: 0.011, height: 0.02, z: 0.02 });+ g.add(part(collar, MATERIALS.steel, { name: 'hub bolts', group: grp }));+ return g;+}++// Raised-cosine valve lift over a 240 degree cam window, the classic four-stroke+// profile. Returns 0 to 1.+function lift(phase) {+ const x = ((phase % 1) + 1) % 1;+ const window = 0.34;+ if (x > window) return 0;+ return 0.5 - 0.5 * Math.cos((x / window) * Math.PI * 2);+}++export function build(v) {+ const d = derive(v);+ const root = new THREE.Group();+ root.name = 'radial-nine';++ const cc = crankcase(d);+ root.add(+ part(cc.rear, MATERIALS.castAlloy, {+ name: 'rear case',+ group: 'crankcase',+ explode: new THREE.Vector3(0, 0, -0.55),+ }),+ );+ root.add(+ part(cc.front, MATERIALS.castAlloy, {+ name: 'front case',+ group: 'crankcase',+ explode: new THREE.Vector3(0, 0, 0.3),+ }),+ );+ const caseBolts = boltRing({ count: v.cylinders * 2, radius: d.caseR * 0.86, head: 0.013, height: 0.03, z: 0.05 });+ root.add(+ part(caseBolts, MATERIALS.steel, {+ name: 'case bolts',+ group: 'crankcase',+ explode: new THREE.Vector3(0, 0, 0.42),+ }),+ );++ // Crankshaft: two cheeks either side of one crankpin, on the engine axis.+ const crank = new THREE.Group();+ crank.name = 'crankshaft';+ crank.userData = { group: 'crankshaft', rest: crank.position.clone(), explode: new THREE.Vector3() };+ const journal = new THREE.CylinderGeometry(d.bore * 0.2, d.bore * 0.2, 0.42, 24);+ journal.rotateX(Math.PI / 2);+ crank.add(part(journal, MATERIALS.steel, { name: 'main journal', group: 'crankshaft' }));+ for (const z of [-0.075, 0.075]) {+ const cheek = new THREE.CylinderGeometry(d.throwR + d.bore * 0.2, d.throwR + d.bore * 0.2, 0.05, 28);+ cheek.rotateX(Math.PI / 2);+ cheek.translate(0, 0, z);+ crank.add(part(cheek, MATERIALS.steel, { name: 'crank cheek', group: 'crankshaft' }));+ }+ const crankpinGeo = new THREE.CylinderGeometry(d.bore * 0.21, d.bore * 0.21, 0.16, 24);+ crankpinGeo.rotateX(Math.PI / 2);+ crankpinGeo.translate(d.throwR, 0, 0);+ crank.add(part(crankpinGeo, MATERIALS.brass, { name: 'crankpin', group: 'crankshaft' }));+ root.add(crank);++ // Cylinders, pistons and rods.+ const cylinders = [];+ for (let i = 0; i < v.cylinders; i++) {+ const theta = (i / v.cylinders) * Math.PI * 2 + Math.PI / 2;+ const axis = new THREE.Vector2(Math.cos(theta), Math.sin(theta));+ const { group, rockers } = cylinderAssembly(d, v, i);+ group.position.set(axis.x * d.baseR, axis.y * d.baseR, 0);+ group.rotation.z = theta - Math.PI / 2;+ group.userData = {+ group: 'cylinders',+ rest: group.position.clone(),+ explode: new THREE.Vector3(axis.x * 0.34, axis.y * 0.34, 0),+ };+ root.add(group);++ // Skirt below the gudgeon pin, crown above it, so the pin sits inside the+ // piston where it belongs rather than under its base.+ const pistonGeo = lathe(+ [+ [0, -d.bore * 0.34], [d.bore * 0.47, -d.bore * 0.34], [d.bore * 0.49, -d.bore * 0.26],+ [d.bore * 0.49, d.crown - 0.012], [d.bore * 0.44, d.crown - 0.004],+ [d.bore * 0.2, d.crown], [0, d.crown],+ ],+ 32,+ );+ pistonGeo.rotateZ(-Math.PI / 2);+ const piston = part(pistonGeo, MATERIALS.castAlloy, {+ name: `piston ${i + 1}`,+ group: 'pistons',+ explode: new THREE.Vector3(axis.x * 0.62, axis.y * 0.62, 0),+ });+ piston.rotation.z = theta;+ root.add(piston);++ const rodGeo = rodGeometry({+ length: d.rod,+ bigEndR: d.bore * 0.24,+ smallEndR: d.bore * 0.12,+ thickness: d.bore * 0.16,+ });+ const rod = part(rodGeo, MATERIALS.steel, {+ name: `rod ${i + 1}`,+ group: 'pistons',+ explode: new THREE.Vector3(axis.x * 0.48, axis.y * 0.48, 0),+ });+ root.add(rod);++ cylinders.push({ theta, axis, piston, rod, rockers, index: i });+ }++ const prop = propeller(d, v);+ prop.position.z = 0.3;+ prop.userData = {+ group: 'propeller',+ rest: prop.position.clone(),+ explode: new THREE.Vector3(0, 0, 0.75),+ };+ root.add(prop);++ const pin = new THREE.Vector2();+ const geared = 0.5; // reduction gear: the prop turns at half crank speed++ function update(angle) {+ crank.rotation.z = angle;+ pin.set(Math.cos(angle) * d.throwR, Math.sin(angle) * d.throwR);+ prop.rotation.z = angle * geared;+ for (const c of cylinders) {+ const dist = slider(pin, c.axis, d.rod);+ c.piston.position.set(c.axis.x * dist, c.axis.y * dist, 0);+ c.piston.userData.rest.copy(c.piston.position);+ const px = c.axis.x * dist;+ const py = c.axis.y * dist;+ c.rod.position.set(pin.x, pin.y, 0);+ c.rod.userData.rest.copy(c.rod.position);+ c.rod.rotation.z = Math.atan2(py - pin.y, px - pin.x);+ // Cam ring phasing. An odd-cylinder radial fires alternate cylinders,+ // so physical cylinder i sits (i * (n + 1) / 2) mod n intervals into a+ // cycle, and one four-stroke cycle takes two crank revolutions.+ const order = ((c.index * (v.cylinders + 1)) / 2) % v.cylinders;+ const cycle = angle / (Math.PI * 4) - order / v.cylinders;+ for (let k = 0; k < c.rockers.length; k++) {+ const r = c.rockers[k];+ r.pivot.rotation.x = r.side * lift(cycle + k * 0.5) * 0.32;+ }+ }+ }++ update(0);++ const readout = [+ ['Displacement', `${d.displacement.toFixed(1)} L`],+ ['Bore x stroke', `${v.bore} x ${v.stroke} mm`],+ ['Rod length', `${(d.rod * 1000).toFixed(0)} mm`],+ ['Frontal diameter', `${((d.deck + d.headH + 0.03) * 2).toFixed(2)} m`],+ ];++ return { root, update, readout, cyclesPerTurn: 1 };+}diff --git a/src/assembly/rig.js b/src/assembly/rig.jsnew file mode 100644index 000000000..6b368715c--- /dev/null+++ b/src/assembly/rig.js@@ -0,0 +1,133 @@+// The small runtime every machine in the atlas is built on.+//+// A machine is a tree of `part()` meshes. Each part records where it rests when+// assembled and which way it flies when the assembly is exploded, so explode /+// reassemble is one lerp over the tree rather than a hand-keyed animation.++import * as THREE from 'three';++// Create a named, explodable mesh. `explode` is a metre offset applied at+// factor 1; `group` names the subassembly it belongs to in the parts list.+export function part(geometry, material, { name, group, explode, position, rotation, scale } = {}) {+ const mesh = new THREE.Mesh(geometry, material);+ mesh.name = name || 'part';+ mesh.castShadow = true;+ mesh.receiveShadow = true;+ if (position) mesh.position.copy(position);+ if (rotation) mesh.rotation.copy(rotation);+ if (scale) mesh.scale.copy(scale);+ mesh.userData.group = group || 'frame';+ mesh.userData.rest = mesh.position.clone();+ mesh.userData.explode = explode ? explode.clone() : new THREE.Vector3();+ return mesh;+}++// A pivot that participates in explode without carrying geometry itself.+export function joint(name, { group, explode, position } = {}) {+ const g = new THREE.Group();+ g.name = name;+ if (position) g.position.copy(position);+ g.userData.group = group || 'frame';+ g.userData.rest = g.position.clone();+ g.userData.explode = explode ? explode.clone() : new THREE.Vector3();+ return g;+}++const _v = new THREE.Vector3();++// Walk the tree once and place everything between rest and exploded. Called+// every frame while the factor is moving and never after it settles.+export function applyExplode(root, factor) {+ root.traverse((o) => {+ const rest = o.userData && o.userData.rest;+ if (!rest) return;+ const e = o.userData.explode;+ o.position.copy(rest).add(_v.copy(e).multiplyScalar(factor));+ });+}++// Group ids present in a machine, in the order they first appear, so the parts+// list reads top-down through the assembly instead of alphabetically.+export function groupsOf(root) {+ const seen = [];+ root.traverse((o) => {+ const g = o.userData && o.userData.group;+ if (g && !seen.includes(g)) seen.push(g);+ });+ return seen;+}++export function setGroupVisible(root, group, visible) {+ root.traverse((o) => {+ if (o.userData && o.userData.group === group) o.visible = visible;+ });+}++const _a = new THREE.Vector3();+const _b = new THREE.Vector3();+const _up = new THREE.Vector3(0, 1, 0);+const _q = new THREE.Quaternion();++// Point a unit-length +Y primitive (a cylinder, a tube, a guide bar) at the+// segment a to b and stretch it to fit. Geometry stays unit length so the same+// buffer serves a link whose length changes every frame.+export function alignSegment(mesh, a, b) {+ _a.copy(a);+ _b.copy(b).sub(_a);+ const len = _b.length();+ mesh.position.copy(_a).addScaledVector(_b, 0.5);+ if (mesh.userData) mesh.userData.rest = mesh.position.clone();+ if (len > 1e-6) {+ _q.setFromUnitVectors(_up, _b.divideScalar(len));+ mesh.quaternion.copy(_q);+ mesh.scale.y = len;+ }+ return len;+}++// Slider-crank solved in the plane: given a crankpin at `pin` and a rod of+// length `rod` whose far end is constrained to the line through the origin in+// direction `axis`, return the distance from the origin to that far end.+// This is the exact solution, not an approximation, so a long rod and a short+// one give visibly different piston motion the way real engines do.+export function slider(pin, axis, rod) {+ const proj = pin.x * axis.x + pin.y * axis.y;+ const disc = rod * rod - (pin.x * pin.x + pin.y * pin.y) + proj * proj;+ return proj + Math.sqrt(Math.max(disc, 0));+}++// Where two circles meet. `sign` picks which of the two intersections to take,+// which is how a linkage stays on one branch of its solution instead of+// snapping through itself halfway round a revolution. Returns null when the+// links cannot reach, so a bad parameter set degrades to "hold the last pose"+// rather than to NaN geometry.+export function circleIntersect(c1, r1, c2, r2, sign = 1) {+ const dx = c2.x - c1.x;+ const dy = c2.y - c1.y;+ const dist = Math.hypot(dx, dy);+ if (dist < 1e-9 || dist > r1 + r2 || dist < Math.abs(r1 - r2)) return null;+ const a = (r1 * r1 - r2 * r2 + dist * dist) / (2 * dist);+ const h2 = r1 * r1 - a * a;+ if (h2 < 0) return null;+ const h = Math.sqrt(h2);+ const mx = c1.x + (a * dx) / dist;+ const my = c1.y + (a * dy) / dist;+ return new THREE.Vector2(mx + (sign * h * dy) / dist, my - (sign * h * dx) / dist);+}++// A pin on a horizontal line, reached from `centre` by a link of length `len`.+// The crosshead and the valve spindle both ride lines like this.+export function slideOnLine(centre, y, len, sign = 1) {+ const dy = y - centre.y;+ const disc = len * len - dy * dy;+ if (disc < 0) return null;+ return new THREE.Vector2(centre.x + sign * Math.sqrt(disc), y);+}++// Place a planar link mesh built by `rodGeometry` (big end at the origin,+// running +X) so its ends land on a and b.+export function placeLink(mesh, a, b, z = 0) {+ mesh.position.set(a.x, a.y, z);+ if (mesh.userData) mesh.userData.rest.copy(mesh.position);+ mesh.rotation.z = Math.atan2(b.y - a.y, b.x - a.x);+}diff --git a/tests/assembly-machines.test.js b/tests/assembly-machines.test.jsnew file mode 100644index 000000000..da284ee2a--- /dev/null+++ b/tests/assembly-machines.test.js@@ -0,0 +1,241 @@+/**+ * Machine Atlas (/assembly) — geometry and kinematics.+ *+ * These machines have no model files behind them, so the only thing standing+ * between a slider and a broken frame is the maths. Two classes of failure are+ * worth a test: geometry that comes out non-finite (a NaN in one vertex kills+ * the whole draw call), and a linkage that cannot physically close at some+ * parameter combination, which would freeze the motion silently.+ */++import { describe, it, expect } from 'vitest';+import { Vector2 } from 'three';+import * as radial from '../src/assembly/radial-engine.js';+import * as locomotive from '../src/assembly/locomotive.js';+import { slider, circleIntersect, slideOnLine } from '../src/assembly/rig.js';+import { finnedBarrel, loftedBlade, spokedWheel } from '../src/assembly/parts.js';++const MACHINES = [radial, locomotive];++function defaults(machine) {+ const v = {};+ for (const p of machine.spec.params) v[p.key] = p.value;+ return v;+}++// Every combination of each parameter's low, default and high value is too many+// builds; the corners plus the defaults catch the cases that actually break.+function extremes(machine) {+ const base = defaults(machine);+ const sets = [base];+ for (const p of machine.spec.params) {+ sets.push({ ...base, [p.key]: p.min }, { ...base, [p.key]: p.max });+ }+ sets.push(Object.fromEntries(machine.spec.params.map((p) => [p.key, p.min])));+ sets.push(Object.fromEntries(machine.spec.params.map((p) => [p.key, p.max])));+ return sets;+}++function everyVertexFinite(root) {+ let checked = 0;+ root.traverse((o) => {+ if (!o.isMesh) return;+ const pos = o.geometry.getAttribute('position');+ for (let i = 0; i < pos.count; i++) {+ if (!Number.isFinite(pos.getX(i)) || !Number.isFinite(pos.getY(i)) || !Number.isFinite(pos.getZ(i))) {+ throw new Error(`non-finite vertex ${i} in ${o.name}`);+ }+ }+ checked++;+ });+ return checked;+}++describe('machine specs', () => {+ it('give every parameter a default inside its own range and on its step grid', () => {+ for (const m of MACHINES) {+ for (const p of m.spec.params) {+ expect(p.value, `${m.spec.id}.${p.key}`).toBeGreaterThanOrEqual(p.min);+ expect(p.value, `${m.spec.id}.${p.key}`).toBeLessThanOrEqual(p.max);+ const steps = (p.value - p.min) / p.step;+ expect(Math.abs(steps - Math.round(steps)), `${m.spec.id}.${p.key}`).toBeLessThan(1e-6);+ }+ }+ });++ it('uses unique machine ids and non-empty copy', () => {+ const ids = MACHINES.map((m) => m.spec.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const m of MACHINES) {+ expect(m.spec.name.length).toBeGreaterThan(0);+ expect(m.spec.blurb.length).toBeGreaterThan(20);+ expect(m.spec.facts.length).toBeGreaterThan(0);+ }+ });++ it('generates code samples from the live values, so they track the geometry', () => {+ const v = defaults(radial);+ const before = radial.codeFor(v).map((s) => s.code).join('\n');+ const after = radial.codeFor({ ...v, bore: v.bore + 10 }).map((s) => s.code).join('\n');+ expect(before).not.toBe(after);+ for (const m of MACHINES) {+ for (const sample of m.codeFor(defaults(m))) {+ expect(sample.code).not.toMatch(/NaN|undefined/);+ }+ }+ });+});++describe('geometry generation', () => {+ it('builds both machines with finite geometry across the parameter extremes', () => {+ for (const m of MACHINES) {+ for (const values of extremes(m)) {+ const built = m.build(values);+ expect(everyVertexFinite(built.root)).toBeGreaterThan(4);+ }+ }+ });++ it('adds a fin to the barrel for every fin asked for', () => {+ const a = finnedBarrel({ bore: 0.15, length: 0.3, fins: 10, segments: 8 });+ const b = finnedBarrel({ bore: 0.15, length: 0.3, fins: 30, segments: 8 });+ expect(b.getAttribute('position').count).toBeGreaterThan(a.getAttribute('position').count);+ });++ it('lofts a blade whose sections taper and twist', () => {+ const g = loftedBlade({ span: 1, chordRoot: 0.2, chordTip: 0.1, twistRoot: 30, twistTip: 5 });+ const pos = g.getAttribute('position');+ let rootWidth = 0;+ let tipWidth = 0;+ for (let i = 0; i < pos.count; i++) {+ const z = pos.getZ(i);+ if (z < 0.02) rootWidth = Math.max(rootWidth, Math.abs(pos.getX(i)));+ if (z > 0.9) tipWidth = Math.max(tipWidth, Math.abs(pos.getX(i)));+ }+ expect(rootWidth).toBeGreaterThan(tipWidth);+ expect(g.getAttribute('normal')).toBeTruthy();+ });++ it('leaves the wheel face open so the spokes are visible', () => {+ const g = spokedWheel({ radius: 0.8, spokes: 16, crankRadius: 0.35 });+ const pos = g.getAttribute('position');+ let found = false;+ for (let i = 0; i < pos.count && !found; i++) {+ // A spoke sits between hub and rim; a solid disc would have no+ // geometry at mid radius other than the closing faces.+ const r = Math.hypot(pos.getX(i), pos.getY(i));+ if (r > 0.35 && r < 0.6 && Math.abs(pos.getZ(i)) < 0.05) found = true;+ }+ expect(found).toBe(true);+ });+});++describe('radial engine kinematics', () => {+ it('solves the slider-crank exactly at top and bottom dead centre', () => {+ const rod = 0.35;+ const throwR = 0.0875;+ const axis = new Vector2(1, 0);+ const tdc = slider(new Vector2(throwR, 0), axis, rod);+ const bdc = slider(new Vector2(-throwR, 0), axis, rod);+ expect(tdc).toBeCloseTo(throwR + rod, 10);+ expect(bdc).toBeCloseTo(rod - throwR, 10);+ expect(tdc - bdc).toBeCloseTo(throwR * 2, 10);+ });++ it('keeps every piston inside its bore for a full revolution', () => {+ const v = defaults(radial);+ const d = radial.derive(v);+ const built = radial.build(v);+ const pistons = [];+ built.root.traverse((o) => {+ if (o.isMesh && o.name.startsWith('piston')) pistons.push(o);+ });+ expect(pistons.length).toBe(v.cylinders);+ for (let i = 0; i < 72; i++) {+ built.update((i / 72) * Math.PI * 2);+ for (const p of pistons) {+ const radius = Math.hypot(p.position.x, p.position.y);+ expect(radius + d.crown).toBeLessThanOrEqual(d.deck + 1e-9);+ expect(radius).toBeGreaterThan(d.baseR - d.bore * 0.34);+ }+ }+ });++ it('gives a longer rod a longer dwell near top dead centre', () => {+ const axis = new Vector2(1, 0);+ const throwR = 0.09;+ const dwell = (rod) => {+ const top = throwR + rod;+ let count = 0;+ for (let i = 0; i < 720; i++) {+ const a = (i / 720) * Math.PI * 2;+ const pin = new Vector2(Math.cos(a) * throwR, Math.sin(a) * throwR);+ if (top - slider(pin, axis, rod) < throwR * 0.05) count++;+ }+ return count;+ };+ expect(dwell(0.36)).toBeGreaterThan(dwell(0.16));+ });+});++describe('locomotive valve gear', () => {+ it('sizes the rocking lever so the eccentric can always reach it', () => {+ for (const values of extremes(locomotive)) {+ const d = locomotive.derive(values);+ expect(d.armLow, JSON.stringify(values)).toBeGreaterThanOrEqual(d.rho);+ }+ });++ it('closes the four-bar chain at every crank angle, for every parameter set', () => {+ for (const values of extremes(locomotive)) {+ const d = locomotive.derive(values);+ for (let i = 0; i < 90; i++) {+ const a = (i / 90) * Math.PI * 2;+ const ecc = new Vector2(+ d.mainX + d.pinR * Math.cos(a) + d.rE * Math.cos(a + d.psi),+ d.pinR * Math.sin(a) + d.rE * Math.sin(a + d.psi),+ );+ const low = circleIntersect(ecc, d.eccRod, d.rockPivot, d.armLow, 1);+ expect(low, `${JSON.stringify(values)} at ${i}`).not.toBeNull();+ }+ }+ });++ it('keeps the crosshead on its centreline and inside the guide bars', () => {+ const values = defaults(locomotive);+ const d = locomotive.derive(values);+ let min = Infinity;+ let max = -Infinity;+ for (let i = 0; i < 180; i++) {+ const a = (i / 180) * Math.PI * 2;+ const pin = new Vector2(d.mainX + d.pinR * Math.cos(a), d.pinR * Math.sin(a));+ const cross = slideOnLine(pin, d.yC, d.mainRod, 1);+ expect(cross).not.toBeNull();+ expect(cross.y).toBeCloseTo(d.yC, 12);+ min = Math.min(min, cross.x);+ max = Math.max(max, cross.x);+ }+ // Crosshead travel is the piston stroke the slider names. The cylinder+ // centreline sits slightly above the axle, so the travel comes out a+ // fraction longer than twice the crank radius, exactly as it does on a+ // real engine with inclined cylinders. It must never come out shorter.+ const travel = max - min;+ expect(travel).toBeGreaterThanOrEqual(d.pinR * 2);+ expect(travel).toBeLessThan(d.pinR * 2 * 1.02);+ expect(max).toBeLessThanOrEqual(d.cylRear);+ });++ it('couples every driver to the same crank angle', () => {+ const values = defaults(locomotive);+ const built = locomotive.build(values);+ const drivers = [];+ built.root.traverse((o) => {+ if (o.isMesh && o.name.startsWith('driver')) drivers.push(o);+ });+ expect(drivers.length).toBe(values.drivers * 2);+ built.update(1.1);+ const angles = new Set(drivers.map((o) => o.rotation.z.toFixed(6)));+ // Two sides, quartered ninety degrees apart, so exactly two angles.+ expect(angles.size).toBe(2);+ });+});