Prompt specification
Build or customize the Three.js 3D scene "Rib motion and diaphragm comparison" 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: Rib motion and diaphragm comparison
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rib-motion-and-diaphragm-comparison-x0970
Scene Description Prompt:
Animate cutaway thoracic insets comparing rib motion and diaphragm displacement during breathing. Create one HTML file using Three.js from cdnjs.
Working Three.js Starter (rib-motion-and-diaphragm-comparison-x0970):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thoracic Motion — Rib and Diaphragm Comparison</title>
<style>
:root {
--bg: #071117;
--panel-left: #0b1d25;
--panel-right: #17131f;
--bone: #e9d8ba;
--teal: #61e1d1;
--orange: #ff805c;
--text: #eef7f6;
--muted: #91a6aa;
--line: rgba(218, 240, 239, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 32%, rgba(1, 7, 10, 0.3) 100%),
linear-gradient(180deg, rgba(3, 8, 12, 0.38), transparent 22%, transparent 76%, rgba(3, 8, 12, 0.55));
z-index: 2;
}
.masthead {
position: fixed;
top: 24px;
left: 30px;
z-index: 5;
pointer-events: none;
}
.eyebrow {
margin-bottom: 7px;
color: var(--teal);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.masthead h1 {
margin: 0;
font-size: clamp(19px, 2vw, 28px);
font-weight: 560;
letter-spacing: -0.045em;
}
.masthead p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.06em;
}
.phase-card {
position: fixed;
top: 24px;
left: 50%;
z-index: 6;
min-width: 174px;
padding: 10px 14px;
transform: translateX(-50%);
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(8, 16, 22, 0.66);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12px);
pointer-events: none;
text-align: center;
}
.phase-row {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.phase-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 14px var(--teal);
transition: background 180ms ease, box-shadow 180ms ease;
}
.phase-card.exhale .phase-dot {
background: var(--orange);
box-shadow: 0 0 14px var(--orange);
}
.phase-track {
height: 2px;
margin-top: 8px;
overflow: hidden;
border-radius: 2px;
background: rgba(255, 255, 255, 0.1);
}
.phase-fill {
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--teal), #b5fff6);
}
.phase-card.exhale .phase-fill {
background: linear-gradient(90deg, var(--orange), #ffd1bf);
}
.panel-copy {
position: fixed;
top: 105px;
z-index: 5;
max-width: 320px;
pointer-events: none;
}
.panel-left {
left: 30px;
}
.panel-right {
left: calc(50% + 30px);
}
.panel-number {
display: flex;
align-items: center;
gap: 10px;
color: var(--muted);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
.panel-number::after {
width: 54px;
height: 1px;
content: "";
background: var(--line);
}
.panel-copy h2 {
margin: 13px 0 7px;
font-size: clamp(22px, 2.4vw, 34px);
font-weight: 520;
letter-spacing: -0.045em;
}
.panel-copy p {
margin: 0;
max-width: 290px;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.motion-key {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 14px;
}
.motion-key span {
padding: 6px 9px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(6, 15, 20, 0.28);
color: #b9cacc;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.readouts {
position: fixed;
bottom: 112px;
z-index: 5;
display: flex;
gap: 8px;
pointer-events: none;
}
.readouts.left {
left: 30px;
}
.readouts.right {
left: calc(50% + 30px);
}
.readout {
min-width: 112px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(5, 12, 17, 0.48);
backdrop-filter: blur(8px);
}
.readout-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.readout-value {
color: var(--text);
font: 600 17px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.readout-value.teal {
color: var(--teal);
}
.readout-value.orange {
color: var(--orange);
}
.divider {
position: fixed;
top: 0;
bottom: 0;
left: 50%;
z-index: 3;
width: 1px;
pointer-events: none;
background: linear-gradient(
180deg,
transparent,
rgba(200, 235, 234, 0.13) 18%,
rgba(200, 235, 234, 0.13) 82%,
transparent
);
}
.divider::after {
position: absolute;
top: 50%;
left: 50%;
width: 5px;
height: 42px;
transform: translate(-50%, -50%);
border: 1px solid rgba(220, 240, 240, 0.18);
border-radius: 999px;
content: "";
background: rgba(5, 12, 17, 0.45);
}
.controls {
position: fixed;
bottom: 22px;
left: 50%;
z-index: 10;
display: grid;
grid-template-columns: auto auto minmax(220px, 1fr);
align-items: center;
gap: 15px;
width: min(760px, calc(100% - 36px));
padding: 12px 15px;
transform: translateX(-50%);
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(7, 15, 20, 0.78);
box-shadow: 0 18px 70px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(18px);
}
.transport {
display: flex;
gap: 7px;
}
.control-button {
display: grid;
width: 38px;
height: 38px;
padding: 0;
place-items: center;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.05);
color: var(--text);
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease, transform 150ms ease;
}
.control-button:hover {
border-color: rgba(97, 225, 209, 0.5);
background: rgba(97, 225, 209, 0.1);
transform: translateY(-1px);
}
.control-button:active {
transform: translateY(0);
}
.control-button svg {
width: 17px;
height: 17px;
fill: currentColor;
}
.speed-control {
width: 100px;
}
.control-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.control-label output {
color: var(--teal);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
height: 3px;
margin: 0;
appearance: none;
border-radius: 3px;
outline: none;
background: rgba(255, 255, 255, 0.15);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 12px;
height: 12px;
appearance: none;
border: 2px solid #092028;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 1px rgba(97, 225, 209, 0.35);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 2px solid #092028;
border-radius: 50%;
background: var(--teal);
}
.timeline {
min-width: 0;
}
.timeline input {
background: linear-gradient(
90deg,
rgba(97, 225, 209, 0.55) 0%,
rgba(97, 225, 209, 0.55) 50%,
rgba(255, 128, 92, 0.45) 50%,
rgba(255, 128, 92, 0.45) 100%
);
}
.timeline input::-webkit-slider-thumb {
background: #f5fffd;
}
.timeline input::-moz-range-thumb {
background: #f5fffd;
}
.timeline-labels {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.timeline-labels span:first-child {
color: var(--teal);
}
.timeline-labels span:last-child {
color: var(--orange);
}
.help {
position: fixed;
right: 28px;
bottom: 28px;
z-index: 4;
color: rgba(211, 229, 230, 0.48);
font-size: 9px;
letter-spacing: 0.08em;
pointer-events: none;
}
@media (max-width: 900px) {
.readouts.right {
left: calc(50% + 20px);
}
.readouts.left {
left: 20px;
}
.readout {
min-width: 102px;
}
.help {
display: none;
}
}
@media (max-width: 760px) {
.masthead {
top: 13px;
left: 16px;
}
.masthead h1 {
font-size: 19px;
}
.masthead p {
display: none;
}
.phase-card {
top: 62px;
right: 14px;
left: auto;
min-width: 142px;
transform: none;
}
.panel-copy {
top: 112px;
left: 16px !important;
max-width: 270px;
}
.panel-right {
top: calc(52% + 12px) !important;
}
.panel-copy h2 {
margin-top: 9px;
font-size: 23px;
}
.panel-copy p {
display: none;
}
.motion-key {
display: none;
}
.readouts {
top: auto;
bottom: 98px;
}
.readouts.left {
left: 16px;
}
.readouts.right {
left: 16px;
}
.readout {
min-width: 96px;
padding: 8px 9px;
}
.readout-value {
font-size: 14px;
}
.divider {
top: 52%;
right: 0;
bottom: auto;
left: 0;
width: auto;
height: 1px;
background: linear-gradient(
90deg,
transparent,
rgba(200, 235, 234, 0.14),
transparent
);
}
.divider::after {
width: 42px;
height: 5px;
}
.controls {
bottom: 10px;
grid-template-columns: auto 1fr;
gap: 10px;
width: calc(100% - 20px);
padding: 9px;
}
.speed-control {
display: none;
}
.timeline {
grid-column: 1 / -1;
grid-row: 2;
}
.transport {
grid-column: 1 / -1;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="vignette"></div>
<header class="masthead">
<div class="eyebrow">Respiratory mechanics / synchronized study</div>
<h1>Thoracic Motion Atlas</h1>
<p>Cutaway comparison of rib deformation and diaphragmatic excursion</p>
</header>
<div id="phaseCard" class="phase-card">
<div class="phase-row">
<span class="phase-dot"></span>
<span id="phaseLabel">Inspiration</span>
</div>
<div class="phase-track"><div id="phaseFill" class="phase-fill"></div></div>
</div>
<section class="panel-copy panel-left">
<div class="panel-number">01 / Skeletal mechanism</div>
<h2>Rib motion</h2>
<p>
Upper ribs rotate in the pump-handle pattern while lower ribs swing
laterally in the bucket-handle pattern.
</p>
<div class="motion-key">
<span>Pump handle</span>
<span>Bucket handle</span>
</div>
</section>
<section class="panel-copy panel-right">
<div class="panel-number">02 / Muscular mechanism</div>
<h2>Diaphragm displacement</h2>
<p>
The contracting dome descends and flattens, increasing thoracic volume
along the vertical axis.
</p>
<div class="motion-key">
<span>Dome descent</span>
<span>Vertical excursion</span>
</div>
</section>
<div class="readouts left">
<div class="readout">
<span class="readout-label">Lateral excursion</span>
<span id="lateralValue" class="readout-value teal">0.0 cm</span>
</div>
<div class="readout">
<span class="readout-label">Pump-handle lift</span>
<span id="liftValue" class="readout-value teal">0.0 cm</span>
</div>
</div>
<div class="readouts right">
<div class="readout">
<span class="readout-label">Dome descent</span>
<span id="diaphragmValue" class="readout-value orange">0.0 cm</span>
</div>
<div class="readout">
<span class="readout-label">Vertical excursion</span>
<span id="volumeValue" class="readout-value orange">0.0 cm</span>
</div>
</div>
<div class="divider"></div>
<div class="controls">
<div class="transport">
<button id="playButton" class="control-button" aria-label="Pause animation">
<svg id="pauseIcon" viewBox="0 0 24 24" aria-hidden="true">
<path d="M6 5h4v14H6zm8 0h4v14h-4z"></path>
</svg>
<svg id="playIcon" viewBox="0 0 24 24" aria-hidden="true" style="display:none">
<path d="M8 5v14l11-7z"></path>
</svg>
</button>
<button id="resetButton" class="control-button" aria-label="Reset camera views">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 4a8 8 0 1 1-7.45 5.09l1.86.73A6 6 0 1 0 8 7.35V11H4V4h2.7v2.7A7.96 7.96 0 0 1 12 4z"></path>
</svg>
</button>
</div>
<label class="speed-control">
<span class="control-label">
Rate <output id="speedValue">1.0×</output>
</span>
<input id="speedInput" type="range" min="0.35" max="1.6" step="0.05" value="1">
</label>
<div class="timeline">
<input id="scrubInput" type="range" min="0" max="1000" step="1" value="0"
aria-label="Breathing cycle position">
<div class="timeline-labels">
<span>Inspiration</span>
<span>Expiration</span>
</div>
</div>
</div>
<div class="help">Drag to orbit · scroll to zoom · double-click to reset</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.querySelector("#stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.13;
renderer.autoClear = false;
stage.appendChild(renderer.domElement);
const Y_AXIS = new THREE.Vector3(0, 1, 0);
const X_AXIS = new THREE.Vector3(1, 0, 0);
const TEAL = new THREE.Color(0x61e1d1);
const ORANGE = new THREE.Color(0xff805c);
const clamp = THREE.MathUtils.clamp;
const smooth = (t) => {
t = clamp(t, 0, 1);
return t * t * (3 - 2 * t);
};
const smoother = (t) => {
t = clamp(t, 0, 1);
return t * t * t * (t * (t * 6 - 15) + 10);
};
function breathAt(p) {
p = ((p % 1) + 1) % 1;
if (p < 0.5) return smoother(p / 0.5);
return 1 - smoother((p - 0.5) / 0.5);
}
function addLights(scene, intensity = 1) {
scene.add(new THREE.HemisphereLight(0xc8f5ff, 0x172029, 2.1 * intensity));
const key = new THREE.DirectionalLight(0xfff0d6, 3.2 * intensity);
key.position.set(3.5, 5, 5);
scene.add(key);
const rim = new THREE.DirectionalLight(0x51d9dc, 2.4 * intensity);
rim.position.set(-4, 1.5, -3);
scene.add(rim);
const warm = new THREE.PointLight(0xff8e68, 1.1 * intensity, 7);
warm.position.set(3, -1, 2);
scene.add(warm);
}
function makeMaterial(options) {
return new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.55,
metalness: 0.04,
...options
});
}
const boneMaterial = makeMaterial({
color: 0xe9d8ba,
roughness: 0.52,
emissive: 0x2b2117,
emissiveIntensity: 0.12
});
const cartilageMaterial = makeMaterial({
color: 0xf2e7d2,
roughness: 0.65
});
const lungMaterial = new THREE.MeshPhysicalMaterial({
color: 0x56d8cc,
roughness: 0.28,
metalness: 0,
transmission: 0.05,
transparent: true,
opacity: 0.16,
side: THREE.DoubleSide,
depthWrite: false
});
const skinMaterial = new THREE.MeshBasicMaterial({
color: 0x83d8dc,
transparent: true,
opacity: 0.045,
side: THREE.DoubleSide,
depthWrite: false
});
const cutMaterial = new THREE.LineBasicMaterial({
color: 0x8ee6df,
transparent: true,
opacity: 0.25
});
const orangeMaterial = new THREE.MeshPhysicalMaterial({
color: 0xff714d,
emissive: 0x4b160d,
emissiveIntensity: 0.18,
roughness: 0.36,
transparent: true,
opacity: 0.77,
side: THREE.DoubleSide,
depthWrite: false
});
/*
* Dynamic tubular geometry.
* The centerline can be animated without recreating TubeGeometry.
*/
function createDynamicTube(path, material, {
segments = 24,
radialSegments = 6,
radius = 0.04
} = {}) {
const vertexCount = (segments + 1) * (radialSegments + 1);
const positions = new Float32Array(vertexCount * 3);
const normals = new Float32Array(vertexCount * 3);
const uvs = new Float32Array(vertexCount * 2);
const indices = [];
for (let i = 0; i <= segments; i++) {
for (let j = 0; j <= radialSegments; j++) {
const k = i * (radialSegments + 1) + j;
uvs[k * 2] = i / segments;
uvs[k * 2 + 1] = j / radialSegments;
}
}
for (let i = 0; i < segments; i++) {
for (let j = 0; j < radialSegments; j++) {
const a = i * (radialSegments + 1) + j;
const b = (i + 1) * (radialSegments + 1) + j;
const c = b + 1;
const d = a + 1;
indices.push(a, b, d, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setIndex(indices);
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage)
);
geometry.setAttribute(
"normal",
new THREE.BufferAttribute(normals, 3).setUsage(THREE.DynamicDrawUsage)
);
geometry.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));
const mesh = new THREE.Mesh(geometry, material);
mesh.frustumCulled = false;
mesh.userData.dynamicTube = { path, segments, radialSegments, radius };
updateDynamicTube(mesh);
return mesh;
}
function updateDynamicTube(mesh) {
const { path, segments, radialSegments, radius } = mesh.userData.dynamicTube;
const position = mesh.geometry.attributes.position;
const normal = mesh.geometry.attributes.normal;
const before = new THREE.Vector3();
const after = new THREE.Vector3();
const tangent = new THREE.Vector3();
const ringNormal = new THREE.Vector3();
const binormal = new THREE.Vector3();
const point = new THREE.Vector3();
for (let i = 0; i <= segments; i++) {
const t = i / segments;
path(clamp(t - 0.002, 0, 1), before);
path(clamp(t + 0.002, 0, 1), after);
path(t, point);
tangent.subVectors(after, before).normalize();
const reference = Math.abs(tangent.dot(Y_AXIS)) < 0.92 ? Y_AXIS : X_AXIS;
ringNormal.copy(reference)
.addScaledVector(tangent, -reference.dot(tangent))
.normalize();
binormal.crossVectors(tangent, ringNormal).normalize();
for (let j = 0; j <= radialSegments; j++) {
const angle = (j / radialSegments) * Math.PI * 2;
const c = Math.cos(angle);
const s = Math.sin(angle);
const nx = ringNormal.x * c + binormal.x * s;
const ny = ringNormal.y * c + binormal.y * s;
const nz = ringNormal.z * c + binormal.z * s;
const index = i * (radialSegments + 1) + j;
position.setXYZ(
index,
point.x + nx * radius,
point.y + ny * radius,
point.z + nz * radius
);
normal.setXYZ(index, nx, ny, nz);
}
}
position.needsUpdate = true;
normal.needsUpdate = true;
}
function makeCylinder(radius, height, material, radialSegments = 12) {
return new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, height, radialSegments),
material
);
}
function makeLine(points, material) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
return new THREE.Line(geometry, material);
}
function makeArrow(color) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.75,
depthWrite: false
});
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.022, 0.022, 1, 10),
material
);
const cone = new THREE.Mesh(
new THREE.ConeGeometry(0.075, 0.11, 12),
material
);
group.add(shaft, cone);
group.userData = { shaft, cone, material };
group.renderOrder = 8;
return group;
}
function updateArrow(arrow, start, vector, opacity = 0.75) {
const length = vector.length();
if (length < 0.018) {
arrow.visible = false;
return;
}
arrow.visible = true;
const direction = vector.clone().normalize();
const shaftLength = Math.max(0.01, length - 0.11);
const { shaft, cone, material } = arrow.userData;
shaft.position.copy(start).addScaledVector(direction, shaftLength * 0.5);
shaft.quaternion.setFromUnitVectors(Y_AXIS, direction);
shaft.scale.set(1, shaftLength, 1);
cone.position.copy(start).addScaledVector(direction, shaftLength + 0.055);
cone.quaternion.setFromUnitVectors(Y_AXIS, direction);
material.opacity = opacity;
}
function addGrid(scene, color) {
const grid = new THREE.GridHelper(9, 28, color, color);
grid.position.y = -1.48;
grid.material.transparent = true;
grid.material.opacity = 0.08;
grid.material.depthWrite = false;
scene.add(grid);
}
/* ---------------------------------------------------------
LEFT VIEW: frontal / oblique rib-cage cutaway
--------------------------------------------------------- */
const leftScene = new THREE.Scene();
leftScene.background = new THREE.Color(0x081820);
leftScene.fog = new THREE.Fog(0x081820, 6, 11);
addLights(leftScene);
addGrid(leftScene, 0x78c8c7);
const leftCamera = new THREE.PerspectiveCamera(38, 1, 0.1, 40);
const leftOrbit = {
target: new THREE.Vector3(0, 0.18, 0),
theta: 0.42,
phi: 1.27,
radius: 5.15,
desiredTheta: 0.42,
desiredPhi: 1.27,
desiredRadius: 5.15
};
const leftRoot = new THREE.Group();
leftScene.add(leftRoot);
// Open-front ghost torso shell.
const torsoProfile = [
new THREE.Vector2(0.72, -1.42),
new THREE.Vector2(0.94, -1.12),
new THREE.Vector2(1.08, -0.45),
new THREE.Vector2(1.13, 0.35),
new THREE.Vector2(1.04, 1.05),
new THREE.Vector2(0.82, 1.55),
new THREE.Vector2(0.46, 1.82)
];
const torsoShell = new THREE.Mesh(
new THREE.LatheGeometry(torsoProfile, 72, 0.48, Math.PI * 2 - 0.96),
skinMaterial
);
torsoShell.renderOrder = 0;
leftRoot.add(torsoShell);
function torsoRadiusAt(y) {
for (let i = 0; i < torsoProfile.length - 1; i++) {
const a = torsoProfile[i];
const b = torsoProfile[i + 1];
if (y >= a.y && y <= b.y) {
const t = (y - a.y) / (b.y - a.y);
return THREE.MathUtils.lerp(a.x, b.x, t);
}
}
return y < torsoProfile[0].y ? torsoProfile[0].x : torsoProfile.at(-1).x;
}
[0.48, Math.PI * 2 - 0.48].forEach((phi) => {
const edge = createDynamicTube(
(t, out) => {
const y = THREE.MathUtils.lerp(-1.4, 1.8, t);
const radius = torsoRadiusAt(y);
out.set(
Math.sin(phi) * radius,
y,
Math.cos(phi) * radius
);
},
new THREE.MeshBasicMaterial({
color: 0x89e5df,
transparent: true,
opacity: 0.22
}),
{ segments: 36, radialSegments: 5, radius: 0.012 }
);
leftRoot.add(edge);
});
// Lungs, trachea, and bronchial tree.
const leftLungs = [];
[-1, 1].forEach((side) => {
const lung = new THREE.Mesh(
new THREE.SphereGeometry(1, 32, 24),
lungMaterial
);
lung.position.set(side * 0.43, 0.12, 0.03);
lung.scale.set(0.5, 0.97, 0.75);
lung.userData.basePosition = lung.position.clone();
lung.userData.baseScale = lung.scale.clone();
lung.renderOrder = 1;
leftRoot.add(lung);
leftLungs.push(lung);
});
const trachea = createDynamicTube(
(t, out) => out.set(0, 1.82 - t * 0.58, 0.06),
new THREE.MeshPhysicalMaterial({
color: 0x91eee1,
transparent: true,
opacity: 0.24,
roughness: 0.25,
depthWrite: false
}),
{ segments: 12, radialSegments: 8, radius: 0.085 }
);
leftRoot.add(trachea);
[-1, 1].forEach((side) => {
const bronchus = createDynamicTube(
(t, out) => {
out.set(
side * 0.42 * smooth(t),
1.25 - 0.18 * Math.sin(t * Math.PI),
0.05
);
},
new THREE.MeshPhysicalMaterial({
color: 0x91eee1,
transparent: true,
opacity: 0.22,
depthWrite: false
}),
{ segments: 14, radialSegments: 6, radius: 0.055 }
);
leftRoot.add(bronchus);
});
const airParticles = [];
const airMaterial = new THREE.MeshBasicMaterial({
color: 0xc7fff8,
transparent: true,
opacity: 0.7
});
for (let i = 0; i < 13; i++) {
const particle = new THREE.Mesh(
new THREE.SphereGeometry(0.025, 8, 8),
airMaterial
);
particle.userData.offset = i / 13;
leftRoot.add(particle);
airParticles.push(particle);
}
// Vertebral column.
const spine = makeCylinder(0.095, 3.05, boneMaterial, 14);
spine.position.set(0, 0.22, -0.91);
leftRoot.add(spine);
for (let i = 0; i < 11; i++) {
const vertebra = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.105, 0.16),
boneMaterial
);
vertebra.position.set(0, 1.48 - i * 0.255, -0.91);
leftRoot.add(vertebra);
}
// Sternum.
const sternum = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 1.43, 0.12, 4, 8, 2),
boneMaterial
);
sternum.position.set(0, 0.31, 1.035);
sternum.rotation.x = -0.025;
leftRoot.add(sternum);
// Clavicles.
[-1, 1].forEach((side) => {
const clavicle = createDynamicTube(
(t, out) => {
const x = side * (0.08 + 0.92 * t);
out.set(
x,
1.66 + 0.09 * Math.sin(t * Math.PI) - 0.06 * t,
0.31 - 0.34 * Math.sin(t * Math.PI)
);
},
boneMaterial,
{ segments: 22, radialSegments: 7, radius: 0.06 }
);
leftRoot.add(clavicle);
});
let breath = 0;
// Dynamic ribs and costal cartilage.
const leftRibTubes = [];
const cartilageTubes = [];
const ribCount = 10;
for (let sideIndex = 0; sideIndex < 2; sideIndex++) {
const side = sideIndex === 0 ? -1 : 1;
for (let i = 0; i < ribCount; i++) {
const n = i / (ribCount - 1);
const baseY = 1.36 - i * 0.255;
const width = 0.72 + 0.31 * Math.sin(n * Math.PI * 0.8);
const upperInfluence = Math.max(0, 1 - n * 2.65);
const lowerInfluence = Math.max(0, (n - 0.32) / 0.68);
const ribPath = (t, out) => {
const theta = t * Math.PI;
const lateralExpansion = 1 + 0.16 * lowerInfluence * breath;
const x = side * (
0.105 + width * Math.sin(theta) * lateralExpansion
);
const z = -0.85 + 1.81 * (1 - Math.cos(theta)) * 0.5;
const frontWeight = smooth((t - 0.45) / 0.55);
const lift =
0.29 * upperInfluence * breath * Math.pow(t, 1.85) +
0.045 * lowerInfluence * breath * Math.pow(t, 2);
return out.set(x, baseY + lift, z);
};
const rib = createDynamicTube(ribPath, boneMaterial, {
segments: 24,
radialSegments: 6,
radius: 0.048 - n * 0.006
});
leftRoot.add(rib);
leftRibTubes.push(rib);
const cartilagePath = (t, out) => {
const end = ribPath(1, new THREE.Vector3());
const start = end.clone();
const target = new THREE.Vector3(
0,
end.y - 0.02,
1.045
);
const control = new THREE.Vector3(
side * 0.08,
end.y + 0.015,
1.085
);
const q = 1 - t;
out.set(
q * q * start.x + 2 * q * t * control.x + t * t * target.x,
q * q * start.y + 2 * q * t * control.y + t * t * target.y,
q * q * start.z + 2 * q * t * control.z + t * t * target.z
);
};
const cartilage = createDynamicTube(cartilagePath, cartilageMaterial, {
segments: 6,
radialSegments: 6,
radius: 0.052
});
leftRoot.add(cartilage);
cartilageTubes.push(cartilage);
}
}
const upperArrow = makeArrow(TEAL);
const lowerArrowRight = makeArrow(TEAL);
const lowerArrowLeft = makeArrow(TEAL);
leftRoot.add(upperArrow, lowerArrowRight, lowerArrowLeft);
function updateLeftView(breath, derivative) {
leftRibTubes.forEach((mesh) => updateDynamicTube(mesh));
cartilageTubes.forEach((mesh) => updateDynamicTube(mesh));
leftLungs.forEach((lung) => {
const { basePosition, baseScale } = lung.userData;
lung.position.copy(basePosition);
lung.position.y -= 0.035 * breath;
lung.scale.copy(baseScale);
lung.scale.x *= 1 + 0.035 * breath;
lung.scale.y *= 1 + 0.055 * breath;
lung.scale.z *= 1 + 0.04 * breath;
});
const direction = Math.sign(derivative) || 1;
const moving = Math.min(1, Math.abs(derivative) * 40);
const opacity = 0.2 + 0.62 * moving;
updateArrow(
upperArrow,
new THREE.Vector3(-1.23, 0.48, 0.35),
new THREE.Vector3(0, direction * 0.34, 0),
opacity
);
updateArrow(
lowerArrowRight,
new THREE.Vector3(1.04, -0.46, 0.24),
new THREE.Vector3(direction * 0.35, 0, 0),
opacity
);
updateArrow(
lowerArrowLeft,
new THREE.Vector3(-1.04, -0.46, 0.24),
new THREE.Vector3(-direction * 0.35, 0, 0),
opacity
);
const particleTravel = phase < 0.5 ? phase : 1 - phase;
airParticles.forEach((particle) => {
const t = (particleTravel + particle.userData.offset) % 1;
particle.position.set(
Math.sin(particle.userData.offset * 13) * 0.025,
1.74 - t * 0.55,
0.06
);
});
}
/* ---------------------------------------------------------
RIGHT VIEW: sagittal diaphragm cutaway
--------------------------------------------------------- */
const rightScene = new THREE.Scene();
rightScene.background = new THREE.Color(0x17131e);
rightScene.fog = new THREE.Fog(0x17131e, 6, 11);
addLights(rightScene, 0.92);
addGrid(rightScene, 0xb895a4);
const rightCamera = new THREE.PerspectiveCamera(37, 1, 0.1, 40);
const rightOrbit = {
target: new THREE.Vector3(0, 0.03, 0),
theta: 0.13,
phi: 1.43,
radius: 4.75,
desiredTheta: 0.13,
desiredPhi: 1.43,
desiredRadius: 4.75
};
const rightRoot = new THREE.Group();
rightScene.add(rightRoot);
// Sagittal body outline.
const torsoShape = new THREE.Shape();
torsoShape.moveTo(-0.48, 1.78);
torsoShape.lineTo(-0.94, 1.53);
torsoShape.bezierCurveTo(-1.19, 1.14, -1.27, 0.52, -1.20, -0.36);
torsoShape.bezierCurveTo(-1.15, -0.9, -0.91, -1.34, -0.58, -1.43);
torsoShape.lineTo(0.69, -1.43);
torsoShape.bezierCurveTo(1.03, -1.14, 1.10, -0.52, 1.06, 0.29);
torsoShape.bezierCurveTo(1.03, 0.92, 0.84, 1.45, 0.48, 1.78);
torsoShape.closePath();
const torsoFill = new THREE.Mesh(
new THREE.ShapeGeometry(torsoShape),
new THREE.MeshBasicMaterial({
color: 0x88d9d5,
transparent: true,
opacity: 0.035,
side: THREE.DoubleSide,
depthWrite: false
})
);
torsoFill.position.z = -0.12;
rightRoot.add(torsoFill);
const torsoOutline = makeLine(
torsoShape.getPoints(100),
new THREE.LineBasicMaterial({
color: 0xa7e8e2,
transparent: true,
opacity: 0.28
})
);
torsoOutline.position.z = -0.1;
rightRoot.add(torsoOutline);
// Sagittal lung profile.
const lungShape = new THREE.Shape();
lungShape.moveTo(-0.77, 1.25);
lungShape.bezierCurveTo(-0.92, 0.79, -0.83, 0.13, -0.55, -0.23);
lungShape.bezierCurveTo(-0.16, -0.52, 0.43, -0.39, 0.78, -0.02);
lungShape.bezierCurveTo(0.75, 0.60, 0.57, 1.13, 0.06, 1.28);
lungShape.bezierCurveTo(-0.28, 1.37, -0.59, 1.35, -0.77, 1.25);
const rightLung = new THREE.Mesh(
new THREE.ShapeGeometry(lungShape, 36),
new THREE.MeshPhysicalMaterial({
color: 0x56d8cc,
roughness: 0.3,
transparent: true,
opacity: 0.18,
side: THREE.DoubleSide,
depthWrite: false
})
);
rightLung.position.z = -0.045;
rightLung.userData.basePosition = rightLung.position.clone();
rightRoot.add(rightLung);
// Spine and sternum.
const sagittalSpine = makeCylinder(0.08, 2.92, boneMaterial, 14);
sagittalSpine.position.set(-1.08, 0.12, -0.03);
rightRoot.add(sagittalSpine);
const sagittalSternum = new THREE.Mesh(
new THREE.BoxGeometry(0.11, 1.42, 0.12),
boneMaterial
);
sagittalSternum.position.set(0.96, 0.38, 0.02);
sagittalSternum.rotation.z = -0.12;
rightRoot.add(sagittalSternum);
// Static rib arcs in profile.
for (let i = 0; i < 9; i++) {
const y = 1.36 - i * 0.255;
const rib = createDynamicTube(
(t, out) => {
const x = THREE.MathUtils.lerp(-1.05, 0.91, t);
out.set(
x,
y - 0.09 * Math.sin(t * Math.PI) + 0.16 * Math.pow(t, 3),
0.05 + 0.035 * Math.sin(t * Math.PI)
);
},
boneMaterial,
{ segments: 24, radialSegments: 6, radius: 0.046 }
);
rightRoot.add(rib);
}
// Dynamic diaphragm surface.
const diaphragmGeometry = new THREE.BufferGeometry();
const diaphragmNX = 32;
const diaphragmNZ = 18;
const diaphragmPositions = new Float32Array(
(diaphragmNX + 1) * (diaphragmNZ + 1) * 3
);
const diaphragmUVs = new Float32Array(
(diaphragmNX + 1) * (diaphragmNZ + 1) * 2
);
const diaphragmIndices = [];
for (let j = 0; j <= diaphragmNZ; j++) {
for (let i = 0; i <= diaphragmNX; i++) {
const index = j * (diaphragmNX + 1) + i;
diaphragmUVs[index * 2] = i / diaphragmNX;
diaphragmUVs[index * 2 + 1] = j / diaphragmNZ;
if (i < diaphragmNX && j < diaphragmNZ) {
const a = index;
const b = index + 1;
const c = index + diaphragmNX + 1;
const d = c + 1;
diaphragmIndices.push(a, c, b, b, c, d);
}
}
}
diaphragmGeometry.setIndex(diaphragmIndices);
diaphragmGeometry.setAttribute(
"position",
new THREE.BufferAttribute(diaphragmPositions, 3)
.setUsage(THREE.DynamicDrawUsage)
);
diaphragmGeometry.setAttribute("uv", new THREE.BufferAttribute(diaphragmUVs, 2));
const diaphragm = new THREE.Mesh(diaphragmGeometry, orangeMaterial);
diaphragm.frustumCulled = false;
diaphragm.renderOrder = 3;
rightRoot.add(diaphragm);
function diaphragmY(x, z, b) {
const nx = x / 1.08;
const nz = z / 0.62;
const xShape = Math.pow(Math.max(0, 1 - nx * nx), 0.65);
const zShape = Math.pow(Math.max(0, 1 - nz * nz), 0.55);
const shape = xShape * zShape;
const amplitude = 0.70 * (1 - 0.36 * b);
return -0.93 + amplitude * shape - 0.27 * b * shape;
}
function updateDiaphragmSurface(b) {
const position = diaphragmGeometry.attributes.position;
let index = 0;
for (let j = 0; j <= diaphragmNZ; j++) {
const z = THREE.MathUtils.lerp(-0.62, 0.62, j / diaphragmNZ);
for (let i = 0; i <= diaphragmNX; i++) {
const x = THREE.MathUtils.lerp(-1.08, 1.08, i / diaphragmNX);
position.setXYZ(index++, x, diaphragmY(x, z, b), z);
}
}
position.needsUpdate = true;
diaphragmGeometry.computeVertexNormals();
}
const diaphragmOutline = createDynamicTube(
(t, out) => {
const x = THREE.MathUtils.lerp(-1.08, 1.08, t);
out.set(x, diaphragmY(x, 0.62, breath), 0.62);
},
new THREE.MeshBasicMaterial({
color: 0xffa07f,
transparent: true,
opacity: 0.95,
depthWrite: false
}),
{ segments: 36, radialSegments: 6, radius: 0.046 }
);
rightRoot.add(diaphragmOutline);
const diaphragmCrest = createDynamicTube(
(t, out) => {
const z = THREE.MathUtils.lerp(-0.62, 0.62, t);
out.set(0, diaphragmY(0, z, breath), z);
},
new THREE.MeshBasicMaterial({
color: 0xffb096,
transparent: true,
opacity: 0.52,
depthWrite: false
}),
{ segments: 28, radialSegments: 5, radius: 0.022 }
);
rightRoot.add(diaphragmCrest);
// End-expiratory reference line.
const restReference = makeLine(
[
new THREE.Vector3(-0.45, diaphragmY(0, 0.62, 0), 0.66),
new THREE.Vector3(0.45, diaphragmY(0, 0.62, 0), 0.66)
],
new THREE.LineDashedMaterial({
color: 0xffb096,
transparent: true,
opacity: 0.45,
dashSize: 0.06,
gapSize: 0.05
})
);
restReference.computeLineDistances();
rightRoot.add(restReference);
const diaphragmArrow = makeArrow(ORANGE);
rightRoot.add(diaphragmArrow);
function updateRightView(breath, derivative) {
updateDiaphragmSurface(breath);
updateDynamicTube(diaphragmOutline);
updateDynamicTube(diaphragmCrest);
rightLung.scale.set(
1 + 0.045 * breath,
1 + 0.055 * breath,
1
);
rightLung.position.y = rightLung.userData.basePosition.y - 0.035 * breath;
const restY = diaphragmY(0, 0, 0);
const currentY = diaphragmY(0, 0, breath);
const moving = Math.min(1, Math.abs(derivative) * 40);
const opacity = 0.18 + 0.68 * moving;
if (derivative >= 0) {
updateArrow(
diaphragmArrow,
new THREE.Vector3(0.2, restY, 0.84),
new THREE.Vector3(0, currentY - restY, 0),
opacity
);
} else {
updateArrow(
diaphragmArrow,
new THREE.Vector3(0.2, currentY, 0.84),
new THREE.Vector3(0, restY - currentY, 0),
opacity
);
}
}
/* ---------------------------------------------------------
Camera controls — implemented directly, without addons
--------------------------------------------------------- */
const views = [
{ scene: leftScene, camera: leftCamera, orbit: leftOrbit },
{ scene: rightScene, camera: rightCamera, orbit: rightOrbit }
];
let viewportRects = [];
function computeRects() {
const width = window.innerWidth;
const height = window.innerHeight;
if (width <= 760) {
const topHeight = height * 0.52;
return [
{ x: 0, y: 0, width, height: topHeight },
{ x: 0, y: topHeight, width, height: height - topHeight }
];
}
return [
{ x: 0, y: 0, width: width / 2, height },
{ x: width / 2, y: 0, width: width / 2, height }
];
}
function updateCamera(view) {
const { camera, orbit } = view;
orbit.theta += (orbit.desiredTheta - orbit.theta) * 0.12;
orbit.phi += (orbit.desiredPhi - orbit.phi) * 0.12;
orbit.radius += (orbit.desiredRadius - orbit.radius) * 0.12;
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function viewAt(clientX, clientY) {
for (let i = 0; i < viewportRects.length; i++) {
const rect = viewportRects[i];
if (
clientX >= rect.x &&
clientX <= rect.x + rect.width &&
clientY >= rect.y &&
clientY <= rect.y + rect.height
) {
return i;
}
}
return 0;
}
function resetView(index) {
const orbit = views[index].orbit;
orbit.desiredTheta = index === 0 ? 0.42 : 0.13;
orbit.desiredPhi = index === 0 ? 1.27 : 1.43;
orbit.desiredRadius = index === 0 ? 5.15 : 4.75;
}
let drag = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
const index = viewAt(event.clientX, event.clientY);
drag = {
index,
lastX: event.clientX,
lastY: event.clientY,
pointerId: event.pointerId
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!drag || event.pointerId !== drag.pointerId) return;
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
const orbit = views[drag.index].orbit;
orbit.desiredTheta -= dx * 0.006;
orbit.desiredPhi = clamp(orbit.desiredPhi - dy * 0.006, 0.52, 2.28);
drag.lastX = event.clientX;
drag.lastY = event.clientY;
});
function endDrag(event) {
if (drag && event.pointerId === drag.pointerId) drag = null;
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
const index = viewAt(event.clientX, event.clientY);
const orbit = views[index].orbit;
orbit.desiredRadius = clamp(
orbit.desiredRadius * Math.exp(event.deltaY * 0.001),
3.1,
8.2
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", (event) => {
resetView(viewAt(event.clientX, event.clientY));
});
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
viewportRects = computeRects();
views.forEach((view, index) => {
const rect = viewportRects[index];
view.camera.aspect = rect.width / rect.height;
view.camera.updateProjectionMatrix();
});
}
window.addEventListener("resize", resize);
resize();
/* ---------------------------------------------------------
Timeline and interface
--------------------------------------------------------- */
const phaseCard = document.querySelector("#phaseCard");
const phaseLabel = document.querySelector("#phaseLabel");
const phaseFill = document.querySelector("#phaseFill");
const playButton = document.querySelector("#playButton");
const pauseIcon = document.querySelector("#pauseIcon");
const playIcon = document.querySelector("#playIcon");
const resetButton = document.querySelector("#resetButton");
const speedInput = document.querySelector("#speedInput");
const speedValue = document.querySelector("#speedValue");
const scrubInput = document.querySelector("#scrubInput");
const lateralValue = document.querySelector("#lateralValue");
const liftValue = document.querySelector("#liftValue");
const diaphragmValue = document.querySelector("#diaphragmValue");
const volumeValue = document.querySelector("#volumeValue");
let phase = 0;
let speed = 1;
let paused = false;
let scrubbing = false;
function setPlaying(playing) {
paused = !playing;
pauseIcon.style.display = paused ? "none" : "block";
playIcon.style.display = paused ? "block" : "none";
playButton.setAttribute(
"aria-label",
paused ? "Play animation" : "Pause animation"
);
}
playButton.addEventListener("click", () => setPlaying(paused));
resetButton.addEventListener("click", () => {
resetView(0);
resetView(1);
phase = 0;
scrubInput.value = "0";
});
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedValue.textContent = `${speed.toFixed(1)}×`;
});
scrubInput.addEventListener("input", () => {
phase = Number(scrubInput.value) / 1000;
});
scrubInput.addEventListener("pointerdown", () => {
scrubbing = true;
});
window.addEventListener("pointerup", () => {
scrubbing = false;
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space" && event.target.tagName !== "INPUT") {
event.preventDefault();
setPlaying(paused);
}
if (event.key.toLowerCase() === "r" && event.target.tagName !== "INPUT") {
resetView(0);
resetView(1);
}
});
/* ---------------------------------------------------------
Render loop
--------------------------------------------------------- */
const clock = new THREE.Clock();
function renderScene(view, rect) {
const height = window.innerHeight;
const bottom = height - rect.y - rect.height;
renderer.setViewport(rect.x, bottom, rect.width, rect.height);
renderer.setScissor(rect.x, bottom, rect.width, rect.height);
renderer.render(view.scene, view.camera);
}
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
if (!paused && !scrubbing) {
phase = (phase + (delta / 5.4) * speed) % 1;
}
breath = breathAt(phase);
const derivative = breathAt(phase + 0.002) - breathAt(phase - 0.002);
updateLeftView(breath, derivative);
updateRightView(breath, derivative);
views.forEach(updateCamera);
renderer.setScissorTest(false);
renderer.setViewport(0, 0, window.innerWidth, window.innerHeight);
renderer.clear(true, true, true);
renderer.setScissorTest(true);
viewportRects.forEach((rect, index) => {
renderScene(views[index], rect);
});
renderer.setScissorTest(false);
const inhaling = phase < 0.5;
phaseLabel.textContent = inhaling ? "Inspiration" : "Expiration";
phaseCard.classList.toggle("exhale", !inhaling);
phaseFill.style.width = `${phase * 100}%`;
if (!scrubbing) {
scrubInput.value = String(Math.round(phase * 1000));
}
lateralValue.textContent = `${(3.4 * breath).toFixed(1)} cm`;
liftValue.textContent = `${(2.1 * breath).toFixed(1)} cm`;
diaphragmValue.textContent = `${(4.6 * breath).toFixed(1)} cm`;
volumeValue.textContent = `${(6.3 * breath).toFixed(1)} cm`;
}
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```