Prompt specification
Build or customize the Three.js 3D scene "Defect-and-slip exploration model" 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: Defect-and-slip exploration model
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/defect-and-slip-exploration-model-x1960
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts a voxel lattice with an adjustable schematic dislocation. Start with regular rows of cubic markers and introduce a visible extra half-plane that ends within the lattice. A step control moves the defect through the model according to a prescribed geometric rule, leaving a measurable offset behind it. Keep neighboring rows and the original boundary markers visible so the displacement can be followed rather than hidden by a camera change. Include a defect-free comparison at the same scale. Treat the marker movements as a teaching model of slip, with no claim that the animation calculates atomistic stress or material strength.
Working Three.js Starter (defect-and-slip-exploration-model-x1960):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Dislocation Teaching Model</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: rgba(15, 23, 42, 0.82);
--border: rgba(148, 163, 184, 0.22);
--text: #e5edf8;
--muted: #94a3b8;
--cyan: #67e8f9;
--amber: #fbbf24;
--slate: #cbd5e1;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow-x: hidden;
}
button,
input {
font: inherit;
}
button {
border: 1px solid var(--border);
border-radius: 9px;
padding: 0.65rem 0.85rem;
color: var(--text);
background: #111b2d;
cursor: pointer;
transition:
background 120ms ease,
border-color 120ms ease,
transform 120ms ease;
}
button:hover:not(:disabled) {
background: #18243a;
border-color: rgba(148, 163, 184, 0.48);
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
button:disabled {
opacity: 0.38;
cursor: default;
}
button.primary {
color: #07111d;
background: var(--cyan);
border-color: var(--cyan);
font-weight: 750;
}
button.primary:hover:not(:disabled) {
background: #a5f3fc;
border-color: #a5f3fc;
}
.app {
min-height: 100dvh;
display: grid;
grid-template-rows: auto auto minmax(430px, 1fr) auto;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.9rem 1.2rem;
border-bottom: 1px solid var(--border);
background: rgba(7, 11, 20, 0.96);
}
.title-block {
min-width: 0;
}
.kicker {
margin: 0 0 0.2rem;
color: var(--cyan);
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.05rem, 2.4vw, 1.45rem);
letter-spacing: -0.02em;
}
.header-note {
max-width: 33rem;
margin: 0;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.45;
text-align: right;
}
.toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.7rem 1rem;
padding: 0.75rem 1.2rem;
border-bottom: 1px solid var(--border);
background: #0b1220;
}
.button-group {
display: flex;
gap: 0.5rem;
}
.slider-control {
display: grid;
grid-template-columns: auto minmax(110px, 180px);
align-items: center;
gap: 0.65rem;
color: var(--muted);
font-size: 0.78rem;
}
.slider-control input {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.readouts {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
margin-left: auto;
}
.readout {
min-width: 7.6rem;
padding: 0.45rem 0.65rem;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(15, 23, 42, 0.7);
}
.readout span {
display: block;
color: var(--muted);
font-size: 0.64rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.readout strong {
display: block;
margin-top: 0.12rem;
color: var(--text);
font-size: 0.88rem;
font-variant-numeric: tabular-nums;
}
#offsetValue {
color: var(--cyan);
}
.stage {
position: relative;
min-height: 0;
display: grid;
grid-template-columns: 1.15fr 1fr;
overflow: hidden;
background: #080d18;
}
.stage canvas {
position: absolute;
inset: 0;
z-index: 0;
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
.stage canvas.dragging {
cursor: grabbing;
}
.panel {
position: relative;
z-index: 1;
min-width: 0;
min-height: 0;
overflow: hidden;
pointer-events: none;
}
#defectPanel {
border-right: 1px solid var(--border);
}
.panel-heading {
position: absolute;
top: 0;
left: 0;
z-index: 3;
max-width: min(31rem, calc(100% - 2rem));
padding: 1rem 1.1rem 1.15rem;
}
.panel-kicker {
margin: 0 0 0.32rem;
color: var(--cyan);
font-size: 0.64rem;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: clamp(1rem, 2.2vw, 1.3rem);
letter-spacing: -0.02em;
}
.panel p {
max-width: 31rem;
margin: 0.42rem 0 0;
color: var(--muted);
font-size: 0.72rem;
line-height: 1.5;
}
.legend {
position: absolute;
left: 1rem;
bottom: 1rem;
z-index: 3;
display: flex;
flex-wrap: wrap;
gap: 0.45rem 0.8rem;
max-width: calc(100% - 2rem);
padding: 0.65rem 0.75rem;
border: 1px solid var(--border);
border-radius: 9px;
background: var(--panel);
backdrop-filter: blur(8px);
color: var(--muted);
font-size: 0.67rem;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 0.38rem;
}
.swatch {
width: 0.68rem;
height: 0.68rem;
border-radius: 2px;
background: var(--slate);
box-shadow: 0 0 8px rgba(203, 213, 225, 0.12);
}
.swatch.gold {
background: var(--amber);
}
.swatch.ghost {
border: 1px solid var(--cyan);
background: transparent;
}
.swatch.measure {
height: 2px;
background: var(--cyan);
}
.scale {
position: absolute;
right: 1rem;
bottom: 1rem;
z-index: 3;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 0.25rem;
color: var(--muted);
font-size: 0.64rem;
}
.scale-line {
width: 60px;
height: 7px;
border-right: 1px solid var(--cyan);
border-bottom: 1px solid var(--cyan);
border-left: 1px solid var(--cyan);
}
.world-label {
position: absolute;
z-index: 4;
transform: translate(-50%, -50%);
padding: 0.24rem 0.42rem;
border: 1px solid currentColor;
border-radius: 5px;
background: rgba(7, 11, 20, 0.88);
font-size: 0.65rem;
font-weight: 750;
white-space: nowrap;
}
#coreLabel {
color: var(--amber);
}
#measureLabel {
color: var(--cyan);
}
.footer {
display: grid;
grid-template-columns: 1.15fr 1fr;
gap: 1rem;
padding: 0.75rem 1.2rem 0.9rem;
border-top: 1px solid var(--border);
background: #080d18;
color: var(--muted);
font-size: 0.7rem;
line-height: 1.45;
}
.footer p {
margin: 0;
}
.footer strong {
color: var(--text);
}
.disclaimer {
padding-left: 1rem;
border-left: 1px solid var(--border);
}
@media (max-width: 820px) {
.app {
grid-template-rows: auto auto minmax(650px, 1fr) auto;
}
.header {
align-items: flex-start;
flex-direction: column;
}
.header-note {
max-width: none;
text-align: left;
}
.readouts {
width: 100%;
margin-left: 0;
}
.readout {
flex: 1 1 8rem;
}
.stage {
grid-template-columns: 1fr;
grid-template-rows: 1fr 1fr;
}
#defectPanel {
border-right: 0;
border-bottom: 1px solid var(--border);
}
.footer {
grid-template-columns: 1fr;
}
.disclaimer {
padding-top: 0.75rem;
padding-left: 0;
border-top: 1px solid var(--border);
border-left: 0;
}
}
@media (max-width: 520px) {
.toolbar {
align-items: stretch;
}
.button-group {
width: 100%;
}
.button-group button {
flex: 1;
}
.slider-control {
grid-template-columns: 1fr;
gap: 0.25rem;
}
.panel-heading {
padding: 0.75rem;
}
.panel p {
max-width: 25rem;
font-size: 0.67rem;
}
.legend {
left: 0.65rem;
bottom: 0.65rem;
padding: 0.5rem;
}
.scale {
right: 0.65rem;
bottom: 0.65rem;
}
}
</style>
</head>
<body>
<main class="app">
<header class="header">
<div class="title-block">
<p class="kicker">Voxel geometry laboratory</p>
<h1>Schematic edge-dislocation glide</h1>
</div>
<p class="header-note">
Drag to orbit, use the wheel to zoom, and advance the defect with the
step control. Stepping never changes the camera.
</p>
</header>
<section class="toolbar" aria-label="Dislocation controls">
<div class="button-group">
<button id="stepButton" class="primary" type="button">
Advance one step →
</button>
<button id="resetStepsButton" type="button">
Reset displacement
</button>
</div>
<label class="slider-control" for="stepSlider">
<span>Glide position</span>
<input
id="stepSlider"
type="range"
min="0"
max="5"
step="1"
value="0"
aria-label="Dislocation glide position in steps"
/>
</label>
<div class="readouts">
<div class="readout">
<span>Core position</span>
<strong id="stepValue">0 / 5</strong>
</div>
<div class="readout">
<span>Measured offset b/a</span>
<strong id="offsetValue">0.00</strong>
</div>
</div>
<button id="resetViewButton" type="button">
Reset camera
</button>
</section>
<section id="stage" class="stage" aria-label="Interactive lattice comparison">
<div id="defectPanel" class="panel">
<div class="panel-heading">
<p class="panel-kicker">01 / Schematic defect</p>
<h2>Dislocated lattice</h2>
<p>
The amber extra half-plane terminates at the core on the slip
plane. Cyan wireframes preserve every original marker position.
</p>
</div>
<div class="legend">
<span class="legend-item">
<span class="swatch"></span> lattice marker
</span>
<span class="legend-item">
<span class="swatch gold"></span> extra half-plane
</span>
<span class="legend-item">
<span class="swatch ghost"></span> original position
</span>
<span class="legend-item">
<span class="swatch measure"></span> offset
</span>
</div>
<div class="scale">
<span class="scale-line"></span>
<span>1 lattice site, a</span>
</div>
<div id="coreLabel" class="world-label">core</div>
<div id="measureLabel" class="world-label">b = 0.00 a</div>
</div>
<div id="referencePanel" class="panel">
<div class="panel-heading">
<p class="panel-kicker">02 / Matched control</p>
<h2>Defect-free reference</h2>
<p>
The same lattice without an extra half-plane, shown at the same
orthographic scale, zoom, and camera orientation.
</p>
</div>
<div class="legend">
<span class="legend-item">
<span class="swatch"></span> undisturbed lattice marker
</span>
<span class="legend-item">
<span class="swatch measure"></span> slip-plane guide
</span>
</div>
<div class="scale">
<span class="scale-line"></span>
<span>1 lattice site, a</span>
</div>
</div>
</section>
<footer class="footer">
<p>
<strong>Prescribed geometric rule:</strong> one step advances the core
one lattice site and translates the upper-right marker block by one
additional lattice spacing. The lower rows, neighboring rows, and
original boundary outlines remain visible for comparison.
</p>
<p class="disclaimer">
<strong>Teaching model only.</strong> This animation illustrates a
schematic topology and marker motion associated with slip. It does not
calculate atomistic stress, forces, energy, yield strength, or
material strength.
</p>
</footer>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and scene constants
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const defectPanel = document.getElementById("defectPanel");
const referencePanel = document.getElementById("referencePanel");
const stepButton = document.getElementById("stepButton");
const resetStepsButton = document.getElementById("resetStepsButton");
const resetViewButton = document.getElementById("resetViewButton");
const stepSlider = document.getElementById("stepSlider");
const stepValue = document.getElementById("stepValue");
const offsetValue = document.getElementById("offsetValue");
const coreLabel = document.getElementById("coreLabel");
const measureLabel = document.getElementById("measureLabel");
const defectScaleLine = defectPanel.querySelector(".scale-line");
const referenceScaleLine = referencePanel.querySelector(".scale-line");
const COLS = 12;
const ROWS = 9;
const SPACING = 0.86;
const CUBE_SIZE = 0.58;
const GOLD_SIZE = 0.56;
const CENTER_ROW = Math.floor(ROWS / 2);
const INITIAL_CUT = 3;
const MAX_STEPS = 5;
const initialCoreX =
-((COLS - 1) * SPACING) / 2 +
INITIAL_CUT * SPACING +
SPACING / 2;
const xPositions = Array.from(
{ length: COLS },
(_, i) => -((COLS - 1) * SPACING) / 2 + i * SPACING
);
const yPositions = Array.from(
{ length: ROWS },
(_, j) => -((ROWS - 1) * SPACING) / 2 + j * SPACING
);
// -------------------------------------------------------------------------
// Renderer
// -------------------------------------------------------------------------
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.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.prepend(renderer.domElement);
const defectScene = new THREE.Scene();
const referenceScene = new THREE.Scene();
defectScene.background = new THREE.Color(0x080d18);
referenceScene.background = new THREE.Color(0x080d18);
const atomGeometry = new THREE.BoxGeometry(
CUBE_SIZE,
CUBE_SIZE,
CUBE_SIZE
);
const goldGeometry = new THREE.BoxGeometry(
GOLD_SIZE,
GOLD_SIZE,
GOLD_SIZE
);
const atomMaterial = new THREE.MeshStandardMaterial({
color: 0xcbd5e1,
roughness: 0.36,
metalness: 0.12
});
const referenceAtomMaterial = new THREE.MeshStandardMaterial({
color: 0xb8c4d4,
roughness: 0.4,
metalness: 0.1
});
const goldMaterial = new THREE.MeshStandardMaterial({
color: 0xfbbf24,
roughness: 0.3,
metalness: 0.18,
emissive: 0x5a3500,
emissiveIntensity: 0.2
});
// -------------------------------------------------------------------------
// Scene construction helpers
// -------------------------------------------------------------------------
function addLighting(scene, targetX) {
const hemisphere = new THREE.HemisphereLight(
0xcfe8ff,
0x111827,
1.8
);
scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xffffff, 3.0);
key.position.set(7, 9, 13);
key.target.position.set(targetX, 0, 0);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -14;
key.shadow.camera.right = 14;
key.shadow.camera.top = 10;
key.shadow.camera.bottom = -10;
key.shadow.camera.near = 1;
key.shadow.camera.far = 45;
key.shadow.bias = -0.0005;
scene.add(key, key.target);
const rim = new THREE.DirectionalLight(0x67e8f9, 1.1);
rim.position.set(-8, -2, 8);
rim.target.position.set(targetX, 0, 0);
scene.add(rim, rim.target);
}
function addBackplate(scene, centerX) {
const plate = new THREE.Mesh(
new THREE.PlaneGeometry(22, 10),
new THREE.MeshStandardMaterial({
color: 0x0e1728,
roughness: 0.94,
metalness: 0.02,
side: THREE.DoubleSide
})
);
plate.position.set(centerX, 0, -0.44);
plate.receiveShadow = true;
scene.add(plate);
}
function addSlipGuide(scene, xMin, xMax) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(xMin, 0, -0.36),
new THREE.Vector3(xMax, 0, -0.36)
]);
const material = new THREE.LineDashedMaterial({
color: 0x718096,
dashSize: 0.18,
gapSize: 0.12,
transparent: true,
opacity: 0.65,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
scene.add(line);
}
function createGhostGeometry(positions, boundaryOnly = false) {
const half = CUBE_SIZE * 0.54;
const vertices = [];
const corners = [
[-half, -half, -half],
[ half, -half, -half],
[ half, half, -half],
[-half, half, -half],
[-half, -half, half],
[ half, -half, half],
[ half, half, half],
[-half, half, half]
];
const edges = [
[0, 1], [1, 2], [2, 3], [3, 0],
[4, 5], [5, 6], [6, 7], [7, 4],
[0, 4], [1, 5], [2, 6], [3, 7]
];
positions.forEach(({ x, y }, index) => {
const i = index % COLS;
const j = Math.floor(index / COLS);
const isBoundary =
i === 0 ||
i === COLS - 1 ||
j === 0 ||
j === ROWS - 1;
if (boundaryOnly && !isBoundary) return;
for (const [a, b] of edges) {
const ca = corners[a];
const cb = corners[b];
vertices.push(
x + ca[0], y + ca[1], ca[2],
x + cb[0], y + cb[1], cb[2]
);
}
});
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(vertices, 3)
);
return geometry;
}
function createGhosts(scene, positions) {
const allGhosts = new THREE.LineSegments(
createGhostGeometry(positions, false),
new THREE.LineBasicMaterial({
color: 0x67e8f9,
transparent: true,
opacity: 0.15,
depthWrite: false
})
);
const boundaryGhosts = new THREE.LineSegments(
createGhostGeometry(positions, true),
new THREE.LineBasicMaterial({
color: 0x67e8f9,
transparent: true,
opacity: 0.46,
depthWrite: false
})
);
scene.add(allGhosts, boundaryGhosts);
}
function createAtoms(scene, material, count) {
const mesh = new THREE.InstancedMesh(
atomGeometry,
material,
count
);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.castShadow = true;
mesh.receiveShadow = true;
// Positions change during the animation, so avoid stale bounds.
mesh.frustumCulled = false;
scene.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Defective lattice
// -------------------------------------------------------------------------
addLighting(defectScene, 2);
addBackplate(defectScene, 2);
addSlipGuide(defectScene, -5.35, 5.35);
const allOriginalPositions = [];
for (let j = 0; j < ROWS; j++) {
for (let i = 0; i < COLS; i++) {
allOriginalPositions.push({
x: xPositions[i],
y: yPositions[j]
});
}
}
createGhosts(defectScene, allOriginalPositions);
const defectAtoms = createAtoms(
defectScene,
atomMaterial,
COLS * ROWS
);
const goldCount = ROWS - CENTER_ROW;
const extraHalfPlane = new THREE.InstancedMesh(
goldGeometry,
goldMaterial,
goldCount
);
extraHalfPlane.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
extraHalfPlane.castShadow = true;
extraHalfPlane.frustumCulled = false;
defectScene.add(extraHalfPlane);
// The amber path records the core's travel without moving the camera.
const travelGeometry = new THREE.BufferGeometry();
travelGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(
[
initialCoreX, 0.43, -0.31,
initialCoreX, 0.43, -0.31
],
3
)
);
const travelLine = new THREE.Line(
travelGeometry,
new THREE.LineBasicMaterial({
color: 0xfbbf24,
transparent: true,
opacity: 0.8,
depthTest: false,
depthWrite: false
})
);
travelLine.renderOrder = 8;
defectScene.add(travelLine);
// Cyan measurement caliper: original position to translated position.
const measurementGeometry = new THREE.BufferGeometry();
measurementGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(18), 3)
);
const measurementLine = new THREE.LineSegments(
measurementGeometry,
new THREE.LineBasicMaterial({
color: 0x67e8f9,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
measurementLine.renderOrder = 9;
measurementLine.frustumCulled = false;
defectScene.add(measurementLine);
const dummy = new THREE.Object3D();
function updateDefectModel(stepValueFloat) {
let instance = 0;
for (let j = 0; j < ROWS; j++) {
for (let i = 0; i < COLS; i++) {
let x = xPositions[i];
// Prescribed geometric rule:
// upper-half markers to the right of the original cut translate
// by one additional lattice spacing for every step.
if (j > CENTER_ROW && i > INITIAL_CUT) {
x += stepValueFloat * SPACING;
}
dummy.position.set(x, yPositions[j], 0);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
defectAtoms.setMatrixAt(instance++, dummy.matrix);
}
}
defectAtoms.instanceMatrix.needsUpdate = true;
const coreX = initialCoreX + stepValueFloat * SPACING;
for (let j = CENTER_ROW; j < ROWS; j++) {
dummy.position.set(coreX, yPositions[j], 0.055);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
extraHalfPlane.setMatrixAt(j - CENTER_ROW, dummy.matrix);
}
extraHalfPlane.instanceMatrix.needsUpdate = true;
const travelPositions = travelGeometry.attributes.position.array;
travelPositions[0] = initialCoreX;
travelPositions[1] = 0.43;
travelPositions[2] = -0.31;
travelPositions[3] = coreX;
travelPositions[4] = 0.43;
travelPositions[5] = -0.31;
travelGeometry.attributes.position.needsUpdate = true;
const measuredIndex = INITIAL_CUT + 1;
const originalX = xPositions[measuredIndex];
const translatedX = originalX + stepValueFloat * SPACING;
const measureY = yPositions[CENTER_ROW + 1];
const z = 0.52;
const tick = 0.11;
const p = measurementGeometry.attributes.position.array;
p.set([
originalX, measureY, z,
translatedX, measureY, z,
originalX, measureY - tick, z,
originalX, measureY + tick, z,
translatedX, measureY - tick, z,
translatedX, measureY + tick, z
]);
measurementGeometry.attributes.position.needsUpdate = true;
measurementLine.visible = stepValueFloat > 0.02;
}
// -------------------------------------------------------------------------
// Defect-free comparison
// -------------------------------------------------------------------------
addLighting(referenceScene, 0);
addBackplate(referenceScene, 0);
addSlipGuide(referenceScene, -5.35, 5.35);
const referenceAtoms = createAtoms(
referenceScene,
referenceAtomMaterial,
COLS * ROWS
);
{
let instance = 0;
for (let j = 0; j < ROWS; j++) {
for (let i = 0; i < COLS; i++) {
dummy.position.set(xPositions[i], yPositions[j], 0);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
referenceAtoms.setMatrixAt(instance++, dummy.matrix);
}
}
referenceAtoms.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Cameras: direct controls, no addon imports
// -------------------------------------------------------------------------
const mainCamera = new THREE.OrthographicCamera(-8, 8, 6, -6, 0.1, 100);
const referenceCamera = new THREE.OrthographicCamera(
-8,
8,
6,
-6,
0.1,
100
);
const cameraTargets = [
{ camera: mainCamera, target: new THREE.Vector3(2, 0, 0) },
{ camera: referenceCamera, target: new THREE.Vector3(0, 0, 0) }
];
const orbit = {
theta: 0.18,
phi: 0.12,
zoom: 1
};
let viewports = [];
let sharedViewHeight = 12;
function updateCameraTransforms() {
const radius = 30;
for (const { camera, target } of cameraTargets) {
const cosPhi = Math.cos(orbit.phi);
camera.position.set(
target.x + radius * Math.sin(orbit.theta) * cosPhi,
target.y + radius * Math.sin(orbit.phi),
target.z + radius * Math.cos(orbit.theta) * cosPhi
);
camera.up.set(0, 1, 0);
camera.lookAt(target);
camera.zoom = orbit.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
}
function resetCamera() {
orbit.theta = 0.18;
orbit.phi = 0.12;
orbit.zoom = 1;
updateCameraTransforms();
}
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 dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
orbit.theta = THREE.MathUtils.clamp(
orbit.theta - dx * 0.006,
-0.9,
0.9
);
orbit.phi = THREE.MathUtils.clamp(
orbit.phi + dy * 0.005,
-0.55,
0.55
);
});
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();
orbit.zoom = THREE.MathUtils.clamp(
orbit.zoom * Math.exp(-event.deltaY * 0.001),
0.72,
1.55
);
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Responsive split rendering
// -------------------------------------------------------------------------
function resizeRenderer() {
const stageRect = stage.getBoundingClientRect();
const width = Math.max(1, Math.round(stageRect.width));
const height = Math.max(1, Math.round(stageRect.height));
renderer.setSize(width, height, false);
const panels = [defectPanel, referencePanel];
viewports = panels.map((panel) => {
const rect = panel.getBoundingClientRect();
return {
x: Math.round(rect.left - stageRect.left),
y: Math.round(
stageRect.height - (rect.top - stageRect.top) - rect.height
),
width: Math.max(1, Math.round(rect.width)),
height: Math.max(1, Math.round(rect.height)),
aspect: rect.width / Math.max(1, rect.height),
rect
};
});
// The same vertical world extent is used for both scenes, so their
// marker scales remain identical when panel heights are equal.
sharedViewHeight = Math.max(
11.8,
16.5 / viewports[0].aspect,
13.0 / viewports[1].aspect
);
for (const viewport of viewports) {
const halfHeight = sharedViewHeight / 2;
const halfWidth = halfHeight * viewport.aspect;
for (const { camera } of cameraTargets) {
camera.left = -halfWidth;
camera.right = halfWidth;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
}
}
updateCameraTransforms();
updateScaleBars();
}
function updateScaleBars() {
if (!viewports.length) return;
const effectiveWorldHeight = sharedViewHeight / orbit.zoom;
const defectPixels =
(viewports[0].height / effectiveWorldHeight) * SPACING;
const referencePixels =
(viewports[1].height / effectiveWorldHeight) * SPACING;
defectScaleLine.style.width = `${defectPixels}px`;
referenceScaleLine.style.width = `${referencePixels}px`;
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
window.addEventListener("resize", resizeRenderer);
// -------------------------------------------------------------------------
// Step animation and UI
// -------------------------------------------------------------------------
const state = {
displayStep: 0,
targetStep: 0,
animation: null
};
function updateReadouts() {
stepValue.textContent = `${state.targetStep} / ${MAX_STEPS}`;
offsetValue.textContent = `${state.targetStep.toFixed(2)} a`;
stepSlider.value = String(state.targetStep);
stepSlider.setAttribute(
"aria-valuetext",
`${state.targetStep} glide steps`
);
stepButton.disabled = state.targetStep >= MAX_STEPS;
}
function animateTo(target) {
state.targetStep = THREE.MathUtils.clamp(
Math.round(target),
0,
MAX_STEPS
);
state.animation = {
from: state.displayStep,
to: state.targetStep,
start: performance.now(),
duration: Math.abs(state.targetStep - state.displayStep) * 330
};
updateReadouts();
}
stepButton.addEventListener("click", () => {
animateTo(state.targetStep + 1);
});
resetStepsButton.addEventListener("click", () => {
animateTo(0);
});
stepSlider.addEventListener("input", () => {
animateTo(Number(stepSlider.value));
});
resetViewButton.addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (tag === "INPUT" || tag === "BUTTON") return;
if (event.code === "Space") {
event.preventDefault();
animateTo(state.targetStep + 1);
} else if (event.key.toLowerCase() === "r") {
animateTo(0);
}
});
function updateAnimation(now) {
if (!state.animation) return;
const animation = state.animation;
const progress = THREE.MathUtils.clamp(
(now - animation.start) / animation.duration,
0,
1
);
const eased =
progress < 0.5
? 4 * progress * progress * progress
: 1 -
Math.pow(-2 * progress + 2, 3) / 2;
state.displayStep =
animation.from +
(animation.to - animation.from) * eased;
if (progress >= 1) {
state.displayStep = animation.to;
state.animation = null;
}
}
// -------------------------------------------------------------------------
// Projected HTML annotations
// -------------------------------------------------------------------------
const projectedPoint = new THREE.Vector3();
function projectPointToPanel(worldPoint, camera, viewport, element) {
projectedPoint.copy(worldPoint).project(camera);
const x = (projectedPoint.x * 0.5 + 0.5) * viewport.width;
const y = (-projectedPoint.y * 0.5 + 0.5) * viewport.height;
const left = THREE.MathUtils.clamp(x, 28, viewport.width - 28);
const top = THREE.MathUtils.clamp(y, 82, viewport.height - 72);
element.style.left = `${left}px`;
element.style.top = `${top}px`;
}
function updateAnnotations() {
if (!viewports.length) return;
const coreX = initialCoreX + state.displayStep * SPACING;
projectPointToPanel(
new THREE.Vector3(coreX, yPositions[CENTER_ROW] + 0.44, 0.15),
mainCamera,
viewports[0],
coreLabel
);
const originalX = xPositions[INITIAL_CUT + 1];
const translatedX = originalX + state.displayStep * SPACING;
projectPointToPanel(
new THREE.Vector3(
(originalX + translatedX) / 2,
yPositions[CENTER_ROW + 1] + 0.34,
0.55
),
mainCamera,
viewports[0],
measureLabel
);
measureLabel.textContent = `b = ${(state.displayStep).toFixed(2)} a`;
measureLabel.style.visibility =
state.displayStep > 0.02 ? "visible" : "hidden";
}
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
function render(now) {
requestAnimationFrame(render);
updateAnimation(now);
updateDefectModel(state.displayStep);
updateCameraTransforms();
updateScaleBars();
renderer.setScissorTest(true);
renderer.setViewport(
viewports[0].x,
viewports[0].y,
viewports[0].width,
viewports[0].height
);
renderer.setScissor(
viewports[0].x,
viewports[0].y,
viewports[0].width,
viewports[0].height
);
renderer.render(defectScene, mainCamera);
renderer.setViewport(
viewports[1].x,
viewports[1].y,
viewports[1].width,
viewports[1].height
);
renderer.setScissor(
viewports[1].x,
viewports[1].y,
viewports[1].width,
viewports[1].height
);
renderer.render(referenceScene, referenceCamera);
renderer.setScissorTest(false);
updateAnnotations();
}
updateDefectModel(0);
updateReadouts();
resizeRenderer();
requestAnimationFrame(render);
</script>
</body>
</html>
```