Prompt specification
Build or customize the Three.js 3D scene "Telegraph key with visible switch contacts" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Telegraph key with visible switch contacts
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/telegraph-key-with-visible-switch-contacts-x2541
Scene Description Prompt:
Build a telegraph key with lever, spring, and two contacts. Show the circuit closing when pressed and distinguish the mechanical motion from the electrical signal. Build this with Three.js from cdnjs as a stylized scene in one self-contained HTML file.
Working Three.js Starter (telegraph-key-with-visible-switch-contacts-x2541):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Telegraph Key — Mechanical Motion vs. Electrical Signal</title>
<style>
:root {
color-scheme: dark;
--bg: #07111a;
--panel: rgba(9, 22, 32, 0.82);
--border: rgba(164, 210, 226, 0.16);
--text: #e9f7fb;
--muted: #88a6b3;
--mechanical: #f4b45f;
--electrical: #62f4ff;
--danger: #ff7f70;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 4;
}
.title-block {
position: absolute;
top: 28px;
left: 30px;
max-width: 420px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.5);
}
.eyebrow {
color: var(--electrical);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 8px;
font-size: clamp(29px, 4vw, 48px);
line-height: 0.98;
letter-spacing: -0.045em;
font-weight: 720;
}
.subtitle {
margin: 0;
max-width: 350px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.legend {
display: flex;
gap: 18px;
margin-top: 18px;
color: #b8ccd4;
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
}
.legend-dot {
width: 9px;
height: 9px;
border-radius: 50%;
box-shadow: 0 0 13px currentColor;
}
.legend-dot.mechanical {
color: var(--mechanical);
background: var(--mechanical);
}
.legend-dot.electrical {
color: var(--electrical);
background: var(--electrical);
}
.readout {
position: absolute;
top: 28px;
right: 28px;
width: 278px;
padding: 17px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(15px);
}
.state-row {
display: flex;
align-items: center;
gap: 10px;
padding-bottom: 13px;
border-bottom: 1px solid var(--border);
}
.state-led {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--danger);
box-shadow: 0 0 14px rgba(255, 127, 112, 0.7);
transition: background 120ms, box-shadow 120ms;
}
.readout.closed .state-led {
background: var(--electrical);
box-shadow: 0 0 17px rgba(98, 244, 255, 0.95);
}
.state-title {
font-size: 12px;
font-weight: 780;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.state-subtitle {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.meter {
margin-top: 14px;
}
.meter-header {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
color: #a9c0c9;
font-size: 10px;
font-weight: 650;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.meter-value {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.track {
height: 4px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.07);
}
.fill {
width: 0;
height: 100%;
border-radius: inherit;
transition: width 70ms linear;
}
#travelFill {
background: var(--mechanical);
box-shadow: 0 0 12px rgba(244, 180, 95, 0.55);
}
#springFill {
background: #f2d09b;
box-shadow: 0 0 12px rgba(242, 208, 155, 0.4);
}
#currentFill {
background: var(--electrical);
box-shadow: 0 0 12px rgba(98, 244, 255, 0.8);
}
.controls {
position: absolute;
right: 28px;
bottom: 25px;
display: flex;
align-items: center;
gap: 10px;
pointer-events: auto;
}
button {
border: 1px solid rgba(244, 180, 95, 0.45);
border-radius: 11px;
padding: 13px 17px;
color: #15100a;
background: linear-gradient(180deg, #ffd394, #e5a44f);
box-shadow: 0 8px 26px rgba(0, 0, 0, 0.25);
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
transition: transform 100ms, filter 100ms, box-shadow 100ms;
user-select: none;
-webkit-user-select: none;
touch-action: none;
}
button:hover {
filter: brightness(1.07);
}
button:active,
button.active {
transform: translateY(2px);
filter: brightness(1.12);
box-shadow: 0 3px 14px rgba(0, 0, 0, 0.28),
0 0 0 3px rgba(244, 180, 95, 0.12);
}
button.secondary {
border-color: var(--border);
color: #b9d0d8;
background: rgba(12, 28, 39, 0.8);
box-shadow: none;
}
.hint {
position: absolute;
left: 30px;
bottom: 28px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.05em;
}
.hint strong {
color: #d4e7ed;
font-weight: 700;
}
.leaders {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
overflow: visible;
pointer-events: none;
z-index: 2;
}
.leader-line {
stroke-width: 1;
opacity: 0.68;
}
.leader-line.mechanical {
stroke: var(--mechanical);
}
.leader-line.electrical {
stroke: var(--electrical);
}
.leader-dot {
stroke-width: 1;
opacity: 0.9;
}
.leader-dot.mechanical {
fill: var(--mechanical);
stroke: #ffe0b0;
}
.leader-dot.electrical {
fill: var(--electrical);
stroke: #d9fdff;
}
.callout {
position: absolute;
top: 0;
left: 0;
z-index: 3;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 7px;
color: #d9e8ed;
background: rgba(6, 16, 24, 0.84);
box-shadow: 0 7px 20px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(8px);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.12em;
line-height: 1;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-999px, -999px);
}
.callout.mechanical {
border-color: rgba(244, 180, 95, 0.32);
}
.callout.electrical {
border-color: rgba(98, 244, 255, 0.32);
}
@media (max-width: 760px) {
.title-block {
top: 18px;
left: 18px;
}
.subtitle,
.legend {
display: none;
}
.readout {
top: auto;
right: 15px;
bottom: 78px;
width: 218px;
padding: 13px;
}
.controls {
right: 15px;
bottom: 18px;
}
.hint {
left: 18px;
bottom: 21px;
max-width: 145px;
line-height: 1.5;
}
.callout {
font-size: 8px;
padding: 6px 7px;
}
}
</style>
</head>
<body>
<svg class="leaders" id="leaders" aria-hidden="true"></svg>
<div class="ui">
<header class="title-block">
<div class="eyebrow">Interactive mechanism study</div>
<h1>Telegraph Key</h1>
<p class="subtitle">
A warm brass mechanism drives the lever and compresses the return spring.
A separate cyan circuit shows current only when the contacts physically meet.
</p>
<div class="legend">
<div class="legend-item">
<span class="legend-dot mechanical"></span>
Mechanical motion
</div>
<div class="legend-item">
<span class="legend-dot electrical"></span>
Electrical signal
</div>
</div>
</header>
<section class="readout" id="readout" aria-live="polite">
<div class="state-row">
<span class="state-led"></span>
<div>
<div class="state-title" id="stateTitle">Open circuit</div>
<div class="state-subtitle" id="stateSubtitle">Contacts separated · no current</div>
</div>
</div>
<div class="meter">
<div class="meter-header">
<span>Lever travel</span>
<span class="meter-value" id="travelValue">0%</span>
</div>
<div class="track"><div class="fill" id="travelFill"></div></div>
</div>
<div class="meter">
<div class="meter-header">
<span>Spring compression</span>
<span class="meter-value" id="springValue">0%</span>
</div>
<div class="track"><div class="fill" id="springFill"></div></div>
</div>
<div class="meter">
<div class="meter-header">
<span>Electrical current</span>
<span class="meter-value" id="currentValue">Idle</span>
</div>
<div class="track"><div class="fill" id="currentFill"></div></div>
</div>
</section>
<div class="hint">
<strong>Hold to press</strong><br />
Click the knob or hold Space · drag to orbit
</div>
<div class="controls">
<button class="secondary" id="resetView" type="button">Reset view</button>
<button id="pressButton" type="button" aria-pressed="false">Hold to press</button>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene and renderer
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111a);
scene.fog = new THREE.FogExp2(0x07111a, 0.024);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0.35, 1.15, 0);
let cameraTheta = 0.68;
let cameraPhi = 0.98;
let cameraRadius = 16;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xb9eaff, 0x17202a, 1.35);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffe0b0, 3.4);
keyLight.position.set(3.5, 10, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0002;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x56dfff, 2.0);
rimLight.position.set(-7, 5, -7);
scene.add(rimLight);
const fillLight = new THREE.PointLight(0x5bbcff, 18, 18, 2);
fillLight.position.set(-4, 4, 5);
scene.add(fillLight);
// -------------------------------------------------------------------------
// Materials
// -------------------------------------------------------------------------
const materials = {
base: new THREE.MeshStandardMaterial({
color: 0x0b1721,
metalness: 0.55,
roughness: 0.36
}),
baseTop: new THREE.MeshStandardMaterial({
color: 0x122532,
metalness: 0.48,
roughness: 0.42
}),
blackMetal: new THREE.MeshStandardMaterial({
color: 0x111c25,
metalness: 0.78,
roughness: 0.3
}),
brass: new THREE.MeshStandardMaterial({
color: 0xd99b4b,
metalness: 0.82,
roughness: 0.24
}),
brightBrass: new THREE.MeshStandardMaterial({
color: 0xf3bd70,
metalness: 0.72,
roughness: 0.2
}),
steel: new THREE.MeshStandardMaterial({
color: 0xb9c7cd,
metalness: 0.88,
roughness: 0.25
}),
rubber: new THREE.MeshStandardMaterial({
color: 0x070b0e,
metalness: 0.08,
roughness: 0.72
}),
wire: new THREE.MeshStandardMaterial({
color: 0x123746,
emissive: 0x00bfd4,
emissiveIntensity: 0.04,
metalness: 0.34,
roughness: 0.38
}),
glass: new THREE.MeshStandardMaterial({
color: 0x7befff,
emissive: 0x00dff4,
emissiveIntensity: 0.05,
metalness: 0.05,
roughness: 0.15,
transparent: true,
opacity: 0.74
}),
signal: new THREE.MeshBasicMaterial({
color: 0xa7ffff,
transparent: true,
opacity: 0.96
})
};
function addMesh(
geometry,
material,
position = [0, 0, 0],
parent = scene,
castShadow = true
) {
const mesh = new THREE.Mesh(geometry, material);
if (position instanceof THREE.Vector3) {
mesh.position.copy(position);
} else {
mesh.position.set(...position);
}
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addBox(w, h, d, material, position, parent = scene) {
return addMesh(new THREE.BoxGeometry(w, h, d), material, position, parent);
}
function addCylinder(
radius,
height,
material,
position,
parent = scene,
radialSegments = 32
) {
return addMesh(
new THREE.CylinderGeometry(radius, radius, height, radialSegments),
material,
position,
parent
);
}
// -------------------------------------------------------------------------
// Desk and key base
// -------------------------------------------------------------------------
const desk = addMesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x08131b,
metalness: 0.18,
roughness: 0.78
}),
[0, -0.015, 0],
scene,
false
);
desk.rotation.x = -Math.PI / 2;
const grid = new THREE.GridHelper(50, 50, 0x284c5b, 0x17323e);
grid.position.y = 0.002;
grid.material.transparent = true;
grid.material.opacity = 0.18;
scene.add(grid);
addBox(9.45, 0.72, 4.6, materials.base, [0, 0.52, 0]);
addBox(9.58, 0.09, 4.73, materials.brass, [0, 0.82, 0]);
addBox(9.18, 0.12, 4.34, materials.baseTop, [0, 0.93, 0]);
const footPositions = [
[-3.9, -1.7],
[3.9, -1.7],
[-3.9, 1.7],
[3.9, 1.7]
];
for (const [x, z] of footPositions) {
addCylinder(0.28, 0.2, materials.rubber, [x, 0.1, z]);
}
// Decorative screws.
for (const x of [-4.15, 4.15]) {
for (const z of [-1.85, 1.85]) {
addCylinder(0.085, 0.025, materials.brightBrass, [x, 1.005, z]);
}
}
// -------------------------------------------------------------------------
// Lever assembly
// -------------------------------------------------------------------------
const pivot = new THREE.Vector3(-0.35, 1.65, 0);
const lever = new THREE.Group();
lever.position.copy(pivot);
scene.add(lever);
// Main black-enamel lever rail and brass top strip.
addBox(7.35, 0.25, 0.52, materials.blackMetal, [0.6, 0, 0], lever);
addBox(6.85, 0.055, 0.29, materials.brass, [0.6, 0.155, 0], lever);
// Rounded end cap.
const endCap = addCylinder(
0.27,
0.52,
materials.brass,
[-3.07, 0, 0],
lever
);
endCap.rotation.x = Math.PI / 2;
// Pivot hub.
const hub = addCylinder(0.26, 0.82, materials.brass, [0, 0, 0], lever);
hub.rotation.x = Math.PI / 2;
// Pivot supports and axle.
addBox(0.9, 0.62, 0.23, materials.blackMetal, [-0.35, 1.27, -0.5]);
addBox(0.9, 0.62, 0.23, materials.blackMetal, [-0.35, 1.27, 0.5]);
const axle = addCylinder(0.17, 1.4, materials.steel, [-0.35, 1.65, 0]);
axle.rotation.x = Math.PI / 2;
for (const z of [-0.76, 0.76]) {
const cap = addCylinder(0.25, 0.12, materials.brass, [-0.35, 1.65, z]);
cap.rotation.x = Math.PI / 2;
}
// Brass press knob.
const knob = new THREE.Group();
knob.position.set(3.55, 0, 0);
lever.add(knob);
addCylinder(0.58, 0.28, materials.brass, [0, 0, 0], knob, 48);
addCylinder(0.43, 0.075, materials.blackMetal, [0, 0.17, 0], knob, 48);
const knobRing = addMesh(
new THREE.TorusGeometry(0.48, 0.025, 10, 64),
materials.brightBrass,
[0, 0.16, 0],
knob
);
knobRing.rotation.x = Math.PI / 2;
// Invisible but raycastable press target.
const pressTarget = addMesh(
new THREE.SphereGeometry(0.8, 20, 14),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
}),
[0, 0.12, 0],
knob,
false
);
// Moving electrical contact on the lever.
const movingContactLocal = new THREE.Vector3(-2.6, 0.18, 0);
const movingContact = addMesh(
new THREE.SphereGeometry(0.16, 28, 20),
materials.brightBrass,
movingContactLocal,
lever
);
addCylinder(
0.065,
0.25,
materials.brass,
[-2.6, 0.03, 0],
lever,
20
);
// Fixed contact and its support.
const fixedContactPosition = new THREE.Vector3(-2.905, 2.18, 0);
const fixedContact = addMesh(
new THREE.SphereGeometry(0.16, 28, 20),
materials.brightBrass,
fixedContactPosition
);
addCylinder(
0.11,
1.06,
materials.brass,
[-2.92, 1.47, 0.48],
scene,
24
);
addBox(0.22, 0.12, 0.62, materials.brass, [-2.92, 2.02, 0.25]);
addCylinder(0.22, 0.09, materials.brass, [-2.92, 1.0, 0.48]);
// -------------------------------------------------------------------------
// Return spring
// -------------------------------------------------------------------------
const springPoints = [];
const springTurns = 11;
const springSegments = 180;
for (let i = 0; i <= springSegments; i++) {
const t = i / springSegments;
const angle = t * Math.PI * 2 * springTurns;
springPoints.push(
new THREE.Vector3(
Math.cos(angle) * 0.105,
t,
Math.sin(angle) * 0.105
)
);
}
const springCurve = new THREE.CatmullRomCurve3(springPoints);
const springGeometry = new THREE.TubeGeometry(springCurve, 240, 0.037, 8, false);
const springMaterial = new THREE.MeshStandardMaterial({
color: 0xd6e3e7,
metalness: 0.9,
roughness: 0.23
});
const spring = addMesh(springGeometry, springMaterial, [0, 0, 0]);
spring.castShadow = true;
const springLower = new THREE.Vector3(2.35, 0.74, 0.45);
const springUpperLocal = new THREE.Vector3(2.35, -0.22, 0.45);
const springLowerCap = addMesh(
new THREE.SphereGeometry(0.09, 18, 12),
materials.steel,
springLower
);
const springUpperCap = addMesh(
new THREE.SphereGeometry(0.09, 18, 12),
materials.steel,
springLower
);
// -------------------------------------------------------------------------
// Mechanical motion guide: rest ghost and pivot arc
// -------------------------------------------------------------------------
const restAngle = 0.045;
const pressedAngle = -0.13;
const ghostGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(pivot.x, pivot.y, 0.72),
new THREE.Vector3(
pivot.x + Math.cos(restAngle) * 4.2,
pivot.y + Math.sin(restAngle) * 4.2,
0.72
)
]);
const ghostLine = new THREE.Line(
ghostGeometry,
new THREE.LineDashedMaterial({
color: 0xf4b45f,
dashSize: 0.14,
gapSize: 0.11,
transparent: true,
opacity: 0.38
})
);
ghostLine.computeLineDistances();
scene.add(ghostLine);
const arcPoints = [];
for (let i = 0; i <= 36; i++) {
const angle = THREE.MathUtils.lerp(restAngle, pressedAngle, i / 36);
arcPoints.push(
new THREE.Vector3(
pivot.x + Math.cos(angle) * 1.06,
pivot.y + Math.sin(angle) * 1.06,
0.72
)
);
}
const arcLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(arcPoints),
new THREE.LineDashedMaterial({
color: 0xf4b45f,
dashSize: 0.08,
gapSize: 0.055,
transparent: true,
opacity: 0.72
})
);
arcLine.computeLineDistances();
scene.add(arcLine);
// -------------------------------------------------------------------------
// Binding posts and signal lamp
// -------------------------------------------------------------------------
const fixedPostPosition = new THREE.Vector3(-3.65, 1.11, 1.45);
const movingPostPosition = new THREE.Vector3(2.95, 1.11, 1.45);
for (const post of [fixedPostPosition, movingPostPosition]) {
addCylinder(0.14, 0.24, materials.steel, post);
addCylinder(0.22, 0.09, materials.brass, [post.x, post.y + 0.15, post.z]);
}
const lampX = 5.55;
addCylinder(0.62, 0.26, materials.blackMetal, [lampX, 0.15, 0], scene, 40);
addCylinder(0.24, 0.29, materials.brass, [lampX, 0.4, 0], scene, 32);
addCylinder(0.095, 0.87, materials.steel, [lampX, 0.9, 0], scene, 24);
addCylinder(0.31, 0.26, materials.blackMetal, [lampX, 1.31, 0], scene, 32);
const bulb = addMesh(
new THREE.SphereGeometry(0.33, 32, 24),
materials.glass,
[lampX, 1.64, 0]
);
const bulbCore = addMesh(
new THREE.SphereGeometry(0.18, 24, 18),
new THREE.MeshBasicMaterial({
color: 0x84fbff,
transparent: true,
opacity: 0.36
}),
[lampX, 1.64, 0],
scene,
false
);
// Protective cage around the bulb.
for (const y of [1.42, 1.87]) {
const ring = addMesh(
new THREE.TorusGeometry(0.39, 0.022, 8, 48),
materials.brass,
[lampX, y, 0]
);
ring.rotation.x = Math.PI / 2;
}
for (let i = 0; i < 4; i++) {
const angle = i * Math.PI / 2 + Math.PI / 4;
const x = lampX + Math.cos(angle) * 0.38;
const z = Math.sin(angle) * 0.38;
const rod = addCylinder(
0.018,
0.65,
materials.brass,
[x, 1.64, z],
scene,
10
);
rod.rotation.z = Math.cos(angle) * 0.04;
rod.rotation.x = Math.sin(angle) * 0.04;
}
const lampLight = new THREE.PointLight(0x54efff, 0, 4.5, 2);
lampLight.position.set(lampX, 1.7, 0);
scene.add(lampLight);
// -------------------------------------------------------------------------
// Electrical circuit path
// -------------------------------------------------------------------------
let signalCurve;
let signalWire = null;
let lastPathProgress = -1;
function buildSignalCurve(movingWorld) {
const points = [
fixedContactPosition.clone(),
new THREE.Vector3(-3.16, 1.52, 0.28),
fixedPostPosition.clone(),
new THREE.Vector3(-4.32, 1.04, 1.78),
new THREE.Vector3(-4.36, 1.04, -1.95),
new THREE.Vector3(4.86, 1.04, -2.13),
new THREE.Vector3(5.42, 1.31, -0.62),
new THREE.Vector3(lampX, 1.64, 0),
new THREE.Vector3(5.42, 1.31, 0.62),
new THREE.Vector3(4.32, 1.04, 2.14),
movingPostPosition.clone(),
new THREE.Vector3(1.18, 1.28, 0.48),
new THREE.Vector3(-0.25, 1.58, 0.45),
movingWorld.clone()
];
signalCurve = new THREE.CatmullRomCurve3(
points,
false,
"catmullrom",
0.28
);
const geometry = new THREE.TubeGeometry(signalCurve, 280, 0.037, 8, false);
if (!signalWire) {
signalWire = addMesh(geometry, materials.wire, [0, 0, 0]);
} else {
signalWire.geometry.dispose();
signalWire.geometry = geometry;
}
}
// Animated charge packets make the electrical signal distinct from the mechanism.
const pulses = [];
for (let i = 0; i < 9; i++) {
const pulse = addMesh(
new THREE.SphereGeometry(0.072, 14, 10),
materials.signal,
[0, 0, 0],
scene,
false
);
pulse.visible = false;
pulses.push(pulse);
}
const contactSpark = addMesh(
new THREE.SphereGeometry(0.13, 20, 14),
new THREE.MeshBasicMaterial({
color: 0xbaffff,
transparent: true,
opacity: 0.9
}),
fixedContactPosition,
scene,
false
);
contactSpark.visible = false;
// -------------------------------------------------------------------------
// Scene labels
// -------------------------------------------------------------------------
const svg = document.getElementById("leaders");
const svgNS = "http://www.w3.org/2000/svg";
function makeLabel(id, text, type, dx, dy) {
const el = document.createElement("div");
el.className = `callout ${type}`;
el.textContent = text;
document.body.appendChild(el);
const line = document.createElementNS(svgNS, "line");
line.setAttribute("class", `leader-line ${type}`);
const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute("r", "3");
circle.setAttribute("class", `leader-dot ${type}`);
svg.appendChild(line);
svg.appendChild(circle);
return { el, line, circle, dx, dy };
}
const labels = [
makeLabel("leverLabel", "Lever / press knob", "mechanical", 35, -58),
makeLabel("springLabel", "Return spring", "mechanical", 55, 10),
makeLabel("fixedLabel", "Fixed contact", "mechanical", -150, -46),
makeLabel("movingLabel", "Moving contact", "mechanical", -164, 20),
makeLabel("circuitLabel", "Electrical loop", "electrical", 32, -47)
];
function updateLabelPositions(
leverAnchor,
springAnchor,
movingAnchor,
lampAnchor
) {
const anchors = [
leverAnchor,
springAnchor,
fixedContactPosition,
movingAnchor,
lampAnchor
];
const width = window.innerWidth;
const height = window.innerHeight;
labels.forEach((label, index) => {
const projected = anchors[index].clone().project(camera);
const ax = (projected.x * 0.5 + 0.5) * width;
const ay = (-projected.y * 0.5 + 0.5) * height;
const lw = label.el.offsetWidth;
const lh = label.el.offsetHeight;
let lx = ax + label.dx;
let ly = ay + label.dy;
lx = THREE.MathUtils.clamp(lx, 8, width - lw - 8);
ly = THREE.MathUtils.clamp(ly, 8, height - lh - 8);
label.el.style.transform = `translate(${lx}px, ${ly}px)`;
const endpointX = THREE.MathUtils.clamp(
lx + (ax < lx ? 0 : lw),
lx,
lx + lw
);
const endpointY = ly + lh * 0.5;
label.line.setAttribute("x1", ax);
label.line.setAttribute("y1", ay);
label.line.setAttribute("x2", endpointX);
label.line.setAttribute("y2", endpointY);
label.circle.setAttribute("cx", ax);
label.circle.setAttribute("cy", ay);
const visible = projected.z > -1 && projected.z < 1;
label.el.style.visibility = visible ? "visible" : "hidden";
label.line.style.visibility = visible ? "visible" : "hidden";
label.circle.style.visibility = visible ? "visible" : "hidden";
});
}
// -------------------------------------------------------------------------
// Interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let spacePressed = false;
let buttonPressed = false;
let knobPressed = false;
let orbiting = false;
let previousPointerX = 0;
let previousPointerY = 0;
const pressButton = document.getElementById("pressButton");
function isPressed() {
return spacePressed || buttonPressed || knobPressed;
}
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function hitsKnob(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObject(pressTarget, false).length > 0;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (hitsKnob(event)) {
knobPressed = true;
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
return;
}
orbiting = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (knobPressed) return;
if (orbiting) {
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + dy * 0.005,
0.55,
1.3
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
updateCamera();
} else {
renderer.domElement.style.cursor = hitsKnob(event) ? "pointer" : "grab";
}
});
function releasePointer() {
knobPressed = false;
orbiting = false;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("lostpointercapture", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
10,
23
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.code === "Space" && !event.repeat) {
spacePressed = true;
event.preventDefault();
}
});
window.addEventListener("keyup", (event) => {
if (event.code === "Space") {
spacePressed = false;
event.preventDefault();
}
});
window.addEventListener("blur", () => {
spacePressed = false;
buttonPressed = false;
knobPressed = false;
});
pressButton.addEventListener("pointerdown", (event) => {
buttonPressed = true;
pressButton.setPointerCapture(event.pointerId);
event.preventDefault();
});
pressButton.addEventListener("pointerup", () => {
buttonPressed = false;
});
pressButton.addEventListener("pointercancel", () => {
buttonPressed = false;
});
document.getElementById("resetView").addEventListener("click", () => {
cameraTheta = 0.68;
cameraPhi = 0.98;
cameraRadius = 16;
updateCamera();
});
// -------------------------------------------------------------------------
// UI updates
// -------------------------------------------------------------------------
const readout = document.getElementById("readout");
const stateTitle = document.getElementById("stateTitle");
const stateSubtitle = document.getElementById("stateSubtitle");
const travelValue = document.getElementById("travelValue");
const springValue = document.getElementById("springValue");
const currentValue = document.getElementById("currentValue");
const travelFill = document.getElementById("travelFill");
const springFill = document.getElementById("springFill");
const currentFill = document.getElementById("currentFill");
function updateUI(progress, compression, closed, signalMix) {
const travel = Math.round(progress * 100);
const compressed = Math.round(compression * 100);
travelValue.textContent = `${travel}%`;
springValue.textContent = `${compressed}%`;
currentValue.textContent = closed ? "Flowing" : "Idle";
travelFill.style.width = `${travel}%`;
springFill.style.width = `${compressed}%`;
currentFill.style.width = `${Math.round(signalMix * 100)}%`;
readout.classList.toggle("closed", closed);
stateTitle.textContent = closed ? "Closed circuit" : "Open circuit";
stateSubtitle.textContent = closed
? "Contacts touching · current flowing"
: "Contacts separated · no current";
pressButton.classList.toggle("active", isPressed());
pressButton.setAttribute("aria-pressed", String(isPressed()));
}
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const worldUp = new THREE.Vector3(0, 1, 0);
const movingWorld = new THREE.Vector3();
const leverAnchor = new THREE.Vector3();
const springAnchor = new THREE.Vector3();
const springUpperWorld = new THREE.Vector3();
const springDirection = new THREE.Vector3();
const lampAnchor = new THREE.Vector3(lampX, 1.82, 0);
let leverProgress = 0;
let elapsed = 0;
let restSpringLength = 1;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
elapsed += dt;
const target = isPressed() ? 1 : 0;
const damping = 1 - Math.exp(-dt * 15);
leverProgress += (target - leverProgress) * damping;
const easedProgress =
leverProgress * leverProgress * (3 - 2 * leverProgress);
lever.rotation.z = THREE.MathUtils.lerp(
restAngle,
pressedAngle,
easedProgress
);
lever.updateMatrixWorld(true);
movingContact.getWorldPosition(movingWorld);
lever.localToWorld(leverAnchor.set(3.55, 0.48, 0));
lever.localToWorld(springUpperWorld.copy(springUpperLocal));
// Orient and compress the spring between its fixed and moving anchors.
springDirection.subVectors(springUpperWorld, springLower);
const currentSpringLength = springDirection.length();
if (restSpringLength === 1) {
restSpringLength = currentSpringLength;
}
spring.position.copy(springLower);
spring.quaternion.setFromUnitVectors(
worldUp,
springDirection.clone().normalize()
);
spring.scale.set(1, currentSpringLength, 1);
springUpperCap.position.copy(springUpperWorld);
const compression = THREE.MathUtils.clamp(
1 - currentSpringLength / restSpringLength,
0,
1
);
const contactDistance = movingWorld.distanceTo(fixedContactPosition);
const surfaceGap = Math.max(0, contactDistance - 0.32);
const closed = surfaceGap < 0.025;
const signalMix = 1 - THREE.MathUtils.smoothstep(surfaceGap, 0, 0.07);
// Rebuild only while the moving endpoint is changing.
if (
!signalCurve ||
Math.abs(leverProgress - lastPathProgress) > 0.002
) {
buildSignalCurve(movingWorld);
lastPathProgress = leverProgress;
}
materials.wire.emissiveIntensity = 0.04 + signalMix * 1.85;
materials.glass.emissiveIntensity = 0.05 + signalMix * 4.0;
bulbCore.material.opacity = 0.28 + signalMix * 0.65;
lampLight.intensity = signalMix * 10;
// Signal packets move around the external circuit only when closed.
pulses.forEach((pulse, index) => {
pulse.visible = signalMix > 0.08;
if (!pulse.visible || !signalCurve) return;
const t = (elapsed * 0.12 + index / pulses.length) % 1;
const point = signalCurve.getPointAt(t);
pulse.position.copy(point);
const pulseScale = 0.62 + signalMix * 0.65;
pulse.scale.setScalar(pulseScale);
});
// Brief contact flash.
contactSpark.visible = closed;
if (closed) {
const flicker = 0.86 + Math.sin(elapsed * 42) * 0.14;
contactSpark.position.copy(
fixedContactPosition.clone().lerp(movingWorld, 0.5)
);
contactSpark.scale.setScalar((0.45 + signalMix * 0.8) * flicker);
contactSpark.material.opacity = 0.35 + signalMix * 0.6;
}
// Label anchors.
springAnchor.copy(springLower).lerp(springUpperWorld, 0.55);
updateLabelPositions(
leverAnchor,
springAnchor,
movingWorld,
lampAnchor
);
updateUI(
easedProgress,
compression,
closed,
signalMix
);
renderer.render(scene, camera);
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
}
window.addEventListener("resize", resize);
resize();
// Establish the initial electrical path and start the render loop.
lever.updateMatrixWorld(true);
movingContact.getWorldPosition(movingWorld);
buildSignalCurve(movingWorld);
animate();
</script>
</body>
</html>
```