Prompt specification
Build or customize the Three.js 3D scene "Volume change and airflow demonstration" 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: Volume change and airflow demonstration
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/volume-change-and-airflow-demonstration-x0962
Scene Description Prompt:
Animate thoracic expansion with inward airflow and contraction with outward airflow under a simple pressure model; keep the airway connected and distinguish lungs from pumping pistons. Use Three.js from cdnjs in a single HTML file, with a 3D cutaway.
Working Three.js Starter (volume-change-and-airflow-demonstration-x0962):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thoracic Pressure and Airflow Lab</title>
<style>
:root {
--bg: #07131d;
--panel: rgba(8, 24, 35, 0.78);
--panel-border: rgba(132, 220, 255, 0.18);
--text: #e9f8ff;
--muted: #91adbb;
--cyan: #67e8f9;
--blue: #5eb7ff;
--red: #ff827f;
--orange: #ffb36b;
--green: #7ee6ae;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #102d3d 0%, #081923 48%, #040b11 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 16px;
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(15px) saturate(125%);
-webkit-backdrop-filter: blur(15px) saturate(125%);
}
#title-panel {
position: absolute;
top: 20px;
left: 20px;
width: min(410px, calc(100vw - 40px));
padding: 18px 20px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 7px;
font-size: clamp(20px, 2.4vw, 30px);
line-height: 1.04;
letter-spacing: -0.035em;
}
.subtitle {
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.model-note {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: #c5dbe5;
font-size: 11px;
line-height: 1.55;
}
.model-note strong {
color: #fff;
}
#readout {
position: absolute;
top: 20px;
right: 20px;
width: 310px;
padding: 17px;
}
.readout-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
#phase {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 9px;
border-radius: 999px;
color: var(--cyan);
background: rgba(103, 232, 249, 0.10);
border: 1px solid rgba(103, 232, 249, 0.18);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
#phase::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
#phase[data-phase="expiration"] {
color: var(--orange);
background: rgba(255, 179, 107, 0.10);
border-color: rgba(255, 179, 107, 0.2);
}
#phase[data-phase="hold"] {
color: var(--green);
background: rgba(126, 230, 174, 0.10);
border-color: rgba(126, 230, 174, 0.2);
}
.cycle-number {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.metric-title {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.pressure-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
margin-top: 5px;
}
#palv {
font-size: 29px;
font-weight: 750;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
#palv-delta {
padding-bottom: 4px;
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.pressure-track {
position: relative;
height: 11px;
margin: 12px 0 4px;
overflow: hidden;
border-radius: 999px;
background:
linear-gradient(90deg,
rgba(94, 183, 255, 0.68) 0%,
rgba(94, 183, 255, 0.16) 49.5%,
rgba(255, 130, 127, 0.17) 50.5%,
rgba(255, 130, 127, 0.68) 100%);
border: 1px solid rgba(255, 255, 255, 0.08);
}
.pressure-zero {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
background: rgba(255, 255, 255, 0.65);
}
#pressure-marker {
position: absolute;
top: -2px;
left: 50%;
width: 3px;
height: 15px;
border-radius: 2px;
background: #fff;
box-shadow: 0 0 9px rgba(255, 255, 255, 0.9);
transform: translateX(-50%);
transition: background-color 120ms ease;
}
.scale-labels {
display: flex;
justify-content: space-between;
color: #708b99;
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.flow-box {
display: flex;
align-items: center;
gap: 10px;
margin-top: 14px;
padding: 10px 11px;
border-radius: 11px;
background: rgba(255, 255, 255, 0.045);
border: 1px solid rgba(255, 255, 255, 0.07);
}
#flow-arrow {
width: 25px;
height: 25px;
display: grid;
place-items: center;
border-radius: 50%;
color: var(--cyan);
background: rgba(103, 232, 249, 0.12);
font-size: 18px;
font-weight: 800;
}
#flow-text {
display: block;
font-size: 11px;
letter-spacing: 0.06em;
}
#flow-value {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.mini-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.mini-metric {
padding: 9px 10px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
border: 1px solid rgba(255, 255, 255, 0.055);
}
.mini-metric span {
display: block;
color: var(--muted);
font-size: 9px;
}
.mini-metric b {
display: block;
margin-top: 4px;
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.equation {
margin-top: 11px;
color: #7693a2;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
line-height: 1.5;
text-align: center;
}
#controls {
position: absolute;
left: 20px;
bottom: 20px;
display: flex;
align-items: center;
gap: 9px;
padding: 10px;
}
button {
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 10px;
padding: 9px 12px;
color: #d9eff8;
background: rgba(255, 255, 255, 0.055);
font: inherit;
font-size: 11px;
font-weight: 650;
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease, transform 150ms ease;
}
button:hover {
background: rgba(103, 232, 249, 0.12);
border-color: rgba(103, 232, 249, 0.30);
}
button:active {
transform: translateY(1px);
}
button.active {
color: var(--cyan);
border-color: rgba(103, 232, 249, 0.35);
background: rgba(103, 232, 249, 0.10);
}
#play {
min-width: 82px;
color: #06131b;
background: var(--cyan);
border-color: transparent;
}
.speed-control {
display: flex;
align-items: center;
gap: 8px;
padding: 0 7px;
color: var(--muted);
font-size: 10px;
}
input[type="range"] {
width: 88px;
accent-color: var(--cyan);
}
#legend {
position: absolute;
right: 20px;
bottom: 20px;
padding: 12px 14px;
color: var(--muted);
font-size: 10px;
line-height: 1.65;
}
.legend-row {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
box-shadow: 0 0 8px currentColor;
}
.swatch.air { color: var(--cyan); background: var(--cyan); }
.swatch.lung { color: var(--red); background: var(--red); }
.swatch.pump { color: var(--orange); background: var(--orange); }
#hint {
position: absolute;
left: 50%;
bottom: 23px;
color: rgba(214, 238, 247, 0.5);
font-size: 10px;
transform: translateX(-50%);
white-space: nowrap;
}
#labels {
position: absolute;
inset: 0;
overflow: hidden;
}
.label {
position: absolute;
min-width: 125px;
padding: 7px 10px;
border-left: 2px solid var(--cyan);
border-radius: 0 8px 8px 0;
color: #e9f8ff;
background: rgba(4, 16, 24, 0.72);
box-shadow: 0 7px 24px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(8px);
transform: translate(-50%, -50%);
opacity: 0;
transition: opacity 120ms ease;
}
.label.visible { opacity: 1; }
.label b {
display: block;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.label span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
white-space: nowrap;
}
.label.lung { border-color: var(--red); }
.label.pump { border-color: var(--orange); }
.label.rib { border-color: #d8c6a0; }
@media (max-width: 900px) {
#readout {
top: auto;
right: 12px;
bottom: 74px;
width: 275px;
}
#title-panel {
top: 12px;
left: 12px;
width: min(360px, calc(100vw - 24px));
}
#controls {
left: 12px;
bottom: 12px;
flex-wrap: wrap;
max-width: calc(100vw - 24px);
}
#legend, #hint, .model-note {
display: none;
}
.label {
display: none;
}
}
@media (max-width: 560px) {
#readout {
right: 8px;
bottom: 104px;
width: 245px;
transform: scale(0.9);
transform-origin: bottom right;
}
#title-panel {
padding: 13px 15px;
}
.subtitle {
display: none;
}
#controls {
gap: 5px;
padding: 7px;
}
button {
padding: 8px 9px;
font-size: 10px;
}
.speed-control {
padding: 0 3px;
}
input[type="range"] {
width: 65px;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div class="hud">
<div id="labels">
<div id="label-lungs" class="label lung">
<b>Passive lungs</b>
<span>compliant tissue · not a piston</span>
</div>
<div id="label-airway" class="label">
<b>Continuous airway</b>
<span>trachea → bronchi → lungs</span>
</div>
<div id="label-diaphragm" class="label pump">
<b>Diaphragm</b>
<span>pressure-generating pump</span>
</div>
<div id="label-ribs" class="label rib">
<b>Rib cage</b>
<span>anterior wall cut away</span>
</div>
</div>
<section id="title-panel" class="panel">
<div class="eyebrow">Interactive respiratory mechanics</div>
<h1>Thoracic Pressure & Airflow</h1>
<div class="subtitle">
A cutaway model in which the diaphragm and ribs change thoracic pressure
while the lungs respond passively as compliant, air-filled tissue.
</div>
<div class="model-note">
<strong>Important:</strong> the lungs do not pump the cycle.
The diaphragm lowers intrapleural pressure during inspiration; elastic
recoil then raises it during expiration. Both lungs remain attached to a
continuously connected airway.
</div>
</section>
<section id="readout" class="panel">
<div class="readout-head">
<div id="phase" data-phase="inspiration">INSPIRATION</div>
<div id="cycle-number" class="cycle-number">CYCLE 01</div>
</div>
<div class="metric-title">Absolute alveolar pressure</div>
<div class="pressure-row">
<div id="palv">757.6 mmHg</div>
<div id="palv-delta">Δ −2.4</div>
</div>
<div class="pressure-track">
<div class="pressure-zero"></div>
<div id="pressure-marker"></div>
</div>
<div class="scale-labels">
<span>−3 mmHg</span>
<span>0</span>
<span>+3 mmHg</span>
</div>
<div class="flow-box">
<div id="flow-arrow">↓</div>
<div>
<b id="flow-text">INWARD AIRFLOW</b>
<span id="flow-value">model Q 0.32 L/s</span>
</div>
</div>
<div class="mini-grid">
<div class="mini-metric">
<span>Intrapleural pressure</span>
<b id="pleural-pressure">−5.2 cmH₂O</b>
</div>
<div class="mini-metric">
<span>Lung volume</span>
<b id="lung-volume">88%</b>
</div>
</div>
<div class="equation">
Q̇in = G(P<sub>atmosphere</sub> − P<sub>alveolar</sub>)
</div>
</section>
<section id="controls" class="panel">
<button id="play" aria-label="Pause simulation">Ⅱ Pause</button>
<div class="speed-control">
<span>Speed</span>
<input id="speed" type="range" min="0.4" max="1.8" step="0.1" value="1">
<span id="speed-value">1.0×</span>
</div>
<button id="ribs" class="active">Ribs on</button>
<button id="airflow" class="active">Flow on</button>
<button id="reset">Reset view</button>
</section>
<section id="legend" class="panel">
<div class="legend-row"><span class="swatch lung"></span> compliant lung tissue</div>
<div class="legend-row"><span class="swatch air"></span> airway and moving air</div>
<div class="legend-row"><span class="swatch pump"></span> pressure-generating muscle</div>
</section>
<div id="hint">Drag to orbit · wheel to zoom · double-click to reset</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
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;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131d);
scene.fog = new THREE.FogExp2(0x07131d, 0.034);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const target = new THREE.Vector3(0, 1.15, 0);
const initialCamera = {
theta: 0.34,
phi: 1.19,
radius: 8.7
};
const desiredCamera = { ...initialCamera };
const currentCamera = { ...initialCamera };
function updateCamera() {
const { theta, phi, radius } = currentCamera;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
updateCamera();
/* ------------------------------------------------------------------ */
/* Lights and stage */
/* ------------------------------------------------------------------ */
const hemi = new THREE.HemisphereLight(0xbdefff, 0x10131a, 1.75);
scene.add(hemi);
const key = new THREE.DirectionalLight(0xffe1cf, 2.65);
key.position.set(4.5, 6.5, 5.5);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -6;
key.shadow.camera.right = 6;
key.shadow.camera.top = 7;
key.shadow.camera.bottom = -4;
key.shadow.bias = -0.0004;
scene.add(key);
const rim = new THREE.DirectionalLight(0x55d8ff, 1.55);
rim.position.set(-5, 3, -3);
scene.add(rim);
const warmPoint = new THREE.PointLight(0xff6e70, 18, 9, 2);
warmPoint.position.set(-3.3, 0.7, 2.5);
scene.add(warmPoint);
const floor = new THREE.Mesh(
new THREE.CircleGeometry(4.7, 96),
new THREE.MeshStandardMaterial({
color: 0x0a1c27,
roughness: 0.92,
metalness: 0.08,
transparent: true,
opacity: 0.72
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.04;
floor.receiveShadow = true;
scene.add(floor);
for (const radius of [3.55, 4.18]) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius, radius + 0.012, 96),
new THREE.MeshBasicMaterial({
color: 0x2e718b,
transparent: true,
opacity: 0.30,
side: THREE.DoubleSide
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = -1.025;
scene.add(ring);
}
/* ------------------------------------------------------------------ */
/* Anatomy helpers */
/* ------------------------------------------------------------------ */
function tubeFrom(points, radius, material, segments = 48) {
const curve = new THREE.CatmullRomCurve3(
points.map((p) => new THREE.Vector3(...p)),
false,
"catmullrom",
0.42
);
const mesh = new THREE.Mesh(
new THREE.TubeGeometry(curve, segments, radius, 10, false),
material
);
return mesh;
}
function updateCylinderBetween(mesh, start, end) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.scale.y = length;
}
/* ------------------------------------------------------------------ */
/* Spine and cutaway rib cage */
/* ------------------------------------------------------------------ */
const anatomy = new THREE.Group();
scene.add(anatomy);
const boneMaterial = new THREE.MeshStandardMaterial({
color: 0xd6c7aa,
roughness: 0.72,
metalness: 0.03,
transparent: true,
opacity: 0.70,
depthWrite: false
});
const vertebraMaterial = new THREE.MeshStandardMaterial({
color: 0xcabf9e,
roughness: 0.78,
metalness: 0.02,
transparent: true,
opacity: 0.73
});
for (let i = 0; i < 12; i++) {
const vertebra = new THREE.Mesh(
new THREE.BoxGeometry(0.36, 0.135, 0.29),
vertebraMaterial
);
vertebra.position.set(0, 0.08 + i * 0.225, -0.76);
vertebra.rotation.x = (i % 2 ? 1 : -1) * 0.025;
vertebra.castShadow = true;
anatomy.add(vertebra);
const process = new THREE.Mesh(
new THREE.BoxGeometry(0.10, 0.10, 0.31),
vertebraMaterial
);
process.position.set(0, 0.06 + i * 0.225, -0.99);
anatomy.add(process);
}
const spinalColumn = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 2.75, 12),
new THREE.MeshStandardMaterial({
color: 0x96d6df,
roughness: 0.65,
transparent: true,
opacity: 0.30
})
);
spinalColumn.position.set(0, 1.30, -0.75);
anatomy.add(spinalColumn);
const ribGroup = new THREE.Group();
anatomy.add(ribGroup);
for (let i = 0; i < 9; i++) {
const y = 0.00 + i * 0.30;
const taper = 1 - i * 0.025;
const rightPoints = [
[0.10, y, -0.73],
[0.68 * taper, y + 0.04, -0.70],
[1.43 * taper, y + 0.08, -0.42],
[2.03 * taper, y + 0.01, -0.02],
[2.13 * taper, y - 0.10, 0.56],
[1.69 * taper, y - 0.23, 1.00]
];
const rightRib = tubeFrom(rightPoints, 0.045, boneMaterial, 54);
rightRib.castShadow = true;
ribGroup.add(rightRib);
const leftRib = new THREE.Mesh(rightRib.geometry, boneMaterial);
leftRib.scale.x = -1;
leftRib.castShadow = true;
ribGroup.add(leftRib);
// Small cut ends emphasize that the front wall has been removed.
const rightEnd = new THREE.Mesh(
new THREE.SphereGeometry(0.053, 12, 8),
boneMaterial
);
rightEnd.position.set(...rightPoints.at(-1));
ribGroup.add(rightEnd);
const leftEnd = rightEnd.clone();
leftEnd.position.x *= -1;
ribGroup.add(leftEnd);
}
/* ------------------------------------------------------------------ */
/* Diaphragm: the pressure-generating pump */
/* ------------------------------------------------------------------ */
const diaphragmRadius = 2.08;
const diaphragmGeometry = new THREE.SphereGeometry(
diaphragmRadius,
64,
24,
0,
Math.PI * 2,
0,
Math.PI / 2
);
diaphragmGeometry.translate(0, -diaphragmRadius, 0);
const diaphragm = new THREE.Mesh(
diaphragmGeometry,
new THREE.MeshStandardMaterial({
color: 0xb94d59,
roughness: 0.56,
metalness: 0.02,
transparent: true,
opacity: 0.84,
side: THREE.DoubleSide,
depthWrite: false
})
);
diaphragm.renderOrder = 1;
diaphragm.castShadow = true;
anatomy.add(diaphragm);
const centralTendon = new THREE.Mesh(
new THREE.SphereGeometry(1, 32, 16),
new THREE.MeshStandardMaterial({
color: 0xe0a69a,
roughness: 0.62,
transparent: true,
opacity: 0.72
})
);
centralTendon.scale.set(0.73, 0.055, 0.92);
centralTendon.renderOrder = 1;
anatomy.add(centralTendon);
/* ------------------------------------------------------------------ */
/* Passive, deforming lungs */
/* ------------------------------------------------------------------ */
function smootherStep(x) {
x = Math.max(0, Math.min(1, x));
return x * x * x * (x * (x * 6 - 15) + 10);
}
class PassiveLung {
constructor(side) {
this.side = side;
this.root = side * 0.36;
this.halfWidth = side > 0 ? 0.86 : 0.82;
this.height = 2.65;
this.depth = side > 0 ? 0.72 : 0.69;
this.baseY = -0.02;
this.zCenter = side > 0 ? 0.04 : -0.04;
this.geometry = new THREE.SphereGeometry(1, 48, 32);
this.basePositions = this.geometry.attributes.position.array.slice();
const material = new THREE.MeshPhysicalMaterial({
color: side > 0 ? 0xff8c88 : 0xff9b94,
roughness: 0.40,
metalness: 0.0,
clearcoat: 0.18,
clearcoatRoughness: 0.56,
transparent: true,
opacity: 0.68,
side: THREE.DoubleSide,
depthWrite: false
});
this.mesh = new THREE.Mesh(this.geometry, material);
this.mesh.renderOrder = 2;
this.mesh.frustumCulled = false;
this.mesh.castShadow = true;
anatomy.add(this.mesh);
this.lastQ = -1;
this.update(0);
this.createInternalAirfield();
this.createFissures();
}
mapDirection(direction, q) {
const [dx, dy, dz] = direction;
const outward = this.side * dx;
const t = (dy + 1) * 0.5;
const x =
this.root +
(outward + 1) * this.halfWidth * (1 + 0.24 * q);
let y;
if (t >= 0.5) {
// The upper lung expands while the hilar midpoint stays fixed.
y =
this.baseY +
t * this.height +
q * 0.18 * ((t - 0.5) / 0.5);
} else {
// The base moves down slightly as the diaphragm descends.
y =
this.baseY +
t * this.height -
q * 0.10 * ((0.5 - t) / 0.5);
}
const z =
this.zCenter +
dz * this.depth * (1 + 0.20 * q);
return new THREE.Vector3(x, y, z);
}
update(q) {
if (Math.abs(q - this.lastQ) < 0.0002) return;
this.lastQ = q;
const positions = this.geometry.attributes.position.array;
const base = this.basePositions;
for (let i = 0; i < positions.length; i += 3) {
const dx = base[i];
const dy = base[i + 1];
const dz = base[i + 2];
const outward = this.side * dx;
const t = (dy + 1) * 0.5;
const x =
this.root +
(outward + 1) * this.halfWidth * (1 + 0.24 * q);
let y;
if (t >= 0.5) {
y =
this.baseY +
t * this.height +
q * 0.18 * ((t - 0.5) / 0.5);
} else {
y =
this.baseY +
t * this.height -
q * 0.10 * ((0.5 - t) / 0.5);
}
const z =
this.zCenter +
dz * this.depth * (1 + 0.20 * q);
positions[i] = x;
positions[i + 1] = y;
positions[i + 2] = z;
}
this.geometry.attributes.position.needsUpdate = true;
this.geometry.computeVertexNormals();
if (this.airPoints) this.updateAirfield(q);
if (this.fissureLines) this.updateFissures(q);
}
createInternalAirfield() {
const count = 190;
const directions = [];
const positions = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
const y = Math.random() * 2 - 1;
const angle = Math.random() * Math.PI * 2;
const radius = Math.sqrt(1 - y * y);
directions.push([
radius * Math.cos(angle),
y,
radius * Math.sin(angle)
]);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
const material = new THREE.PointsMaterial({
color: 0xffddd5,
size: 0.028,
transparent: true,
opacity: 0.30,
depthWrite: false,
blending: THREE.AdditiveBlending
});
this.airPoints = new THREE.Points(geometry, material);
this.airPoints.renderOrder = 3;
this.airPoints.frustumCulled = false;
this.airDirections = directions;
anatomy.add(this.airPoints);
}
updateAirfield(q) {
const positions = this.airPoints.geometry.attributes.position.array;
const center = new THREE.Vector3(
this.root + this.halfWidth * (1 + 0.24 * q),
this.baseY + this.height * 0.5,
this.zCenter
);
for (let i = 0; i < this.airDirections.length; i++) {
const surface = this.mapDirection(this.airDirections[i], q);
const inset = 0.68 + (i % 11) / 11 * 0.22;
positions[i * 3] =
center.x + (surface.x - center.x) * inset;
positions[i * 3 + 1] =
center.y + (surface.y - center.y) * inset;
positions[i * 3 + 2] =
center.z + (surface.z - center.z) * inset;
}
this.airPoints.geometry.attributes.position.needsUpdate = true;
}
createFissures() {
this.fissureDefinitions = [];
if (this.side > 0) {
this.fissureDefinitions.push({
points: [
[0.20, 0.86, 0.46],
[0.57, 0.39, 0.73],
[0.88, -0.10, 0.45]
]
});
this.fissureDefinitions.push({
points: [
[0.30, 0.26, 0.92],
[0.73, 0.22, 0.66],
[1.00, 0.16, 0.14]
]
});
} else {
this.fissureDefinitions.push({
points: [
[-0.20, 0.86, 0.46],
[-0.57, 0.37, 0.74],
[-0.88, -0.12, 0.45]
]
});
}
this.fissureLines = this.fissureDefinitions.map(() => {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(48 * 3), 3)
);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color: 0x8f3042,
transparent: true,
opacity: 0.72,
depthWrite: false
})
);
line.renderOrder = 3;
line.frustumCulled = false;
anatomy.add(line);
return line;
});
this.updateFissures(this.lastQ);
}
updateFissures(q) {
this.fissureDefinitions.forEach((definition, index) => {
const curve = new THREE.CatmullRomCurve3(
definition.points.map((p) => new THREE.Vector3(...p)),
false,
"catmullrom",
0.35
);
const positions = this.fissureLines[index].geometry.attributes.position.array;
for (let i = 0; i < 48; i++) {
const point = curve.getPoint(i / 47).normalize();
const mapped = this.mapDirection(
[point.x, point.y, point.z],
q
);
positions[i * 3] = mapped.x;
positions[i * 3 + 1] = mapped.y;
positions[i * 3 + 2] = mapped.z;
}
this.fissureLines[index].geometry.attributes.position.needsUpdate = true;
});
}
}
const rightLung = new PassiveLung(1);
const leftLung = new PassiveLung(-1);
/* ------------------------------------------------------------------ */
/* Connected airway */
/* ------------------------------------------------------------------ */
const airwayMaterial = new THREE.MeshStandardMaterial({
color: 0x78e5ff,
emissive: 0x075c76,
emissiveIntensity: 1.0,
roughness: 0.36,
metalness: 0.05,
transparent: true,
opacity: 0.94,
depthWrite: false
});
const trachea = tubeFrom(
[
[0, 3.38, 0.08],
[0, 2.82, 0.07],
[0, 2.20, 0.03],
[0, 1.74, 0]
],
0.115,
airwayMaterial,
44
);
trachea.renderOrder = 4;
anatomy.add(trachea);
const cartilageMaterial = new THREE.MeshStandardMaterial({
color: 0xbceeff,
emissive: 0x12465a,
emissiveIntensity: 0.6,
roughness: 0.55,
transparent: true,
opacity: 0.74,
depthWrite: false
});
for (let i = 0; i < 11; i++) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.125, 0.017, 8, 28),
cartilageMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.set(0, 1.98 + i * 0.122, 0.045);
ring.renderOrder = 4;
anatomy.add(ring);
}
const bifurcation = new THREE.Mesh(
new THREE.SphereGeometry(0.13, 18, 12),
airwayMaterial
);
bifurcation.position.set(0, 1.74, 0);
bifurcation.renderOrder = 4;
anatomy.add(bifurcation);
const hilumPositions = {
right: new THREE.Vector3(0.36, 1.305, 0.04),
left: new THREE.Vector3(-0.36, 1.305, -0.04)
};
for (const side of [1, -1]) {
const end = side > 0
? hilumPositions.right
: hilumPositions.left;
const mainBronchus = tubeFrom(
[
[0, 1.74, 0],
[side * 0.18, 1.53, end.z * 0.45],
[end.x, end.y, end.z]
],
0.085,
airwayMaterial,
30
);
mainBronchus.renderOrder = 4;
anatomy.add(mainBronchus);
const hilum = new THREE.Mesh(
new THREE.SphereGeometry(0.10, 16, 12),
airwayMaterial
);
hilum.position.copy(end);
hilum.renderOrder = 4;
anatomy.add(hilum);
}
// Distal bronchioles flex with the lungs, but their proximal ends remain
// attached to the fixed hilar junction.
const bronchioles = [];
for (const side of [1, -1]) {
const start = side > 0
? hilumPositions.right.clone()
: hilumPositions.left.clone();
const definitions = [
{
radius: 0.040,
end: new THREE.Vector3(side * 1.10, 2.03, side * 0.03)
},
{
radius: 0.034,
end: new THREE.Vector3(side * 1.42, 1.36, side * 0.13)
},
{
radius: 0.034,
end: new THREE.Vector3(side * 1.18, 0.57, side * 0.08)
}
];
for (const definition of definitions) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
definition.radius,
definition.radius * 1.15,
1,
10
),
airwayMaterial
);
mesh.renderOrder = 4;
anatomy.add(mesh);
bronchioles.push({
mesh,
start: start.clone(),
side,
definition
});
}
}
function updateBronchioles(q) {
for (const bronchiole of bronchioles) {
const end = bronchiole.definition.end.clone();
end.x = bronchiole.side * (
Math.abs(end.x) + 0.24 * q
);
end.y += 0.035 * q;
updateCylinderBetween(
bronchiole.mesh,
bronchiole.start,
end
);
}
}
/* ------------------------------------------------------------------ */
/* Flow particles and pressure arrows */
/* ------------------------------------------------------------------ */
const flowCurves = [
new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 3.26, 0.10),
new THREE.Vector3(0, 2.35, 0.07),
new THREE.Vector3(0, 1.74, 0.02),
new THREE.Vector3(0.36, 1.305, 0.04),
new THREE.Vector3(1.02, 1.91, 0.04)
]),
new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 3.26, 0.10),
new THREE.Vector3(0, 2.35, 0.07),
new THREE.Vector3(0, 1.74, 0.02),
new THREE.Vector3(0.36, 1.305, 0.04),
new THREE.Vector3(1.18, 0.70, 0.08)
]),
new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 3.26, 0.10),
new THREE.Vector3(0, 2.35, 0.07),
new THREE.Vector3(0, 1.74, 0.02),
new THREE.Vector3(-0.36, 1.305, -0.04),
new THREE.Vector3(-1.02, 1.95, -0.04)
]),
new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 3.26, 0.10),
new THREE.Vector3(0, 2.35, 0.07),
new THREE.Vector3(0, 1.74, 0.02),
new THREE.Vector3(-0.36, 1.305, -0.04),
new THREE.Vector3(-1.18, 0.70, -0.08)
])
];
const particleCount = 64;
const particlePositions = new Float32Array(particleCount * 3);
const particleSeeds = [];
for (let i = 0; i < particleCount; i++) {
particleSeeds.push(Math.random());
}
const flowGeometry = new THREE.BufferGeometry();
flowGeometry.setAttribute(
"position",
new THREE.BufferAttribute(particlePositions, 3)
);
const flowMaterial = new THREE.PointsMaterial({
color: 0x85efff,
size: 0.065,
transparent: true,
opacity: 0,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const flowParticles = new THREE.Points(flowGeometry, flowMaterial);
flowParticles.renderOrder = 6;
flowParticles.frustumCulled = false;
scene.add(flowParticles);
function configureArrow(arrow) {
arrow.line.material.transparent = true;
arrow.line.material.depthWrite = false;
arrow.line.material.depthTest = false;
arrow.cone.material.transparent = true;
arrow.cone.material.depthWrite = false;
arrow.cone.material.depthTest = false;
arrow.renderOrder = 7;
}
const trachealArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(0, 3.78, 0),
0.6,
0x67e8f9,
0.16,
0.09
);
configureArrow(trachealArrow);
scene.add(trachealArrow);
const rightLungArrow = new THREE.ArrowHelper(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(2.45, 1.28, 0.12),
0.42,
0x67e8f9,
0.13,
0.08
);
configureArrow(rightLungArrow);
scene.add(rightLungArrow);
const leftLungArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(-2.45, 1.28, 0.12),
0.42,
0x67e8f9,
0.13,
0.08
);
configureArrow(leftLungArrow);
scene.add(leftLungArrow);
/* ------------------------------------------------------------------ */
/* Simple pressure model */
/* ------------------------------------------------------------------ */
const AMBIENT_PRESSURE = 760;
const CYCLE_DURATION = 7.2;
let simulationTime = 0.85;
let flowTravel = 0;
let playing = true;
let simulationSpeed = 1;
let showAirflow = true;
function pressureModel(phase) {
let volume = 0;
let alveolarDelta = 0;
let phaseName = "hold";
if (phase < 0.42) {
// Inspiration: negative alveolar pressure drives air inward.
const h = phase / 0.42;
volume = smootherStep(h);
alveolarDelta = -2.4 * Math.sin(Math.PI * h);
phaseName = "inspiration";
} else if (phase < 0.52) {
// End-inspiratory hold.
volume = 1;
phaseName = "hold";
} else if (phase < 0.90) {
// Expiration: positive alveolar pressure drives air outward.
const h = (phase - 0.52) / 0.38;
volume = 1 - smootherStep(h);
alveolarDelta = 1.8 * Math.sin(Math.PI * h);
phaseName = "expiration";
} else {
// End-expiratory hold.
volume = 0;
phaseName = "hold";
}
const pleuralPressure = -6.0 * volume;
return {
volume,
alveolarDelta,
absoluteAlveolarPressure: AMBIENT_PRESSURE + alveolarDelta,
pleuralPressure,
phaseName
};
}
/* ------------------------------------------------------------------ */
/* Labels */
/* ------------------------------------------------------------------ */
const labelDefinitions = [
{
element: $("label-lungs"),
position: () => new THREE.Vector3(-1.25, 1.24, 0.86)
},
{
element: $("label-airway"),
position: () => new THREE.Vector3(0.25, 2.76, 0.18)
},
{
element: $("label-diaphragm"),
position: () => new THREE.Vector3(0.55, -0.30, 0.82)
},
{
element: $("label-ribs"),
position: () => new THREE.Vector3(2.03, 2.16, 0.05)
}
];
const projected = new THREE.Vector3();
function updateLabels() {
for (const definition of labelDefinitions) {
projected.copy(definition.position()).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.1 &&
Math.abs(projected.y) < 1.1;
definition.element.classList.toggle("visible", visible);
if (visible) {
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
definition.element.style.left = `${x}px`;
definition.element.style.top = `${y}px`;
}
}
}
/* ------------------------------------------------------------------ */
/* Custom camera controls: no addons */
/* ------------------------------------------------------------------ */
let dragging = false;
let previousX = 0;
let previousY = 0;
let pointerId = null;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerId = event.pointerId;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== pointerId) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
desiredCamera.theta -= dx * 0.006;
desiredCamera.phi = Math.max(
0.48,
Math.min(1.48, desiredCamera.phi - dy * 0.005)
);
});
function stopDragging(event) {
if (event.pointerId !== pointerId) return;
dragging = false;
pointerId = null;
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredCamera.radius = Math.max(
5.2,
Math.min(14, desiredCamera.radius + event.deltaY * 0.006)
);
},
{ passive: false }
);
function resetView() {
desiredCamera.theta = initialCamera.theta;
desiredCamera.phi = initialCamera.phi;
desiredCamera.radius = initialCamera.radius;
}
canvas.addEventListener("dblclick", resetView);
/* ------------------------------------------------------------------ */
/* UI controls */
/* ------------------------------------------------------------------ */
$("play").addEventListener("click", () => {
playing = !playing;
$("play").textContent = playing ? "Ⅱ Pause" : "▶ Play";
});
$("speed").addEventListener("input", (event) => {
simulationSpeed = Number(event.target.value);
$("speed-value").textContent = `${simulationSpeed.toFixed(1)}×`;
});
$("ribs").addEventListener("click", () => {
ribGroup.visible = !ribGroup.visible;
$("ribs").classList.toggle("active", ribGroup.visible);
$("ribs").textContent = ribGroup.visible ? "Ribs on" : "Ribs off";
});
$("airflow").addEventListener("click", () => {
showAirflow = !showAirflow;
$("airflow").classList.toggle("active", showAirflow);
$("airflow").textContent = showAirflow ? "Flow on" : "Flow off";
});
$("reset").addEventListener("click", resetView);
function updateReadout(model, cycleNumber) {
const delta = model.alveolarDelta;
$("phase").dataset.phase = model.phaseName;
$("phase").textContent =
model.phaseName === "hold"
? "PRESSURE HOLD"
: model.phaseName.toUpperCase();
$("cycle-number").textContent =
`CYCLE ${String(cycleNumber).padStart(2, "0")}`;
$("palv").textContent =
`${model.absoluteAlveolarPressure.toFixed(1)} mmHg`;
$("palv-delta").textContent =
`Δ ${delta >= 0 ? "+" : ""}${delta.toFixed(1)}`;
const marker = Math.max(0, Math.min(100, 50 + delta / 3 * 50));
$("pressure-marker").style.left = `${marker}%`;
$("pressure-marker").style.backgroundColor =
delta < 0 ? "#67e8f9" : delta > 0 ? "#ff827f" : "#ffffff";
let flowText = "NO FLOW";
let arrow = "•";
let color = "#c5dbe5";
if (delta < -0.03) {
flowText = "INWARD AIRFLOW";
arrow = "↓";
color = "#67e8f9";
} else if (delta > 0.03) {
flowText = "OUTWARD AIRFLOW";
arrow = "↑";
color = "#ffb36b";
}
$("flow-text").textContent = flowText;
$("flow-text").style.color = color;
$("flow-arrow").textContent = arrow;
$("flow-arrow").style.color = color;
const modelFlow = Math.abs(delta) / 2.4 * 0.65;
$("flow-value").textContent =
`model Q ${modelFlow.toFixed(2)} L/s`;
$("pleural-pressure").textContent =
`${model.pleuralPressure.toFixed(1)} cmH₂O`;
$("lung-volume").textContent =
`${Math.round(model.volume * 100)}%`;
}
/* ------------------------------------------------------------------ */
/* Animation */
/* ------------------------------------------------------------------ */
function updateFlow(model, dt) {
const pressure = model.alveolarDelta;
if (pressure < -0.01) {
const strength = Math.min(1, -pressure / 1.2);
flowTravel += dt * simulationSpeed * strength * 0.72;
} else if (pressure > 0.01) {
const strength = Math.min(1, pressure / 1.2);
flowTravel -= dt * simulationSpeed * strength * 0.72;
}
const intensity = Math.min(1, Math.abs(pressure) / 0.75);
flowMaterial.opacity = showAirflow ? intensity * 0.92 : 0;
flowParticles.visible = showAirflow && intensity > 0.015;
if (flowParticles.visible) {
for (let i = 0; i < particleCount; i++) {
const curve = flowCurves[i % flowCurves.length];
const t = ((particleSeeds[i] + flowTravel) % 1 + 1) % 1;
const point = curve.getPointAt(t);
particlePositions[i * 3] = point.x;
particlePositions[i * 3 + 1] = point.y;
particlePositions[i * 3 + 2] = point.z;
}
flowGeometry.attributes.position.needsUpdate = true;
}
const arrowVisible =
showAirflow && Math.abs(pressure) > 0.035;
trachealArrow.visible = arrowVisible;
rightLungArrow.visible = arrowVisible;
leftLungArrow.visible = arrowVisible;
if (arrowVisible) {
const color = pressure < 0 ? 0x67e8f9 : 0xffb36b;
const length = 0.36 + intensity * 0.38;
trachealArrow.setColor(color);
rightLungArrow.setColor(color);
leftLungArrow.setColor(color);
if (pressure < 0) {
trachealArrow.setDirection(new THREE.Vector3(0, -1, 0));
trachealArrow.position.set(0, 3.79, 0);
rightLungArrow.setDirection(new THREE.Vector3(-1, 0, 0));
leftLungArrow.setDirection(new THREE.Vector3(1, 0, 0));
} else {
trachealArrow.setDirection(new THREE.Vector3(0, 1, 0));
trachealArrow.position.set(0, 3.38, 0);
rightLungArrow.setDirection(new THREE.Vector3(1, 0, 0));
leftLungArrow.setDirection(new THREE.Vector3(-1, 0, 0));
}
trachealArrow.setLength(length + 0.12, 0.16, 0.09);
rightLungArrow.setLength(length, 0.13, 0.08);
leftLungArrow.setLength(length, 0.13, 0.08);
rightLungArrow.position.set(
2.12 + model.volume * 0.43,
1.28,
0.12
);
leftLungArrow.position.set(
-2.10 - model.volume * 0.42,
1.28,
0.12
);
for (const arrow of [
trachealArrow,
rightLungArrow,
leftLungArrow
]) {
arrow.line.material.opacity = 0.35 + intensity * 0.65;
arrow.cone.material.opacity = 0.35 + intensity * 0.65;
}
}
}
const clock = new THREE.Clock();
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
if (playing) {
simulationTime += dt * simulationSpeed;
}
const phase = (simulationTime % CYCLE_DURATION) / CYCLE_DURATION;
const cycleNumber = Math.floor(simulationTime / CYCLE_DURATION) + 1;
const model = pressureModel(phase);
// The pump structures change pressure and thoracic geometry.
const diaphragmScale = 0.16 - model.volume * 0.11;
diaphragm.scale.y = diaphragmScale;
diaphragm.position.y = -0.48 + diaphragmRadius * diaphragmScale;
centralTendon.position.set(0, diaphragm.position.y, 0);
ribGroup.scale.set(
1 + model.volume * 0.045,
1,
1 + model.volume * 0.025
);
ribGroup.position.y = model.volume * 0.025;
// The lungs respond passively; they do not translate as rigid pistons.
rightLung.update(model.volume);
leftLung.update(model.volume);
updateBronchioles(model.volume);
updateFlow(model, dt);
updateReadout(model, cycleNumber);
// Damped camera movement.
currentCamera.theta +=
(desiredCamera.theta - currentCamera.theta) * 0.10;
currentCamera.phi +=
(desiredCamera.phi - currentCamera.phi) * 0.10;
currentCamera.radius +=
(desiredCamera.radius - currentCamera.radius) * 0.10;
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
```