Prompt specification
Build or customize the Three.js 3D scene "Granular packing exploration tray" 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: Granular packing exploration tray
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/granular-packing-exploration-tray-x1392
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts a low-poly granular packing experiment in a shallow transparent tray. Provide a small, bounded set of round grains in two size classes and let the user change their mixture before starting a settling trial. Keep the tray dimensions fixed and show empty spaces between grains from an overhead and an oblique view. Report a clearly defined geometric void-space estimate for this toy model, rather than calling it a measured material density. Use repeatable initial arrangements so two mixtures can be compared sensibly. Avoid allowing grains to overlap or disappear when the container becomes crowded.
Working Three.js Starter (granular-packing-exploration-tray-x1392):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Repeatable Granular Packing Toy</title>
<style>
:root {
color-scheme: light;
--ink: #203332;
--muted: #647876;
--line: #d7e2df;
--paper: #f8fbfa;
--panel: #ffffff;
--teal: #248f8b;
--teal-dark: #176965;
--amber: #e4a13d;
--danger: #b33f3f;
--shadow: 0 10px 30px rgba(30, 62, 59, 0.10);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--paper);
color: var(--ink);
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
header {
height: 62px;
padding: 0 22px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
border-bottom: 1px solid var(--line);
background: rgba(255, 255, 255, 0.94);
}
header h1 {
margin: 0;
font-size: 1.02rem;
letter-spacing: 0.01em;
}
header p {
margin: 3px 0 0;
color: var(--muted);
font-size: 0.79rem;
}
.status {
border: 1px solid #b8d7d2;
border-radius: 999px;
padding: 7px 12px;
background: #edf7f5;
color: var(--teal-dark);
font-size: 0.78rem;
font-weight: 700;
white-space: nowrap;
}
main {
height: calc(100vh - 62px);
display: grid;
grid-template-columns: 326px minmax(0, 1fr);
}
aside {
overflow-y: auto;
padding: 16px;
border-right: 1px solid var(--line);
background: #f3f8f7;
}
.card {
margin-bottom: 14px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 13px;
background: var(--panel);
box-shadow: var(--shadow);
}
.card h2 {
margin: 0 0 12px;
font-size: 0.84rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: #3e5957;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.field-label {
font-weight: 700;
font-size: 0.86rem;
}
output {
color: var(--teal-dark);
font-variant-numeric: tabular-nums;
font-size: 0.84rem;
font-weight: 800;
}
input[type="range"] {
width: 100%;
margin: 13px 0 8px;
accent-color: var(--teal);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
color: var(--muted);
font-size: 0.77rem;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.dot {
width: 10px;
height: 10px;
border-radius: 50%;
display: inline-block;
}
.dot.large {
background: var(--amber);
}
.dot.small {
background: var(--teal);
}
.hint {
margin: 10px 0 0;
color: var(--muted);
font-size: 0.75rem;
line-height: 1.45;
}
.seed-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 13px;
}
input[type="number"] {
width: 100%;
min-width: 0;
border: 1px solid #bfcfcc;
border-radius: 8px;
padding: 8px 9px;
color: var(--ink);
background: #fff;
font: inherit;
}
button {
border: 1px solid #b9cdca;
border-radius: 9px;
padding: 9px 11px;
background: #fff;
color: var(--ink);
font: inherit;
font-size: 0.79rem;
font-weight: 750;
cursor: pointer;
}
button:hover:not(:disabled) {
border-color: var(--teal);
color: var(--teal-dark);
}
button.primary {
width: 100%;
border-color: var(--teal);
background: var(--teal);
color: white;
}
button.primary:hover:not(:disabled) {
background: var(--teal-dark);
color: white;
}
button:disabled,
input:disabled {
cursor: not-allowed;
opacity: 0.48;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 9px;
}
.progress {
height: 7px;
overflow: hidden;
margin-top: 12px;
border-radius: 99px;
background: #e4eeec;
}
.progress > div {
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--teal), #68bdb7);
transition: width 0.08s linear;
}
.void-number {
margin: 0;
color: var(--teal-dark);
font-size: 2.25rem;
font-weight: 850;
letter-spacing: -0.045em;
font-variant-numeric: tabular-nums;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.metric {
padding: 9px;
border-radius: 9px;
background: #f2f7f6;
font-size: 0.72rem;
color: var(--muted);
}
.metric strong {
display: block;
margin-top: 3px;
color: var(--ink);
font-size: 0.88rem;
font-variant-numeric: tabular-nums;
}
details {
margin-top: 12px;
color: var(--muted);
font-size: 0.73rem;
line-height: 1.45;
}
summary {
cursor: pointer;
font-weight: 750;
color: #3e5957;
}
.formula {
margin: 8px 0;
padding: 8px;
border-radius: 7px;
background: #eef5f3;
color: #35504e;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.67rem;
overflow-wrap: anywhere;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.73rem;
}
th,
td {
padding: 7px 4px;
text-align: left;
border-bottom: 1px solid #e3ebe9;
font-variant-numeric: tabular-nums;
}
th {
color: var(--muted);
font-weight: 700;
}
.empty {
color: var(--muted);
font-style: italic;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #edf3f1;
}
#stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
z-index: 0;
}
.view-label {
position: absolute;
z-index: 2;
pointer-events: none;
padding: 7px 10px;
border: 1px solid rgba(125, 157, 152, 0.42);
border-radius: 8px;
background: rgba(255, 255, 255, 0.83);
color: #3a5653;
font-size: 0.69rem;
font-weight: 850;
letter-spacing: 0.055em;
box-shadow: 0 5px 16px rgba(39, 66, 63, 0.08);
}
#obliqueLabel {
left: calc(50% + 13px);
top: 13px;
}
#overheadLabel {
left: 13px;
top: 13px;
}
.split-line {
position: absolute;
z-index: 1;
left: 50%;
top: 0;
width: 1px;
height: 100%;
background: rgba(105, 136, 132, 0.32);
pointer-events: none;
}
.stage-hint {
position: absolute;
z-index: 2;
left: 50%;
bottom: 13px;
transform: translateX(-50%);
padding: 7px 11px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.82);
color: #55706d;
font-size: 0.7rem;
pointer-events: none;
white-space: nowrap;
}
#stage.narrow .view-label {
left: 12px;
}
#stage.narrow #overheadLabel {
top: 12px;
}
#stage.narrow #obliqueLabel {
top: calc(50% + 12px);
}
#stage.narrow .split-line {
left: 0;
top: 50%;
width: 100%;
height: 1px;
}
#stage.narrow .stage-hint {
bottom: 9px;
font-size: 0.62rem;
}
.ok {
color: var(--teal-dark) !important;
}
.bad {
color: var(--danger) !important;
}
@media (max-width: 820px) {
body {
overflow: auto;
}
header {
height: auto;
min-height: 62px;
padding: 11px 15px;
}
header p {
display: none;
}
main {
height: auto;
display: flex;
flex-direction: column;
}
#stage {
order: 0;
height: 70vh;
min-height: 560px;
}
aside {
order: 1;
overflow: visible;
border-right: 0;
border-top: 1px solid var(--line);
}
}
</style>
</head>
<body>
<header>
<div>
<h1>Repeatable Granular Packing Toy</h1>
<p>Single-layer round grains in a fixed transparent tray</p>
</div>
<div id="status" class="status">Ready to settle</div>
</header>
<main>
<aside>
<section class="card">
<h2>1 · Configure mixture</h2>
<div class="row">
<label class="field-label" for="mixture">Small-grain share</label>
<output id="mixtureOutput" for="mixture">50%</output>
</div>
<input
id="mixture"
type="range"
min="0"
max="100"
step="5"
value="50"
aria-label="Small grain percentage"
>
<div class="legend">
<span><i class="dot large"></i>Large: radius 0.30</span>
<span><i class="dot small"></i>Small: radius 0.18</span>
</div>
<div class="seed-row">
<label>
<span class="field-label">Arrangement seed</span>
<input id="seed" type="number" min="1" max="9999" value="7">
</label>
<button id="newSeed" type="button">New seed</button>
</div>
<p class="hint">
The grain count is fixed at 96. A seed reuses the same anchor positions,
while the small-grain subset changes in a nested, deterministic order.
Keep the seed unchanged for direct A/B comparisons.
</p>
</section>
<section class="card">
<h2>2 · Settling trial</h2>
<button id="start" class="primary" type="button">Start settling trial</button>
<div class="button-row">
<button id="reset" type="button">Reset / edit</button>
<button id="storeA" type="button" disabled>Save as A</button>
</div>
<div class="button-row">
<button id="storeB" type="button" disabled>Save as B</button>
</div>
<div class="progress" aria-label="Trial progress">
<div id="progressFill"></div>
</div>
<p class="hint">
Grains first fall onto the floor, followed by a deterministic 2-D
compaction/jostle pass. Circle constraints and wall constraints are
solved iteratively; grains are never removed to resolve congestion.
</p>
</section>
<section class="card">
<h2>Geometric void-space estimate</h2>
<div id="voidValue" class="void-number">—</div>
<div class="hint">Planar floor-area void fraction</div>
<div class="metric-grid">
<div class="metric">
Empty projected area
<strong id="voidArea">—</strong>
</div>
<div class="metric">
Tray area
<strong>70.00 units²</strong>
</div>
<div class="metric">
Grains rendered
<strong id="grainCount">96 / 96</strong>
</div>
<div class="metric">
Overlap pairs
<strong id="overlapCount" class="ok">0</strong>
</div>
</div>
<details>
<summary>Definition and limits</summary>
<div class="formula">
φvoid = 1 − [nL·π·(0.30)² + nS·π·(0.18)²] / (10 × 7)
</div>
<p>
This is the fraction of the fixed tray floor not covered by the
projected circular footprints of the non-overlapping, single-layer
grains. It is a geometric toy-model estimate, not a measured
material density and not a three-dimensional bulk porosity.
</p>
</details>
</section>
<section class="card">
<h2>Compare saved trials</h2>
<table>
<thead>
<tr>
<th>Slot</th>
<th>Small</th>
<th>Seed</th>
<th>Void</th>
</tr>
</thead>
<tbody id="comparisonBody">
<tr>
<td colspan="4" class="empty">Complete a trial and save it to A or B.</td>
</tr>
</tbody>
</table>
</section>
</aside>
<section id="stage" aria-label="Two views of the granular packing experiment">
<div id="overheadLabel" class="view-label">OVERHEAD · ORTHOGRAPHIC</div>
<div id="obliqueLabel" class="view-label">OBLIQUE · DRAG TO ORBIT</div>
<div class="split-line"></div>
<div class="stage-hint">
Fixed tray: 10 × 7 units · 96 grains · drag the oblique view to orbit
</div>
</section>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Fixed model dimensions and bounds
// -------------------------------------------------------------------------
const TRAY_W = 10;
const TRAY_D = 7;
const TRAY_AREA = TRAY_W * TRAY_D;
const GRAIN_COUNT = 96;
const LARGE_RADIUS = 0.30;
const SMALL_RADIUS = 0.18;
const WALL_HEIGHT = 0.68;
const GRAVITY = 6.0;
const RELAXATION_DURATION = 3.5;
const stage = document.querySelector("#stage");
const ui = {
status: document.querySelector("#status"),
mixture: document.querySelector("#mixture"),
mixtureOutput: document.querySelector("#mixtureOutput"),
seed: document.querySelector("#seed"),
newSeed: document.querySelector("#newSeed"),
start: document.querySelector("#start"),
reset: document.querySelector("#reset"),
storeA: document.querySelector("#storeA"),
storeB: document.querySelector("#storeB"),
progressFill: document.querySelector("#progressFill"),
voidValue: document.querySelector("#voidValue"),
voidArea: document.querySelector("#voidArea"),
grainCount: document.querySelector("#grainCount"),
overlapCount: document.querySelector("#overlapCount"),
comparisonBody: document.querySelector("#comparisonBody")
};
let mixtureSmall = 50;
let seed = 7;
let state = "edit"; // edit | running | done
let elapsed = 0;
let grains = [];
let basePoints = [];
let classPermutation = [];
let maxLandTime = 0;
let currentEstimate = null;
const savedTrials = { A: null, B: null };
// -------------------------------------------------------------------------
// Renderer, cameras and scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0xedf3f1, 1);
renderer.autoClear = false;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Overhead and oblique views of grains settling in a transparent tray"
);
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
const overheadCamera = new THREE.OrthographicCamera(-6, 6, 4, -4, 0.1, 50);
overheadCamera.position.set(0, 14, 0);
overheadCamera.up.set(0, 0, -1);
overheadCamera.lookAt(0, 0, 0);
const obliqueCamera = new THREE.PerspectiveCamera(38, 1, 0.1, 80);
const orbit = {
theta: 0.72,
elevation: 0.72,
radius: 14.0,
target: new THREE.Vector3(0, 0.12, 0)
};
function updateObliqueCamera() {
const horizontal = orbit.radius * Math.cos(orbit.elevation);
obliqueCamera.position.set(
orbit.target.x + horizontal * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.sin(orbit.elevation),
orbit.target.z + horizontal * Math.cos(orbit.theta)
);
obliqueCamera.lookAt(orbit.target);
}
updateObliqueCamera();
scene.add(new THREE.HemisphereLight(0xf7fffd, 0x7c9691, 2.1));
const keyLight = new THREE.DirectionalLight(0xfff4dc, 3.0);
keyLight.position.set(4.5, 9, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xc5eeff, 1.2);
fillLight.position.set(-6, 4, -4);
scene.add(fillLight);
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0x8ad4d0,
transparent: true,
opacity: 0.16,
roughness: 0.22,
metalness: 0,
depthWrite: false,
side: THREE.DoubleSide
});
const glassEdgeMaterial = new THREE.LineBasicMaterial({
color: 0x4c9691,
transparent: true,
opacity: 0.72
});
function addBoxWithEdges(width, height, depth, x, y, z) {
const geometry = new THREE.BoxGeometry(width, height, depth);
const mesh = new THREE.Mesh(geometry, glassMaterial);
mesh.position.set(x, y, z);
mesh.receiveShadow = true;
scene.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
glassEdgeMaterial
);
edges.position.copy(mesh.position);
scene.add(edges);
return mesh;
}
// The inner tray dimensions remain exactly TRAY_W by TRAY_D.
addBoxWithEdges(TRAY_W, 0.12, TRAY_D, 0, -0.06, 0);
addBoxWithEdges(0.06, WALL_HEIGHT, TRAY_D + 0.12,
-TRAY_W / 2 - 0.03, WALL_HEIGHT / 2, 0);
addBoxWithEdges(0.06, WALL_HEIGHT, TRAY_D + 0.12,
TRAY_W / 2 + 0.03, WALL_HEIGHT / 2, 0);
addBoxWithEdges(TRAY_W, WALL_HEIGHT, 0.06,
0, WALL_HEIGHT / 2, -TRAY_D / 2 - 0.03);
addBoxWithEdges(TRAY_W, WALL_HEIGHT, 0.06,
0, WALL_HEIGHT / 2, TRAY_D / 2 + 0.03);
// A regular grid provides an immediate visual reference for empty floor.
const gridVertices = [];
for (let x = -TRAY_W / 2; x <= TRAY_W / 2 + 0.001; x += 0.5) {
gridVertices.push(x, 0.008, -TRAY_D / 2, x, 0.008, TRAY_D / 2);
}
for (let z = -TRAY_D / 2; z <= TRAY_D / 2 + 0.001; z += 0.5) {
gridVertices.push(-TRAY_W / 2, 0.008, z, TRAY_W / 2, 0.008, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x4f8e88,
transparent: true,
opacity: 0.23
})
);
scene.add(grid);
const shadowCatcher = new THREE.Mesh(
new THREE.PlaneGeometry(15, 12),
new THREE.ShadowMaterial({ opacity: 0.12 })
);
shadowCatcher.rotation.x = -Math.PI / 2;
shadowCatcher.position.y = -0.125;
shadowCatcher.receiveShadow = true;
scene.add(shadowCatcher);
const grainGroup = new THREE.Group();
scene.add(grainGroup);
// Low-poly icosahedral grains. Their horizontal footprint is a true circle
// of the radius used by the area and collision calculations.
const grainGeometry = new THREE.IcosahedronGeometry(1, 1);
const largeMaterial = new THREE.MeshStandardMaterial({
color: 0xe4a13d,
roughness: 0.72,
metalness: 0.02,
flatShading: true
});
const smallMaterial = new THREE.MeshStandardMaterial({
color: 0x248f8b,
roughness: 0.68,
metalness: 0.02,
flatShading: true
});
// -------------------------------------------------------------------------
// Deterministic arrangement and mixture construction
// -------------------------------------------------------------------------
function mulberry32(initialSeed) {
let a = initialSeed >>> 0;
return function () {
a += 0x6d2b79f5;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function normalizedSeed(value) {
const n = Number.parseInt(value, 10);
if (!Number.isFinite(n)) return 1;
return Math.max(1, Math.min(9999, n));
}
function generateBasePoints(currentSeed) {
const random = mulberry32((currentSeed * 2654435761) >>> 0);
const points = [];
const columns = 12;
const rows = 8;
const dx = 0.76;
const dz = 0.78;
// A jittered staggered lattice is repeatable, and its minimum spacing
// stays above the sum of two large radii.
for (let row = 0; row < rows; row++) {
const stagger = (row % 2) * dx * 0.5 + (random() - 0.5) * 0.03;
for (let column = 0; column < columns; column++) {
const x =
(column - (columns - 1) / 2) * dx +
stagger +
(random() - 0.5) * 0.06;
const z =
(row - (rows - 1) / 2) * dz +
(random() - 0.5) * 0.06;
points.push({ x, z });
}
}
return points;
}
function generatePermutation(currentSeed) {
const random = mulberry32((currentSeed ^ 0xa5a5a5a5) >>> 0);
const values = Array.from({ length: GRAIN_COUNT }, (_, i) => i);
for (let i = values.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[values[i], values[j]] = [values[j], values[i]];
}
return values;
}
function updateEstimate() {
const smallCount = Math.round(GRAIN_COUNT * mixtureSmall / 100);
const largeCount = GRAIN_COUNT - smallCount;
const occupiedArea =
largeCount * Math.PI * LARGE_RADIUS * LARGE_RADIUS +
smallCount * Math.PI * SMALL_RADIUS * SMALL_RADIUS;
const voidArea = Math.max(0, TRAY_AREA - occupiedArea);
const voidPercent = 100 * voidArea / TRAY_AREA;
currentEstimate = {
smallCount,
largeCount,
occupiedArea,
voidArea,
voidPercent
};
ui.voidValue.textContent = `${voidPercent.toFixed(1)}%`;
ui.voidArea.textContent = `${voidArea.toFixed(2)} units²`;
}
function rebuildGrains() {
grainGroup.clear();
const randomForDrop = mulberry32(
((seed ^ 0x9e3779b9) >>> 0)
);
const smallCount = Math.round(GRAIN_COUNT * mixtureSmall / 100);
const smallIndices = new Set(classPermutation.slice(0, smallCount));
grains = [];
maxLandTime = 0;
for (let i = 0; i < GRAIN_COUNT; i++) {
const isSmall = smallIndices.has(i);
const radius = isSmall ? SMALL_RADIUS : LARGE_RADIUS;
const point = basePoints[i];
const phase = randomForDrop() * Math.PI * 2;
const fallStart = randomForDrop() * 0.18;
const startY = 1.25 + randomForDrop() * 1.35;
const restY = radius * 0.72 + 0.025;
const fallDuration = Math.sqrt(
2 * Math.max(0, startY - restY) / GRAVITY
);
const landTime = fallStart + fallDuration;
const mesh = new THREE.Mesh(
grainGeometry,
isSmall ? smallMaterial : largeMaterial
);
mesh.scale.set(radius, radius * 0.72, radius);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
grainGroup.add(mesh);
grains.push({
index: i,
radius,
isSmall,
x: point.x,
z: point.z,
vx: 0,
vz: 0,
y: startY,
startY,
restY,
fallStart,
landTime,
phase,
mesh
});
maxLandTime = Math.max(maxLandTime, landTime);
}
syncMeshes();
updateEstimate();
updateDiagnostics();
}
function syncMeshes() {
for (const grain of grains) {
grain.mesh.position.set(grain.x, grain.y, grain.z);
}
}
// -------------------------------------------------------------------------
// Non-overlap constraints and diagnostics
// -------------------------------------------------------------------------
function overlapStats() {
let count = 0;
let maximumPenetration = 0;
for (let i = 0; i < grains.length; i++) {
const a = grains[i];
for (let j = i + 1; j < grains.length; j++) {
const b = grains[j];
const dx = b.x - a.x;
const dz = b.z - a.z;
const distance = Math.hypot(dx, dz);
const penetration = a.radius + b.radius - distance;
if (penetration > 1e-5) {
count++;
maximumPenetration = Math.max(maximumPenetration, penetration);
}
}
}
return { count, maximumPenetration };
}
function constrainToTray(grain) {
grain.x = Math.max(
-TRAY_W / 2 + grain.radius,
Math.min(TRAY_W / 2 - grain.radius, grain.x)
);
grain.z = Math.max(
-TRAY_D / 2 + grain.radius,
Math.min(TRAY_D / 2 - grain.radius, grain.z)
);
}
function resolveContacts(iterations) {
for (let iteration = 0; iteration < iterations; iteration++) {
for (let i = 0; i < grains.length; i++) {
const a = grains[i];
for (let j = i + 1; j < grains.length; j++) {
const b = grains[j];
let dx = b.x - a.x;
let dz = b.z - a.z;
let distance = Math.hypot(dx, dz);
const minimumDistance = a.radius + b.radius;
if (distance < minimumDistance) {
if (distance < 1e-9) {
const angle = ((i * 17 + j * 31) % 360) * Math.PI / 180;
dx = Math.cos(angle);
dz = Math.sin(angle);
distance = 1;
}
const nx = dx / distance;
const nz = dz / distance;
const penetration = minimumDistance - distance;
// Inverse-area weighting lets smaller grains move a little more.
const inverseMassA = 1 / (a.radius * a.radius);
const inverseMassB = 1 / (b.radius * b.radius);
const inverseMassTotal = inverseMassA + inverseMassB;
const correctionA =
penetration * inverseMassA / inverseMassTotal;
const correctionB =
penetration * inverseMassB / inverseMassTotal;
a.x -= nx * correctionA;
a.z -= nz * correctionA;
b.x += nx * correctionB;
b.z += nz * correctionB;
}
}
}
for (const grain of grains) {
constrainToTray(grain);
}
}
}
function updateDiagnostics() {
const stats = overlapStats();
ui.grainCount.textContent = `${grainGroup.children.length} / ${GRAIN_COUNT}`;
ui.overlapCount.textContent = String(stats.count);
ui.overlapCount.classList.toggle("ok", stats.count === 0);
ui.overlapCount.classList.toggle("bad", stats.count !== 0);
}
// -------------------------------------------------------------------------
// Toy settling simulation
// -------------------------------------------------------------------------
function updateSimulation(dt) {
elapsed += dt;
for (const grain of grains) {
if (elapsed < grain.fallStart) {
grain.y = grain.startY;
} else {
const fallingTime = elapsed - grain.fallStart;
grain.y = Math.max(
grain.restY,
grain.startY - 0.5 * GRAVITY * fallingTime * fallingTime
);
}
}
const relaxTime = elapsed - maxLandTime;
if (relaxTime >= 0) {
// Save a valid configuration. If a proposed step cannot be resolved,
// restoring this snapshot guarantees that grains never remain overlapped.
const previousPositions = grains.map(grain => ({
x: grain.x,
z: grain.z
}));
if (relaxTime < RELAXATION_DURATION) {
for (const grain of grains) {
const jitterX =
Math.sin(elapsed * 3.7 + grain.phase) * 0.022;
const jitterZ =
Math.cos(elapsed * 3.1 + grain.phase * 1.31) * 0.022;
grain.vx += (jitterX - grain.x * 0.0009) * dt;
grain.vz += (jitterZ - grain.z * 0.0009) * dt;
const damping = Math.exp(-2.4 * dt);
grain.vx *= damping;
grain.vz *= damping;
grain.x += grain.vx * dt;
grain.z += grain.vz * dt;
}
}
resolveContacts(24);
if (overlapStats().maximumPenetration > 1e-5) {
grains.forEach((grain, index) => {
grain.x = previousPositions[index].x;
grain.z = previousPositions[index].z;
grain.vx *= 0.2;
grain.vz *= 0.2;
});
}
if (relaxTime >= RELAXATION_DURATION) {
for (const grain of grains) {
grain.vx = 0;
grain.vz = 0;
grain.y = grain.restY;
}
const finalPositions = grains.map(grain => ({
x: grain.x,
z: grain.z
}));
resolveContacts(80);
if (overlapStats().maximumPenetration > 1e-5) {
grains.forEach((grain, index) => {
grain.x = finalPositions[index].x;
grain.z = finalPositions[index].z;
});
}
state = "done";
updateControls();
}
}
const totalDuration = maxLandTime + RELAXATION_DURATION;
ui.progressFill.style.width =
`${Math.min(100, 100 * elapsed / totalDuration)}%`;
syncMeshes();
updateDiagnostics();
}
// -------------------------------------------------------------------------
// UI state and A/B comparison
// -------------------------------------------------------------------------
function updateControls() {
const locked = state !== "edit";
ui.mixture.disabled = locked;
ui.seed.disabled = locked;
ui.newSeed.disabled = locked;
ui.start.disabled = state !== "edit";
ui.storeA.disabled = state !== "done";
ui.storeB.disabled = state !== "done";
if (state === "edit") {
ui.status.textContent = "Ready to settle";
ui.reset.textContent = "Reset / edit";
ui.progressFill.style.width = "0%";
} else if (state === "running") {
ui.status.textContent = "Settling…";
ui.reset.textContent = "Cancel trial";
} else {
ui.status.textContent = "Trial complete";
ui.reset.textContent = "Reset / edit";
ui.progressFill.style.width = "100%";
}
}
function saveTrial(slot) {
if (state !== "done" || !currentEstimate) return;
savedTrials[slot] = {
mixtureSmall,
seed,
voidPercent: currentEstimate.voidPercent
};
renderComparison();
}
function renderComparison() {
const rows = ["A", "B"].map(slot => {
const trial = savedTrials[slot];
if (!trial) {
return `
<tr>
<td><strong>${slot}</strong></td>
<td colspan="3" class="empty">No saved trial</td>
</tr>
`;
}
return `
<tr>
<td><strong>${slot}</strong></td>
<td>${trial.mixtureSmall}%</td>
<td>${trial.seed}</td>
<td>${trial.voidPercent.toFixed(1)}%</td>
</tr>
`;
});
ui.comparisonBody.innerHTML = rows.join("");
}
ui.mixture.addEventListener("input", () => {
if (state !== "edit") return;
mixtureSmall = Number(ui.mixture.value);
ui.mixtureOutput.textContent = `${mixtureSmall}%`;
ui.mixture.setAttribute(
"aria-valuetext",
`${mixtureSmall} percent small grains`
);
// The same anchors and the same nested permutation are retained.
rebuildGrains();
});
ui.seed.addEventListener("change", () => {
if (state !== "edit") return;
seed = normalizedSeed(ui.seed.value);
ui.seed.value = seed;
basePoints = generateBasePoints(seed);
classPermutation = generatePermutation(seed);
rebuildGrains();
});
ui.newSeed.addEventListener("click", () => {
if (state !== "edit") return;
seed = seed >= 9999 ? 1 : seed + 1;
ui.seed.value = seed;
basePoints = generateBasePoints(seed);
classPermutation = generatePermutation(seed);
rebuildGrains();
});
ui.start.addEventListener("click", () => {
if (state !== "edit") return;
elapsed = 0;
for (const grain of grains) {
grain.vx = 0;
grain.vz = 0;
}
state = "running";
updateControls();
});
ui.reset.addEventListener("click", () => {
state = "edit";
elapsed = 0;
rebuildGrains();
updateControls();
});
ui.storeA.addEventListener("click", () => saveTrial("A"));
ui.storeB.addEventListener("click", () => saveTrial("B"));
// -------------------------------------------------------------------------
// Viewport sizing and direct camera interaction
// -------------------------------------------------------------------------
let viewWidth = 1;
let viewHeight = 1;
let narrowLayout = false;
function resize() {
viewWidth = Math.max(1, Math.floor(stage.clientWidth));
viewHeight = Math.max(1, Math.floor(stage.clientHeight));
narrowLayout = viewWidth < 640;
renderer.setSize(viewWidth, viewHeight, false);
stage.classList.toggle("narrow", narrowLayout);
const overheadAspect = narrowLayout
? viewWidth / Math.max(1, viewHeight / 2)
: (viewWidth / 2) / viewHeight;
const obliqueAspect = narrowLayout
? viewWidth / Math.max(1, viewHeight / 2)
: (viewWidth - viewWidth / 2) / viewHeight;
const margin = 0.65;
const halfHeight = Math.max(
TRAY_D / 2 + margin,
(TRAY_W / 2 + margin) / overheadAspect
);
overheadCamera.left = -halfHeight * overheadAspect;
overheadCamera.right = halfHeight * overheadAspect;
overheadCamera.top = halfHeight;
overheadCamera.bottom = -halfHeight;
overheadCamera.updateProjectionMatrix();
obliqueCamera.aspect = obliqueAspect;
obliqueCamera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resize();
function pointerIsOblique(event) {
const rect = renderer.domElement.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
return narrowLayout
? y >= rect.height / 2
: x >= rect.width / 2;
}
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
if (!pointerIsOblique(event)) return;
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.elevation = Math.max(
0.25,
Math.min(1.28, orbit.elevation + dy * 0.005)
);
updateObliqueCamera();
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
if (!pointerIsOblique(event)) return;
event.preventDefault();
orbit.radius = Math.max(
8.5,
Math.min(20, orbit.radius + event.deltaY * 0.01)
);
updateObliqueCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Rendering
// -------------------------------------------------------------------------
function renderViews() {
renderer.setScissorTest(false);
renderer.setViewport(0, 0, viewWidth, viewHeight);
renderer.clear(true, true, true);
renderer.setScissorTest(true);
if (narrowLayout) {
const topHeight = Math.floor(viewHeight / 2);
renderer.setViewport(0, viewHeight - topHeight, viewWidth, topHeight);
renderer.setScissor(0, viewHeight - topHeight, viewWidth, topHeight);
renderer.clear(true, true, true);
renderer.render(scene, overheadCamera);
renderer.setViewport(0, 0, viewWidth, viewHeight - topHeight);
renderer.setScissor(0, 0, viewWidth, viewHeight - topHeight);
renderer.clear(true, true, true);
renderer.render(scene, obliqueCamera);
} else {
const leftWidth = Math.floor(viewWidth / 2);
const rightWidth = viewWidth - leftWidth;
renderer.setViewport(0, 0, leftWidth, viewHeight);
renderer.setScissor(0, 0, leftWidth, viewHeight);
renderer.clear(true, true, true);
renderer.render(scene, overheadCamera);
renderer.setViewport(leftWidth, 0, rightWidth, viewHeight);
renderer.setScissor(leftWidth, 0, rightWidth, viewHeight);
renderer.clear(true, true, true);
renderer.render(scene, obliqueCamera);
}
renderer.setScissorTest(false);
}
basePoints = generateBasePoints(seed);
classPermutation = generatePermutation(seed);
rebuildGrains();
updateControls();
renderComparison();
const clock = new THREE.Clock();
function animate() {
const dt = Math.min(clock.getDelta(), 1 / 30);
if (state === "running") {
updateSimulation(dt);
}
renderViews();
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```