Prompt specification
Build or customize the Three.js 3D scene "Linear and cross-linked network 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: Linear and cross-linked network comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/linear-and-cross-linked-network-comparison-x1982
Scene Description Prompt:
Linear and cross-linked network comparison. Place freely rearranging chain models beside a network with explicit cross-links; illustrate differing mobility qualitatively without claiming all polymers follow one simple mechanical rule. Please build this with Three.js from cdnjs in one self-contained HTML file, using a 3D cutaway.
Working Three.js Starter (linear-and-cross-linked-network-comparison-x1982):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Polymer Architecture — Linear vs. Cross-linked</title>
<style>
:root {
color-scheme: dark;
--bg: #07111b;
--panel: rgba(9, 22, 34, 0.86);
--panel-border: rgba(157, 213, 255, 0.16);
--text: #e9f5ff;
--muted: #91a9ba;
--cyan: #55dcff;
--violet: #9b8cff;
--amber: #ffc65c;
--pink: #ff68aa;
}
* {
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;
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas.dragging {
cursor: grabbing;
}
.hud {
position: fixed;
z-index: 5;
pointer-events: none;
}
.header {
top: 22px;
left: 24px;
right: 24px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 24px;
}
.brand {
max-width: 670px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.55);
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 8px;
color: var(--cyan);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px var(--cyan);
content: "";
}
h1 {
margin: 0;
font-size: clamp(25px, 3.1vw, 43px);
font-weight: 720;
letter-spacing: -0.035em;
line-height: 1.03;
}
.subtitle {
max-width: 610px;
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.controls {
position: fixed;
top: 22px;
right: 24px;
z-index: 10;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: 390px;
}
button {
appearance: none;
border: 1px solid rgba(154, 216, 255, 0.2);
border-radius: 10px;
padding: 9px 12px;
background: rgba(9, 24, 37, 0.86);
color: #dff5ff;
font: inherit;
font-size: 12px;
font-weight: 650;
cursor: pointer;
backdrop-filter: blur(12px);
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
button:hover {
border-color: rgba(85, 220, 255, 0.55);
background: rgba(18, 42, 57, 0.95);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.legend {
right: 24px;
bottom: 190px;
display: grid;
grid-template-columns: auto auto;
gap: 8px 14px;
padding: 12px 14px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(7, 18, 28, 0.72);
color: #b7cad7;
font-size: 11px;
backdrop-filter: blur(10px);
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
white-space: nowrap;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 8px currentColor;
}
.swatch.bond {
width: 15px;
height: 3px;
border-radius: 4px;
background: #b8e8f5;
}
.swatch.cross {
width: 15px;
height: 3px;
border-radius: 4px;
background: var(--amber);
}
.swatch.anchor {
background: var(--pink);
}
.insights {
left: 50%;
bottom: 18px;
width: min(1120px, calc(100% - 36px));
transform: translateX(-50%);
display: grid;
grid-template-columns: 1fr 1fr 1.12fr;
gap: 10px;
}
.insight {
min-height: 132px;
padding: 15px 16px;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(16px);
}
.insight::before {
display: block;
width: 31px;
height: 3px;
margin-bottom: 11px;
border-radius: 99px;
background: var(--cyan);
content: "";
}
.insight.cross::before {
background: var(--violet);
}
.insight.scope::before {
background: var(--amber);
}
.insight h2 {
margin: 0 0 7px;
font-size: 13px;
letter-spacing: 0.01em;
}
.insight p {
margin: 0;
color: #9fb4c2;
font-size: 11.5px;
line-height: 1.55;
}
.interaction-hint {
left: 24px;
bottom: 192px;
color: rgba(180, 205, 220, 0.66);
font-size: 10.5px;
letter-spacing: 0.04em;
}
#loading {
position: fixed;
inset: 0;
z-index: 30;
display: grid;
place-items: center;
background: var(--bg);
color: var(--muted);
font-size: 13px;
transition: opacity 300ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 900px) {
.header {
right: 18px;
left: 18px;
}
.controls {
top: 132px;
right: 18px;
max-width: 260px;
}
.legend {
display: none;
}
.interaction-hint {
display: none;
}
.insights {
width: calc(100% - 24px);
grid-template-columns: repeat(3, minmax(230px, 1fr));
overflow-x: auto;
scrollbar-width: thin;
}
}
@media (max-width: 560px) {
.header {
top: 16px;
}
.subtitle {
max-width: 320px;
font-size: 11px;
}
.controls {
top: 122px;
right: 12px;
max-width: 210px;
}
button {
padding: 8px 10px;
font-size: 10.5px;
}
.insights {
bottom: 10px;
}
.insight {
min-height: 145px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<header class="hud header">
<div class="brand">
<div class="eyebrow">Polymer architecture · qualitative 3D cutaway</div>
<h1>Linear chains vs. a cross-linked network</h1>
<p class="subtitle">
Independent strands can change their arrangement when conditions permit.
Explicit junctions connect strands into a network, limiting large-scale
rearrangement while preserving local motion.
</p>
</div>
</header>
<nav class="controls" aria-label="Scene controls">
<button id="pauseButton" type="button">Ⅱ Pause motion</button>
<button id="resetMotionButton" type="button">Reset motion</button>
<button id="resetViewButton" type="button">Reset view</button>
</nav>
<div class="hud legend" aria-label="Visualization legend">
<div class="legend-item"><span class="swatch"></span>monomer / bead</div>
<div class="legend-item"><span class="swatch bond"></span>chain bond</div>
<div class="legend-item"><span class="swatch cross"></span>cross-link</div>
<div class="legend-item"><span class="swatch anchor"></span>frame anchor</div>
</div>
<div class="hud interaction-hint">Drag to orbit · wheel or pinch to zoom · double-click to reset</div>
<section class="hud insights" aria-label="Comparison notes">
<article class="insight">
<h2>Linear architecture</h2>
<p>
The strands have no permanent inter-chain junctions. In this schematic
they can slide past neighbors and reorganize their overall configuration.
</p>
</article>
<article class="insight cross">
<h2>Cross-linked architecture</h2>
<p>
Amber bridges are explicit inter-chain junctions. They restrain
large-scale rearrangement, but the network is not motionless: local bond
and segment motion remain.
</p>
</article>
<article class="insight scope">
<h2>Conceptual scope</h2>
<p>
This is not a universal mechanical rule. Real mobility also depends on
chemistry, temperature, density, solvent, load, plasticization, and
cross-link density.
</p>
</article>
</section>
<div id="loading">Loading the 3D comparison…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111b);
scene.fog = new THREE.FogExp2(0x07111b, 0.025);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xbfe8ff, 0x152132, 1.8));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4, 9, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x38cfff, 24, 12, 2);
cyanLight.position.set(-6, 2.5, 4);
scene.add(cyanLight);
const violetLight = new THREE.PointLight(0x8070ff, 22, 12, 2);
violetLight.position.set(6, 2.0, 3);
scene.add(violetLight);
// -------------------------------------------------------------------------
// Small helpers
// -------------------------------------------------------------------------
const UP = new THREE.Vector3(0, 1, 0);
const tempDirection = new THREE.Vector3();
const dummy = new THREE.Object3D();
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeLabelSprite(title, subtitle, accent) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 230;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 8, 8, 1008, 214, 28);
ctx.fillStyle = "rgba(6, 18, 29, 0.90)";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = accent;
ctx.stroke();
ctx.fillStyle = accent;
roundedRect(ctx, 32, 31, 10, 168, 5);
ctx.fill();
ctx.textBaseline = "alphabetic";
ctx.fillStyle = "#eefaff";
ctx.font = "700 58px system-ui, sans-serif";
ctx.fillText(title, 68, 102);
ctx.fillStyle = "#9fb8c8";
ctx.font = "500 29px system-ui, sans-serif";
ctx.fillText(subtitle, 68, 159);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(4.9, 1.1, 1);
sprite.renderOrder = 30;
return sprite;
}
function setInstanceMatrix(mesh, index, position, quaternion, scale) {
dummy.position.copy(position);
dummy.quaternion.copy(quaternion);
dummy.scale.copy(scale);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
}
function positionRod(mesh, index, a, b) {
tempDirection.subVectors(b, a);
const length = tempDirection.length();
if (length < 0.00001) {
dummy.position.copy(a);
dummy.quaternion.identity();
dummy.scale.set(1, 0.001, 1);
} else {
tempDirection.multiplyScalar(1 / length);
dummy.position.copy(a).add(b).multiplyScalar(0.5);
dummy.quaternion.setFromUnitVectors(UP, tempDirection);
dummy.scale.set(1, length, 1);
}
dummy.updateMatrix();
if (mesh.isInstancedMesh) {
mesh.setMatrixAt(index, dummy.matrix);
} else {
dummy.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);
}
}
// -------------------------------------------------------------------------
// Cutaway chamber
// -------------------------------------------------------------------------
function buildChamber(accentHex) {
const group = new THREE.Group();
const width = 6.65;
const depth = 3.35;
const height = 4.55;
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x203442,
roughness: 0.48,
metalness: 0.62
});
const accentMaterial = new THREE.MeshStandardMaterial({
color: accentHex,
emissive: accentHex,
emissiveIntensity: 0.5,
roughness: 0.34,
metalness: 0.4
});
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0x7dc9e8,
transparent: true,
opacity: 0.045,
roughness: 0.12,
metalness: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const floor = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.22, 0.14, depth + 0.22),
frameMaterial
);
floor.position.y = -2.34;
floor.receiveShadow = true;
floor.castShadow = true;
group.add(floor);
const frontAccent = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.12, 0.035, 0.035),
accentMaterial
);
frontAccent.position.set(0, -2.255, depth / 2 + 0.07);
group.add(frontAccent);
const backPanel = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
glassMaterial
);
backPanel.position.set(0, -0.03, -depth / 2);
group.add(backPanel);
for (const side of [-1, 1]) {
const sidePanel = new THREE.Mesh(
new THREE.PlaneGeometry(depth, height),
glassMaterial
);
sidePanel.position.set((side * width) / 2, -0.03, 0);
sidePanel.rotation.y = Math.PI / 2;
group.add(sidePanel);
const rearPost = new THREE.Mesh(
new THREE.BoxGeometry(0.075, height, 0.075),
frameMaterial
);
rearPost.position.set(
(side * width) / 2,
-0.03,
-depth / 2
);
rearPost.castShadow = true;
group.add(rearPost);
const lowerSideRail = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.075, depth),
frameMaterial
);
lowerSideRail.position.set(
(side * width) / 2,
-2.255,
0
);
group.add(lowerSideRail);
const upperSideRail = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.055, depth),
frameMaterial
);
upperSideRail.position.set(
(side * width) / 2,
height / 2 - 0.03,
0
);
group.add(upperSideRail);
// Short front-corner stubs emphasize that the front wall is cut away.
const frontStub = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.43, 0.075),
frameMaterial
);
frontStub.position.set(
(side * width) / 2,
-2.02,
depth / 2
);
group.add(frontStub);
}
const topRearRail = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.075, 0.075),
frameMaterial
);
topRearRail.position.set(0, height / 2 - 0.03, -depth / 2);
group.add(topRearRail);
const grid = new THREE.GridHelper(width - 0.12, 16, accentHex, 0x36566a);
grid.position.y = -2.255;
grid.material.transparent = true;
grid.material.opacity = 0.15;
group.add(grid);
// Dashed outline indicates the removed front face of the cutaway.
const cutGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-width / 2, -2.255, depth / 2),
new THREE.Vector3(width / 2, -2.255, depth / 2),
new THREE.Vector3(width / 2, height / 2 - 0.03, depth / 2),
new THREE.Vector3(-width / 2, height / 2 - 0.03, depth / 2)
]);
const cutMaterial = new THREE.LineDashedMaterial({
color: accentHex,
transparent: true,
opacity: 0.3,
dashSize: 0.12,
gapSize: 0.09,
depthWrite: false
});
const cutLine = new THREE.LineLoop(cutGeometry, cutMaterial);
cutLine.computeLineDistances();
group.add(cutLine);
return group;
}
// -------------------------------------------------------------------------
// Lightweight bead-and-constraint model
//
// This is an explanatory animation, not a molecular-dynamics calculation.
// Both models use the same bead count, scale, constraint solver, and thermal-
// like agitation. The network differs by permanent inter-chain constraints.
// -------------------------------------------------------------------------
class PolymerSimulation {
constructor(crosslinked) {
this.crosslinked = crosslinked;
this.chainCount = 5;
this.segmentsPerChain = 15;
this.time = 0;
this.particles = [];
this.constraints = [];
this.crossConstraints = [];
this.bondConstraints = [];
this.anchorRods = [];
this.bounds = {
minX: -3.03,
maxX: 3.03,
minY: -2.05,
maxY: 1.92,
minZ: -1.22,
maxZ: 1.22
};
this.initializeParticles();
this.initializeConstraints();
this.initialPositions = this.particles.map((p) => p.pos.clone());
}
initializeParticles() {
let id = 0;
for (let chain = 0; chain < this.chainCount; chain++) {
const baseY = -1.48 + chain * 0.70;
for (let j = 0; j < this.segmentsPerChain; j++) {
const u = j / (this.segmentsPerChain - 1);
const pos = new THREE.Vector3(
-2.72 + 5.44 * u,
baseY +
0.16 * Math.sin(u * Math.PI * 2.3 + chain * 0.8) +
0.06 * Math.sin(u * Math.PI * 6.0 - chain),
0.28 * Math.sin(u * Math.PI * 3.1 + chain * 0.65) +
0.11 * Math.cos(u * Math.PI * 4.7 - chain)
);
this.particles.push({
id: id++,
chain,
index: j,
pos,
prev: pos.clone(),
fixed: false
});
}
}
if (this.crosslinked) {
// Illustrative frame anchors at two boundary nodes.
const leftAnchor = this.particles[0];
const rightAnchor =
this.particles[
(this.chainCount - 1) * this.segmentsPerChain +
this.segmentsPerChain - 1
];
leftAnchor.pos.set(-3.02, -1.48, 0);
leftAnchor.fixed = true;
rightAnchor.pos.set(3.02, 1.32, 0);
rightAnchor.fixed = true;
this.anchorRods.push(
{
particle: leftAnchor.id,
target: new THREE.Vector3(-3.30, -1.48, -1.63)
},
{
particle: rightAnchor.id,
target: new THREE.Vector3(3.30, 1.32, -1.63)
}
);
}
}
initializeConstraints() {
const particleIndex = (chain, j) =>
chain * this.segmentsPerChain + j;
const addConstraint = (a, b, kind, stiffness, rest = null) => {
const pa = this.particles[a];
const pb = this.particles[b];
const constraint = {
a,
b,
kind,
stiffness,
rest:
rest ??
pa.pos.distanceTo(pb.pos)
};
this.constraints.push(constraint);
if (kind === "cross") {
this.crossConstraints.push(constraint);
} else if (kind === "bond") {
this.bondConstraints.push(constraint);
}
};
// Chain bonds and weak bending resistance.
for (let chain = 0; chain < this.chainCount; chain++) {
for (let j = 0; j < this.segmentsPerChain - 1; j++) {
addConstraint(
particleIndex(chain, j),
particleIndex(chain, j + 1),
"bond",
0.98
);
}
for (let j = 0; j < this.segmentsPerChain - 2; j++) {
const a = particleIndex(chain, j);
const b = particleIndex(chain, j + 2);
const rest =
this.particles[a].pos.distanceTo(this.particles[b].pos) *
0.985;
addConstraint(
a,
b,
"bend",
this.crosslinked ? 0.10 : 0.055,
rest
);
}
}
if (!this.crosslinked) return;
// Explicit permanent bridges between neighboring and non-neighboring
// strands. Together these make one connected network.
const bridges = [
[0, 1, [2, 7, 12]],
[1, 2, [4, 9]],
[2, 3, [1, 6, 11]],
[3, 4, [3, 8, 13]],
[0, 2, [9]],
[1, 3, [7]],
[2, 4, [5]]
];
for (const [chainA, chainB, indices] of bridges) {
for (const j of indices) {
const a = particleIndex(chainA, j);
const b = particleIndex(chainB, j);
const rest =
this.particles[a].pos.distanceTo(this.particles[b].pos) *
0.98;
addConstraint(a, b, "cross", 0.88, rest);
}
}
}
reset() {
this.time = 0;
this.particles.forEach((particle, i) => {
particle.pos.copy(this.initialPositions[i]);
particle.prev.copy(particle.pos);
});
}
step(dt) {
this.time += dt;
const damping = this.crosslinked ? 0.974 : 0.979;
const dt2 = dt * dt;
// Motion-like driving field. The linear model receives additional
// chain-scale drift so independent strands can visibly reorganize.
for (const p of this.particles) {
if (p.fixed) {
p.prev.copy(p.pos);
continue;
}
const t = this.time;
const x = p.pos.x;
const y = p.pos.y;
const z = p.pos.z;
let ax =
9.0 * Math.sin(y * 2.1 + t * 0.77 + p.chain * 0.13) +
3.5 * Math.cos(z * 2.6 - t * 0.48);
let ay =
5.0 * Math.cos(x * 1.9 - t * 0.61) +
3.0 * Math.sin(z * 2.8 + t * 0.39);
let az =
10.0 * Math.sin(x * 1.55 + t * 0.69 + p.chain * 0.09) +
4.0 * Math.cos(y * 2.4 + t * 0.43);
if (!this.crosslinked) {
ax +=
8.0 * Math.sin(t * 0.48 + p.chain * 1.77) +
2.0 * Math.cos(t * 0.91 + p.chain);
ay += 2.5 * Math.sin(t * 0.53 + p.chain * 0.7);
az +=
12.0 * Math.cos(t * 0.41 + p.chain * 0.93) +
3.0 * Math.sin(t * 0.83 + p.chain * 1.2);
} else {
// The network keeps local agitation but lacks independent
// chain-scale translation.
ax *= 0.52;
ay *= 0.48;
az *= 0.50;
}
const vx = (p.pos.x - p.prev.x) * damping;
const vy = (p.pos.y - p.prev.y) * damping;
const vz = (p.pos.z - p.prev.z) * damping;
p.prev.copy(p.pos);
p.pos.x += vx + ax * dt2;
p.pos.y += vy + ay * dt2;
p.pos.z += vz + az * dt2;
}
// Position-based distance constraints.
const iterations = 6;
for (let iteration = 0; iteration < iterations; iteration++) {
for (const constraint of this.constraints) {
const a = this.particles[constraint.a];
const b = this.particles[constraint.b];
let dx = b.pos.x - a.pos.x;
let dy = b.pos.y - a.pos.y;
let dz = b.pos.z - a.pos.z;
let distance = Math.hypot(dx, dy, dz);
if (distance < 0.000001) {
distance = 0.000001;
dx = 0.000001;
}
const error = (distance - constraint.rest) / distance;
const correction = error * 0.5 * constraint.stiffness;
const weightA = a.fixed ? 0 : 1;
const weightB = b.fixed ? 0 : 1;
const totalWeight = weightA + weightB;
if (totalWeight === 0) continue;
const factor = correction / totalWeight;
if (weightA) {
a.pos.x += dx * factor * weightA;
a.pos.y += dy * factor * weightA;
a.pos.z += dz * factor * weightA;
}
if (weightB) {
b.pos.x -= dx * factor * weightB;
b.pos.y -= dy * factor * weightB;
b.pos.z -= dz * factor * weightB;
}
}
this.resolveParticleOverlaps();
this.applyBoundaries();
}
}
resolveParticleOverlaps() {
const minimumDistance = 0.225;
const minimumDistanceSquared =
minimumDistance * minimumDistance;
for (let i = 0; i < this.particles.length; i++) {
const a = this.particles[i];
for (let j = i + 1; j < this.particles.length; j++) {
const b = this.particles[j];
// Neighboring beads are governed by bond constraints.
if (a.chain === b.chain) continue;
let dx = b.pos.x - a.pos.x;
let dy = b.pos.y - a.pos.y;
let dz = b.pos.z - a.pos.z;
const distanceSquared = dx * dx + dy * dy + dz * dz;
if (distanceSquared >= minimumDistanceSquared) continue;
let distance = Math.sqrt(Math.max(distanceSquared, 0.000001));
const correction = (minimumDistance - distance) / distance * 0.5;
const weightA = a.fixed ? 0 : 1;
const weightB = b.fixed ? 0 : 1;
const totalWeight = weightA + weightB;
if (!totalWeight) continue;
dx *= correction / totalWeight;
dy *= correction / totalWeight;
dz *= correction / totalWeight;
if (weightA) {
a.pos.x -= dx * weightA;
a.pos.y -= dy * weightA;
a.pos.z -= dz * weightA;
}
if (weightB) {
b.pos.x += dx * weightB;
b.pos.y += dy * weightB;
b.pos.z += dz * weightB;
}
}
}
}
applyBoundaries() {
const b = this.bounds;
for (const p of this.particles) {
if (p.fixed) continue;
if (p.pos.x < b.minX) {
p.pos.x = b.minX;
p.prev.x = p.pos.x + (p.pos.x - p.prev.x) * 0.5;
} else if (p.pos.x > b.maxX) {
p.pos.x = b.maxX;
p.prev.x = p.pos.x + (p.pos.x - p.prev.x) * 0.5;
}
if (p.pos.y < b.minY) {
p.pos.y = b.minY;
p.prev.y = p.pos.y + (p.pos.y - p.prev.y) * 0.5;
} else if (p.pos.y > b.maxY) {
p.pos.y = b.maxY;
p.prev.y = p.pos.y + (p.pos.y - p.prev.y) * 0.5;
}
if (p.pos.z < b.minZ) {
p.pos.z = b.minZ;
p.prev.z = p.pos.z + (p.pos.z - p.prev.z) * 0.5;
} else if (p.pos.z > b.maxZ) {
p.pos.z = b.maxZ;
p.prev.z = p.pos.z + (p.pos.z - p.prev.z) * 0.5;
}
}
}
}
// -------------------------------------------------------------------------
// Polymer rendering
// -------------------------------------------------------------------------
function createPolymerModel({
crosslinked,
chamberAccent,
beadColor,
bondColor,
title,
subtitle
}) {
const group = new THREE.Group();
const simulation = new PolymerSimulation(crosslinked);
group.add(buildChamber(chamberAccent));
const beadMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.26,
metalness: 0.08,
emissive: crosslinked ? 0x101b45 : 0x073849,
emissiveIntensity: 0.48
});
const bondMaterial = new THREE.MeshStandardMaterial({
color: bondColor,
roughness: 0.42,
metalness: 0.18,
emissive: crosslinked ? 0x101c3e : 0x0a3442,
emissiveIntensity: 0.45
});
const crossMaterial = new THREE.MeshStandardMaterial({
color: 0xffc65c,
roughness: 0.3,
metalness: 0.38,
emissive: 0xff741e,
emissiveIntensity: 0.72
});
const anchorMaterial = new THREE.MeshStandardMaterial({
color: 0xff68aa,
roughness: 0.3,
metalness: 0.25,
emissive: 0xb51f68,
emissiveIntensity: 0.72
});
const beadMesh = new THREE.InstancedMesh(
new THREE.SphereGeometry(0.112, 16, 12),
beadMaterial,
simulation.particles.length
);
beadMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
beadMesh.castShadow = true;
beadMesh.receiveShadow = true;
beadMesh.frustumCulled = false;
group.add(beadMesh);
const normalColor = new THREE.Color(beadColor);
const brightColor = new THREE.Color(crosslinked ? 0xc2d5ff : 0xd3f8ff);
const anchorColor = new THREE.Color(0xff68aa);
simulation.particles.forEach((particle, i) => {
let color = normalColor;
if (particle.fixed) {
color = anchorColor;
} else if (
particle.index ===
Math.floor(simulation.segmentsPerChain / 2)
) {
color = brightColor;
}
beadMesh.setColorAt(i, color);
});
beadMesh.instanceColor.needsUpdate = true;
const bondMesh = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.037, 0.037, 1, 8),
bondMaterial,
simulation.bondConstraints.length
);
bondMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
bondMesh.frustumCulled = false;
group.add(bondMesh);
const crossMesh = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.058, 0.058, 1, 10),
crossMaterial,
simulation.crossConstraints.length
);
crossMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
crossMesh.frustumCulled = false;
crossMesh.castShadow = true;
group.add(crossMesh);
const crossEndpoints = new Set();
for (const constraint of simulation.crossConstraints) {
crossEndpoints.add(constraint.a);
crossEndpoints.add(constraint.b);
}
const haloMaterial = new THREE.MeshBasicMaterial({
color: 0xffb63e,
transparent: true,
opacity: 0.23,
depthWrite: false
});
const haloMesh = new THREE.InstancedMesh(
new THREE.SphereGeometry(0.17, 12, 8),
haloMaterial,
crossEndpoints.size
);
haloMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
haloMesh.frustumCulled = false;
haloMesh.renderOrder = 4;
group.add(haloMesh);
const anchorMeshes = simulation.anchorRods.map(() => {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.052, 0.052, 1, 10),
anchorMaterial
);
mesh.castShadow = true;
group.add(mesh);
return mesh;
});
const label = makeLabelSprite(title, subtitle, chamberAccent);
label.position.set(0, 2.55, -0.95);
group.add(label);
const identityQuaternion = new THREE.Quaternion();
const unitScale = new THREE.Vector3(1, 1, 1);
const anchorScale = new THREE.Vector3(1.35, 1.35, 1.35);
function updateVisuals() {
simulation.particles.forEach((particle, i) => {
setInstanceMatrix(
beadMesh,
i,
particle.pos,
identityQuaternion,
particle.fixed ? anchorScale : unitScale
);
});
beadMesh.instanceMatrix.needsUpdate = true;
simulation.bondConstraints.forEach((constraint, i) => {
positionRod(
bondMesh,
i,
simulation.particles[constraint.a].pos,
simulation.particles[constraint.b].pos
);
});
bondMesh.instanceMatrix.needsUpdate = true;
simulation.crossConstraints.forEach((constraint, i) => {
positionRod(
crossMesh,
i,
simulation.particles[constraint.a].pos,
simulation.particles[constraint.b].pos
);
});
crossMesh.instanceMatrix.needsUpdate = true;
let haloIndex = 0;
for (const endpoint of crossEndpoints) {
setInstanceMatrix(
haloMesh,
haloIndex++,
simulation.particles[endpoint].pos,
identityQuaternion,
unitScale
);
}
haloMesh.instanceMatrix.needsUpdate = true;
simulation.anchorRods.forEach((anchor, i) => {
positionRod(
anchorMeshes[i],
0,
simulation.particles[anchor.particle].pos,
anchor.target
);
});
}
updateVisuals();
return {
group,
simulation,
updateVisuals
};
}
const linearModel = createPolymerModel({
crosslinked: false,
chamberAccent: "#55dcff",
beadColor: "#50d8ff",
bondColor: "#a9e8f7",
title: "LINEAR CHAINS",
subtitle: "independent strands • rearrangement possible"
});
const networkModel = createPolymerModel({
crosslinked: true,
chamberAccent: "#9b8cff",
beadColor: "#789dff",
bondColor: "#b8caff",
title: "CROSS-LINKED NETWORK",
subtitle: "permanent junctions • constrained network"
});
scene.add(linearModel.group, networkModel.group);
// -------------------------------------------------------------------------
// Responsive layout
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, -0.05, 0);
const cameraState = {
yaw: 0.075,
pitch: 0.105,
radius: 17.6
};
function isPortraitLayout() {
return innerWidth / innerHeight < 0.85;
}
function layoutScene() {
const portrait = isPortraitLayout();
if (portrait) {
linearModel.group.position.set(0, 3.05, 0);
networkModel.group.position.set(0, -3.05, 0);
cameraTarget.set(0, 0, 0);
cameraState.radius = 22.5;
} else {
linearModel.group.position.set(-4.15, 0, 0);
networkModel.group.position.set(4.15, 0, 0);
cameraTarget.set(0, -0.05, 0);
cameraState.radius = 17.6;
}
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
applyCamera();
}
function applyCamera() {
const { yaw, pitch, radius } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(yaw) * Math.cos(pitch),
cameraTarget.y + radius * Math.sin(pitch),
cameraTarget.z + radius * Math.cos(yaw) * Math.cos(pitch)
);
camera.lookAt(cameraTarget);
}
layoutScene();
// -------------------------------------------------------------------------
// Custom camera controls: orbit, zoom, keyboard, and double-click reset
// -------------------------------------------------------------------------
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch += deltaY * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch,
-0.18,
0.85
);
previousX = event.clientX;
previousY = event.clientY;
applyCamera();
});
function stopDragging(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (
event &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.009,
11,
31
);
applyCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraState.yaw = 0.075;
cameraState.pitch = 0.105;
cameraState.radius = isPortraitLayout() ? 22.5 : 17.6;
applyCamera();
});
addEventListener("keydown", (event) => {
const key = event.key.toLowerCase();
if (key === "arrowleft") cameraState.yaw += 0.08;
else if (key === "arrowright") cameraState.yaw -= 0.08;
else if (key === "arrowup") cameraState.pitch += 0.05;
else if (key === "arrowdown") cameraState.pitch -= 0.05;
else if (key === "+" || key === "=") cameraState.radius -= 0.7;
else if (key === "-") cameraState.radius += 0.7;
else return;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch,
-0.18,
0.85
);
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius,
11,
31
);
applyCamera();
});
// -------------------------------------------------------------------------
// UI controls
// -------------------------------------------------------------------------
const pauseButton = document.getElementById("pauseButton");
const resetMotionButton = document.getElementById("resetMotionButton");
const resetViewButton = document.getElementById("resetViewButton");
const prefersReducedMotion = matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
let playing = !prefersReducedMotion;
function updatePauseButton() {
pauseButton.textContent = playing
? "Ⅱ Pause motion"
: "▶ Resume motion";
pauseButton.setAttribute("aria-pressed", String(!playing));
}
pauseButton.addEventListener("click", () => {
playing = !playing;
updatePauseButton();
});
resetMotionButton.addEventListener("click", () => {
linearModel.simulation.reset();
networkModel.simulation.reset();
linearModel.updateVisuals();
networkModel.updateVisuals();
});
resetViewButton.addEventListener("click", () => {
cameraState.yaw = 0.075;
cameraState.pitch = 0.105;
cameraState.radius = isPortraitLayout() ? 22.5 : 17.6;
applyCamera();
});
updatePauseButton();
addEventListener("resize", layoutScene);
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const fixedTimeStep = 1 / 60;
let accumulator = 0;
let previousTime = performance.now();
let firstFrame = true;
function animate(now) {
requestAnimationFrame(animate);
const frameTime = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing) {
accumulator += frameTime;
let steps = 0;
while (accumulator >= fixedTimeStep && steps < 3) {
linearModel.simulation.step(fixedTimeStep);
networkModel.simulation.step(fixedTimeStep);
accumulator -= fixedTimeStep;
steps++;
}
}
linearModel.updateVisuals();
networkModel.updateVisuals();
renderer.render(scene, camera);
if (firstFrame) {
firstFrame = false;
document.getElementById("loading").classList.add("hidden");
}
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```