Prompt specification
Build or customize the Three.js 3D scene "Spinning top mass profile" 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: Spinning top mass profile
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/spinning-top-mass-profile-x0377
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a spinning top. Display two tops with equal height and differently distributed rims beside vertical axes; cutaway sections reveal where each object's modeled mass is concentrated. Voxel style.
Working Three.js Starter (spinning-top-mass-profile-x0377):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Top — Mass Distribution Study</title>
<style>
:root {
--bg: #071019;
--panel: rgba(10, 20, 30, 0.82);
--line: rgba(173, 211, 230, 0.18);
--text: #e9f4fa;
--muted: #91a8b8;
--cyan: #49e1d0;
--amber: #ffad4d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.brand {
position: fixed;
top: 24px;
left: 26px;
z-index: 10;
pointer-events: none;
}
.eyebrow {
margin-bottom: 7px;
color: #7f9baa;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(20px, 2.5vw, 31px);
font-weight: 650;
letter-spacing: -0.035em;
}
.brand p {
max-width: 460px;
margin: 7px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.study-panel {
left: 24px;
bottom: 24px;
width: min(365px, calc(100vw - 48px));
padding: 17px 18px;
border-radius: 12px;
}
.study-panel h2 {
margin: 0 0 9px;
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.study-panel p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.facts {
display: flex;
gap: 8px;
margin: 14px 0 13px;
flex-wrap: wrap;
}
.fact {
padding: 6px 8px;
border: 1px solid rgba(164, 201, 219, 0.14);
border-radius: 5px;
color: #bfd0db;
background: rgba(255, 255, 255, 0.025);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.legend {
display: flex;
gap: 18px;
color: #b7c8d3;
font-size: 11px;
}
.legend span {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: 0 0 12px currentColor;
}
.swatch.cyan {
color: var(--cyan);
background: var(--cyan);
}
.swatch.amber {
color: var(--amber);
background: var(--amber);
}
.controls {
right: 24px;
bottom: 24px;
width: 250px;
padding: 15px;
border-radius: 12px;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 14px;
}
button {
min-height: 35px;
border: 1px solid rgba(167, 208, 229, 0.2);
border-radius: 7px;
color: #dcebf3;
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(167, 208, 229, 0.42);
background: rgba(255, 255, 255, 0.08);
}
button:active {
transform: translateY(1px);
}
.control-row {
margin-top: 11px;
}
.control-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: #9fb3c0;
font-size: 10px;
font-weight: 650;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control-label output {
color: #dcebf3;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
accent-color: #80d8e5;
cursor: pointer;
}
#tags {
position: fixed;
inset: 0;
z-index: 5;
overflow: hidden;
pointer-events: none;
}
.object-tag {
position: absolute;
min-width: 145px;
padding: 9px 11px 10px;
border: 1px solid rgba(151, 199, 220, 0.2);
border-radius: 8px;
background: rgba(7, 16, 25, 0.76);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
transform: translate(-50%, calc(-100% - 10px));
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
}
.object-tag::after {
content: "";
position: absolute;
left: 50%;
top: 100%;
width: 1px;
height: 11px;
background: linear-gradient(currentColor, transparent);
opacity: 0.65;
}
.object-tag.a {
color: var(--cyan);
}
.object-tag.b {
color: var(--amber);
}
.object-tag strong {
display: block;
margin-bottom: 3px;
color: currentColor;
font-size: 10px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.object-tag small {
display: block;
color: #a9bbc6;
font-size: 9px;
letter-spacing: 0.025em;
}
.hint {
position: fixed;
right: 25px;
top: 25px;
z-index: 10;
padding: 7px 10px;
border: 1px solid rgba(155, 196, 217, 0.14);
border-radius: 6px;
color: #8098a7;
background: rgba(8, 18, 28, 0.55);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
pointer-events: none;
}
@media (max-width: 760px) {
.brand {
top: 17px;
left: 17px;
}
.brand p {
max-width: 290px;
}
.hint {
display: none;
}
.study-panel {
left: 12px;
bottom: 12px;
width: calc(100vw - 24px);
padding: 12px;
}
.facts,
.study-panel p {
display: none;
}
.controls {
right: 12px;
top: 102px;
bottom: auto;
width: 190px;
padding: 11px;
}
.button-row {
margin-bottom: 9px;
}
.object-tag {
min-width: 112px;
padding: 7px 8px;
}
.object-tag small {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel spinning top comparison"></canvas>
<header class="brand">
<div class="eyebrow">Vertical-axis mass study</div>
<h1>Same top. Different balance.</h1>
<p>
Equal-height voxel shells with identical mass-voxel counts.
The cutaway exposes each modeled rim distribution.
</p>
</header>
<div class="hint">Drag to orbit · Scroll to zoom</div>
<div id="tags">
<div class="object-tag a" id="tag-a">
<strong>A · Balanced rim</strong>
<small>Mass distributed around the full circumference</small>
</div>
<div class="object-tag b" id="tag-b">
<strong>B · Offset rim</strong>
<small>Same voxel count, concentrated to one side</small>
</div>
</div>
<section class="panel study-panel">
<h2>Controlled comparison</h2>
<p>
Both tops use the same outer voxel profile and vertical centerline.
Only the placement of the colored mass voxels changes.
</p>
<div class="facts">
<div class="fact">Equal envelope · 3.36 u</div>
<div class="fact" id="mass-count">42 mass voxels each</div>
<div class="fact">Shared vertical axis</div>
</div>
<div class="legend">
<span><i class="swatch cyan"></i>Distributed mass</span>
<span><i class="swatch amber"></i>Offset mass</span>
</div>
</section>
<section class="panel controls">
<div class="button-row">
<button id="pause" type="button">Pause</button>
<button id="reset" type="button">Reset view</button>
</div>
<div class="control-row">
<label class="control-label" for="cutaway">
Cutaway width
<output id="cutaway-value">118°</output>
</label>
<input id="cutaway" type="range" min="45" max="150" value="118" />
</div>
<div class="control-row">
<label class="control-label" for="spin">
Spin speed
<output id="spin-value">0.80×</output>
</label>
<input id="spin" type="range" min="0" max="1.6" step="0.05" value="0.8" />
</div>
</section>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 12, 28);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
80
);
/* --------------------------------------------------------------
Direct camera controls: orbit, zoom, and reset.
No addons or examples modules are used.
---------------------------------------------------------------- */
const orbit = {
theta: 0.65,
phi: 1.05,
radius: 9.2,
target: new THREE.Vector3(0, 1.58, 0)
};
const defaultOrbit = {
theta: 0.65,
phi: 1.05,
radius: 9.2
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
updateCamera();
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.005,
0.48,
1.43
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
5.7,
14.5
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
Object.assign(orbit, defaultOrbit);
updateCamera();
});
/* --------------------------------------------------------------
Scene lighting and floor.
---------------------------------------------------------------- */
scene.add(new THREE.HemisphereLight(0xb8dcff, 0x071019, 1.55));
const keyLight = new THREE.DirectionalLight(0xf2f8ff, 3.15);
keyLight.position.set(4.5, 8.5, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 22;
keyLight.shadow.bias = -0.00015;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x35d9d0, 17, 9, 2);
cyanLight.position.set(-4.2, 3.5, 2.2);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xff9d42, 17, 9, 2);
amberLight.position.set(4.2, 3.3, 1.7);
scene.add(amberLight);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x0a141e,
roughness: 0.95,
metalness: 0.05
});
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(36, 36),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.015;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 48, 0x294252, 0x162936);
grid.position.y = 0.002;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x101c27,
roughness: 0.72,
metalness: 0.18
});
const platformEdgeMaterial = new THREE.MeshStandardMaterial({
color: 0x263948,
roughness: 0.56,
metalness: 0.3
});
const topPositions = [-2.2, 2.2];
const topAccents = [0x49e1d0, 0xffad4d];
const platformGeometry = new THREE.BoxGeometry(2.78, 0.1, 2.78);
const edgeGeometry = new THREE.BoxGeometry(2.42, 0.025, 0.025);
for (let index = 0; index < topPositions.length; index++) {
const x = topPositions[index];
const platform = new THREE.Mesh(platformGeometry, platformMaterial);
platform.position.set(x, 0.05, 0);
platform.receiveShadow = true;
scene.add(platform);
for (const z of [-1.21, 1.21]) {
const edge = new THREE.Mesh(edgeGeometry, platformEdgeMaterial);
edge.position.set(x, 0.115, z);
scene.add(edge);
}
// Segmented voxel datum around each top.
const markerGeometry = new THREE.BoxGeometry(0.07, 0.035, 0.14);
const markerMaterial = new THREE.MeshStandardMaterial({
color: topAccents[index],
emissive: topAccents[index],
emissiveIntensity: 0.22,
roughness: 0.45,
metalness: 0.2
});
const markers = new THREE.InstancedMesh(
markerGeometry,
markerMaterial,
28
);
const dummy = new THREE.Object3D();
for (let i = 0; i < 28; i++) {
const angle = (i / 28) * Math.PI * 2;
dummy.position.set(
x + Math.cos(angle) * 1.22,
0.125,
Math.sin(angle) * 1.22
);
dummy.rotation.set(0, -angle, 0);
dummy.scale.setScalar(i === 0 ? 1.35 : 0.72);
dummy.updateMatrix();
markers.setMatrixAt(i, dummy.matrix);
}
markers.instanceMatrix.needsUpdate = true;
scene.add(markers);
}
/* --------------------------------------------------------------
Fixed vertical centerlines and equal-height reference marks.
---------------------------------------------------------------- */
function createAxis(x) {
const axisGroup = new THREE.Group();
axisGroup.position.x = x;
const shaftCount = 29;
const shaftGeometry = new THREE.BoxGeometry(0.052, 0.118, 0.052);
const shaftMaterial = new THREE.MeshStandardMaterial({
color: 0x9bb0bc,
emissive: 0x18333e,
emissiveIntensity: 0.45,
roughness: 0.36,
metalness: 0.65
});
const shaft = new THREE.InstancedMesh(
shaftGeometry,
shaftMaterial,
shaftCount
);
const dummy = new THREE.Object3D();
for (let i = 0; i < shaftCount; i++) {
dummy.position.set(0, 0.1 + i * 0.125, 0);
dummy.updateMatrix();
shaft.setMatrixAt(i, dummy.matrix);
}
shaft.instanceMatrix.needsUpdate = true;
axisGroup.add(shaft);
const tickGeometry = new THREE.BoxGeometry(0.17, 0.025, 0.025);
const tickMaterial = new THREE.MeshBasicMaterial({
color: 0x698494,
transparent: true,
opacity: 0.65
});
for (let y = 0.45; y <= 3.45; y += 0.5) {
const tick = new THREE.Mesh(tickGeometry, tickMaterial);
tick.position.set(0.1, y, 0);
axisGroup.add(tick);
}
const cap = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.12, 0.12),
shaftMaterial
);
cap.position.y = 3.67;
axisGroup.add(cap);
scene.add(axisGroup);
}
function createHeightGuide(x) {
const group = new THREE.Group();
group.position.set(x + 1.34, 0, -0.55);
const dashGeometry = new THREE.BoxGeometry(0.025, 0.09, 0.025);
const guideMaterial = new THREE.MeshBasicMaterial({
color: 0x577486,
transparent: true,
opacity: 0.48
});
const dashCount = 17;
const dashes = new THREE.InstancedMesh(
dashGeometry,
guideMaterial,
dashCount
);
const dummy = new THREE.Object3D();
for (let i = 0; i < dashCount; i++) {
dummy.position.set(0, 0.2 + i * 0.195, 0);
dummy.updateMatrix();
dashes.setMatrixAt(i, dummy.matrix);
}
dashes.instanceMatrix.needsUpdate = true;
group.add(dashes);
const tickGeometry = new THREE.BoxGeometry(0.19, 0.025, 0.025);
for (const y of [0.145, 3.475]) {
const tick = new THREE.Mesh(tickGeometry, guideMaterial);
tick.position.x = -0.08;
tick.position.y = y;
group.add(tick);
}
scene.add(group);
}
topPositions.forEach((x) => {
createAxis(x);
createHeightGuide(x);
});
/* --------------------------------------------------------------
Shared voxel geometry and top profile.
---------------------------------------------------------------- */
const GRID = 0.16;
const TOP_X = -2.2;
const TOP_B = 2.2;
// y, outer radius. Both models use this exact profile.
const profile = [
[0.20, 0.06],
[0.36, 0.20],
[0.52, 0.36],
[0.68, 0.52],
[0.84, 0.68],
[1.00, 0.84],
[1.16, 0.96],
[1.32, 1.04],
[1.48, 1.04],
[1.64, 1.04],
[1.80, 0.98],
[1.96, 0.86],
[2.12, 0.70],
[2.28, 0.54],
[2.44, 0.40],
[2.60, 0.30],
[2.76, 0.24],
[2.92, 0.24],
[3.08, 0.24],
[3.24, 0.24],
[3.40, 0.12]
];
const shellGeometry = new THREE.BoxGeometry(0.154, 0.154, 0.154);
const massGeometry = new THREE.BoxGeometry(0.142, 0.142, 0.142);
const shellMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.58,
metalness: 0.22,
emissive: 0x071019,
emissiveIntensity: 0.38
});
const balancedMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.3,
metalness: 0.2,
emissive: 0x07524c,
emissiveIntensity: 0.34
});
const offsetMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.32,
metalness: 0.2,
emissive: 0x5b1e00,
emissiveIntensity: 0.32
});
function insideRadius(ix, iz, radius) {
const x = ix * GRID;
const z = iz * GRID;
return x * x + z * z <= radius * radius;
}
function hash01(x, y, z) {
const value = Math.sin(x * 127.1 + y * 311.7 + z * 74.7) * 43758.5453;
return value - Math.floor(value);
}
function generateShellRecords() {
const records = [];
for (const [y, radius] of profile) {
for (let ix = -7; ix <= 7; ix++) {
for (let iz = -7; iz <= 7; iz++) {
if (!insideRadius(ix, iz, radius)) continue;
const boundary =
!insideRadius(ix + 1, iz, radius) ||
!insideRadius(ix - 1, iz, radius) ||
!insideRadius(ix, iz + 1, radius) ||
!insideRadius(ix, iz - 1, radius);
if (!boundary) continue;
const x = ix * GRID;
const z = iz * GRID;
const heightMix = THREE.MathUtils.clamp(
(y - profile[0][0]) /
(profile[profile.length - 1][0] - profile[0][0]),
0,
1
);
const color = new THREE.Color(0x304353);
color.lerp(new THREE.Color(0x70889a), heightMix * 0.48);
const variation = hash01(ix, y, iz);
color.offsetHSL(
(variation - 0.5) * 0.012,
(variation - 0.5) * 0.05,
(variation - 0.5) * 0.075
);
records.push({ x, y, z, color });
}
}
}
return records;
}
function angularDifference(a, b) {
return Math.atan2(Math.sin(a - b), Math.cos(a - b));
}
function massCandidates(y) {
const candidates = [];
for (let ix = -6; ix <= 6; ix++) {
for (let iz = -6; iz <= 6; iz++) {
const x = ix * GRID;
const z = iz * GRID;
const radius = Math.hypot(x, z);
if (radius < 0.48 || radius > 0.92) continue;
candidates.push({
ix,
iz,
x,
y,
z,
radius,
angle: Math.atan2(z, x)
});
}
}
return candidates;
}
function generateBalancedMass() {
const records = [];
const levels = [1.16, 1.40, 1.64];
const perLevel = 14;
for (const y of levels) {
const candidates = massCandidates(y);
const used = new Set();
for (let i = 0; i < perLevel; i++) {
const targetAngle = (i / perLevel) * Math.PI * 2;
const targetRadius = 0.72;
candidates.sort((a, b) => {
const scoreA =
Math.abs(angularDifference(a.angle, targetAngle)) +
0.12 * Math.abs(a.radius - targetRadius);
const scoreB =
Math.abs(angularDifference(b.angle, targetAngle)) +
0.12 * Math.abs(b.radius - targetRadius);
return scoreA - scoreB;
});
let chosen = candidates.find(
(candidate) => !used.has(`${candidate.ix},${candidate.iz}`)
);
if (!chosen) break;
used.add(`${chosen.ix},${chosen.iz}`);
const variation = hash01(chosen.ix, y, chosen.iz);
const color = new THREE.Color(0x32ddcb);
color.lerp(new THREE.Color(0x9bfff1), variation * 0.42);
records.push({
x: chosen.x,
y,
z: chosen.z,
color
});
}
}
return records;
}
function generateOffsetMass() {
const records = [];
const levels = [1.16, 1.40, 1.64];
const perLevel = 14;
// The initial cluster faces the default camera.
const clusterCenter = 0.78;
for (const y of levels) {
let candidates = massCandidates(y).filter((candidate) =>
Math.abs(
angularDifference(candidate.angle, clusterCenter)
) < THREE.MathUtils.degToRad(58)
);
if (candidates.length < perLevel) {
candidates = massCandidates(y).filter((candidate) =>
Math.abs(
angularDifference(candidate.angle, clusterCenter)
) < THREE.MathUtils.degToRad(72)
);
}
candidates.sort((a, b) => {
const scoreA =
Math.abs(angularDifference(a.angle, clusterCenter)) +
0.09 * Math.abs(a.radius - 0.78);
const scoreB =
Math.abs(angularDifference(b.angle, clusterCenter)) +
0.09 * Math.abs(b.radius - 0.78);
return scoreA - scoreB;
});
for (let i = 0; i < Math.min(perLevel, candidates.length); i++) {
const candidate = candidates[i];
const color = new THREE.Color(0xffb64d);
if (candidate.radius > 0.8) {
color.lerp(new THREE.Color(0xff684c), 0.48);
}
const variation = hash01(candidate.ix, y, candidate.iz);
color.offsetHSL(0, 0, (variation - 0.5) * 0.07);
records.push({
x: candidate.x,
y,
z: candidate.z,
color
});
}
}
return records;
}
function createVoxelMesh(records, geometry, material) {
const mesh = new THREE.InstancedMesh(
geometry,
material,
records.length
);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
for (let i = 0; i < records.length; i++) {
mesh.setColorAt(i, records[i].color);
}
if (mesh.instanceColor) {
mesh.instanceColor.needsUpdate = true;
}
return mesh;
}
const shellRecords = generateShellRecords();
const balancedMassRecords = generateBalancedMass();
const offsetMassRecords = generateOffsetMass();
const topA = new THREE.Group();
topA.position.x = TOP_X;
const topB = new THREE.Group();
topB.position.x = TOP_B;
const shellA = createVoxelMesh(
shellRecords,
shellGeometry,
shellMaterial
);
const shellB = createVoxelMesh(
shellRecords,
shellGeometry,
shellMaterial
);
const massA = createVoxelMesh(
balancedMassRecords,
massGeometry,
balancedMaterial
);
const massB = createVoxelMesh(
offsetMassRecords,
massGeometry,
offsetMaterial
);
topA.add(shellA, massA);
topB.add(shellB, massB);
scene.add(topA, topB);
document.querySelector("#mass-count").textContent =
`${balancedMassRecords.length} / ${offsetMassRecords.length} mass voxels`;
/* --------------------------------------------------------------
Animated voxel matrices.
The shell spins while its cutaway remains oriented toward the
camera. Mass voxels remain visible inside the opened region.
---------------------------------------------------------------- */
const updateDummy = new THREE.Object3D();
const spinQuaternion = new THREE.Quaternion();
const yAxis = new THREE.Vector3(0, 1, 0);
let cutawayDegrees = 118;
let cutawayRadians = THREE.MathUtils.degToRad(cutawayDegrees);
function updateVoxelMesh(mesh, records, angle, cutawayCenter, cutShell) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
const halfWidth = cutawayRadians * 0.5;
spinQuaternion.setFromAxisAngle(yAxis, angle);
for (let i = 0; i < records.length; i++) {
const record = records[i];
const spunX = cos * record.x + sin * record.z;
const spunZ = -sin * record.x + cos * record.z;
let visible = true;
if (cutShell) {
const radialDistance = Math.hypot(spunX, spunZ);
const voxelAngle = Math.atan2(spunZ, spunX);
const difference = Math.abs(
angularDifference(voxelAngle, cutawayCenter)
);
// Keep the central axis intact while opening the outer shell.
if (radialDistance > 0.32 && difference < halfWidth) {
visible = false;
}
}
updateDummy.position.set(spunX, record.y, spunZ);
updateDummy.quaternion.copy(spinQuaternion);
updateDummy.scale.setScalar(visible ? 1 : 0);
updateDummy.updateMatrix();
mesh.setMatrixAt(i, updateDummy.matrix);
}
mesh.instanceMatrix.needsUpdate = true;
}
/* --------------------------------------------------------------
UI controls.
---------------------------------------------------------------- */
const pauseButton = document.querySelector("#pause");
const cutawayInput = document.querySelector("#cutaway");
const spinInput = document.querySelector("#spin");
const cutawayValue = document.querySelector("#cutaway-value");
const spinValue = document.querySelector("#spin-value");
let paused = false;
let spinSpeed = Number(spinInput.value);
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
cutawayInput.addEventListener("input", () => {
cutawayDegrees = Number(cutawayInput.value);
cutawayRadians = THREE.MathUtils.degToRad(cutawayDegrees);
cutawayValue.textContent = `${cutawayDegrees}°`;
});
spinInput.addEventListener("input", () => {
spinSpeed = Number(spinInput.value);
spinValue.textContent = `${spinSpeed.toFixed(2)}×`;
});
document.querySelector("#reset").addEventListener("click", () => {
Object.assign(orbit, defaultOrbit);
updateCamera();
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
}
if (event.key.toLowerCase() === "r") {
Object.assign(orbit, defaultOrbit);
updateCamera();
}
});
/* --------------------------------------------------------------
Screen-space labels.
---------------------------------------------------------------- */
const tagA = document.querySelector("#tag-a");
const tagB = document.querySelector("#tag-b");
const projection = new THREE.Vector3();
function positionTag(element, x, y, z) {
projection.set(x, y, z).project(camera);
const visible = projection.z > -1 && projection.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const screenX = (projection.x * 0.5 + 0.5) * window.innerWidth;
const screenY = (-projection.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${screenX}px`;
element.style.top = `${screenY}px`;
}
/* --------------------------------------------------------------
Render loop.
---------------------------------------------------------------- */
let previousTime = performance.now();
let elapsed = 0;
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!paused) {
elapsed += delta * spinSpeed;
}
const angle = elapsed * 1.05;
const cameraAzimuth = Math.atan2(
camera.position.z - orbit.target.z,
camera.position.x - orbit.target.x
);
updateVoxelMesh(
shellA,
shellRecords,
angle,
cameraAzimuth,
true
);
updateVoxelMesh(
shellB,
shellRecords,
angle,
cameraAzimuth,
true
);
// Mass remains modeled inside the opened shell.
updateVoxelMesh(
massA,
balancedMassRecords,
angle,
cameraAzimuth,
false
);
updateVoxelMesh(
massB,
offsetMassRecords,
angle,
cameraAzimuth,
false
);
positionTag(tagA, TOP_X, 3.94, 0);
positionTag(tagB, TOP_B, 3.94, 0);
renderer.render(scene, camera);
}
requestAnimationFrame(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>
```