Prompt specification
Build or customize the Three.js 3D scene "Snow grains over a terrain channel" 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: Snow grains over a terrain channel
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/snow-grains-over-a-terrain-channel-x1250
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows snowpack and avalanche terrain. Release a small set of particles down a bounded chute with gravity and damping; label the motion illustrative granular behavior and keep particles inside the demonstration tray. Stylized solid forms.
Working Three.js Starter (snow-grains-over-a-terrain-channel-x1250):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snowpack & Avalanche Terrain</title>
<style>
:root {
color-scheme: dark;
--ink: #ecf7fb;
--muted: #a9bec8;
--panel: rgba(10, 24, 33, 0.82);
--panel-border: rgba(202, 231, 241, 0.16);
--accent: #72d3e8;
--warm: #ffb56b;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #09151d;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#overlay {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
#intro {
position: absolute;
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 20px 22px;
border-radius: 18px;
}
.eyebrow {
margin-bottom: 10px;
color: var(--accent);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 37px);
line-height: 1.05;
letter-spacing: -0.035em;
}
#intro p {
margin: 13px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
#simulation-note {
position: absolute;
top: 22px;
right: 22px;
width: min(330px, calc(100vw - 44px));
padding: 14px 16px;
border-radius: 15px;
font-size: 12px;
line-height: 1.5;
}
.note-row {
display: flex;
align-items: flex-start;
gap: 10px;
}
.note-dot {
flex: 0 0 auto;
width: 9px;
height: 9px;
margin-top: 4px;
border-radius: 50%;
background: var(--warm);
box-shadow: 0 0 0 5px rgba(255, 181, 107, 0.1);
}
#simulation-note strong {
color: #ffe0bd;
}
#legend {
position: absolute;
left: 22px;
bottom: 112px;
padding: 13px 15px;
border-radius: 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.7;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 3px;
}
#controls {
position: absolute;
left: 50%;
bottom: 22px;
display: flex;
align-items: center;
gap: 17px;
width: max-content;
max-width: calc(100vw - 32px);
padding: 12px 14px;
border-radius: 18px;
transform: translateX(-50%);
}
button {
min-height: 42px;
padding: 0 17px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px;
background: rgba(255, 255, 255, 0.07);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition:
background 150ms ease,
transform 150ms ease,
border-color 150ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.13);
border-color: rgba(255, 255, 255, 0.24);
}
button:active {
transform: translateY(1px);
}
#release {
border-color: rgba(114, 211, 232, 0.42);
background: var(--accent);
color: #08222b;
}
#release:hover {
background: #91e2f2;
}
.control-divider {
width: 1px;
height: 38px;
background: rgba(255, 255, 255, 0.11);
}
.slider-control {
display: grid;
grid-template-columns: auto 94px auto;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
input[type="range"] {
width: 94px;
accent-color: var(--accent);
cursor: pointer;
}
output {
min-width: 30px;
color: var(--ink);
font-size: 11px;
text-align: right;
}
#status-panel {
position: absolute;
right: 22px;
bottom: 112px;
min-width: 152px;
padding: 12px 14px;
border-radius: 14px;
text-align: right;
}
#grain-count {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
}
#state {
font-size: 12px;
font-weight: 750;
}
#camera-help {
position: absolute;
right: 22px;
bottom: 24px;
color: rgba(220, 239, 245, 0.6);
font-size: 11px;
letter-spacing: 0.03em;
}
#world-labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
padding: 6px 9px;
border: 1px solid rgba(190, 222, 232, 0.22);
border-radius: 8px;
background: rgba(8, 22, 30, 0.72);
color: #d9edf3;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-50%, -100%);
transition: opacity 120ms linear;
backdrop-filter: blur(8px);
}
.world-label::after {
position: absolute;
top: 100%;
left: 50%;
width: 1px;
height: 15px;
background: rgba(190, 222, 232, 0.45);
content: "";
}
@media (max-width: 820px) {
#intro {
top: 12px;
left: 12px;
width: min(330px, calc(100vw - 24px));
padding: 16px;
}
#simulation-note {
top: auto;
right: 12px;
bottom: 156px;
width: min(280px, calc(100vw - 24px));
}
#legend,
#camera-help {
display: none;
}
#controls {
bottom: 12px;
flex-wrap: wrap;
justify-content: center;
gap: 10px;
width: calc(100vw - 24px);
padding: 10px;
}
.control-divider {
display: none;
}
.slider-control {
grid-template-columns: auto 78px auto;
}
input[type="range"] {
width: 78px;
}
#status-panel {
right: 12px;
bottom: 156px;
}
}
@media (max-width: 520px) {
#intro p {
display: none;
}
#simulation-note {
bottom: 177px;
font-size: 10px;
}
#status-panel {
bottom: 242px;
}
button {
min-height: 38px;
padding: 0 12px;
font-size: 11px;
}
.slider-control {
grid-template-columns: auto 65px auto;
font-size: 9px;
}
input[type="range"] {
width: 65px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive snowpack and avalanche terrain"></canvas>
<div id="overlay">
<section id="intro" class="panel">
<div class="eyebrow">Terrain Study / 01</div>
<h1>Snowpack &<br>Avalanche Terrain</h1>
<p>
Release faceted snow grains from the upper snowpack and observe their
movement through a confined, instrumented chute.
</p>
</section>
<aside id="simulation-note" class="panel">
<div class="note-row">
<span class="note-dot"></span>
<div>
<strong>Illustrative granular behavior.</strong><br>
This demonstration is not a predictive avalanche or engineering
simulation.
</div>
</div>
</aside>
<aside id="legend" class="panel">
<div class="legend-row">
<span class="swatch" style="background:#edf6f8"></span>
Snowpack
</div>
<div class="legend-row">
<span class="swatch" style="background:#91aab4"></span>
Packed chute
</div>
<div class="legend-row">
<span class="swatch" style="background:#ffad62"></span>
Boundary markers
</div>
</aside>
<aside id="status-panel" class="panel" aria-live="polite">
<div id="state">Ready</div>
<div id="grain-count">0 / 28 grains</div>
</aside>
<div id="controls" class="panel">
<button id="release" type="button">Release 28 grains</button>
<button id="reset" type="button">Reset</button>
<span class="control-divider"></span>
<label class="slider-control">
Gravity
<input id="gravity" type="range" min="4" max="14" step="0.1" value="10.5">
<output id="gravity-value">10.5</output>
</label>
<label class="slider-control">
Damping
<input id="damping" type="range" min="0.2" max="3" step="0.05" value="0.85">
<output id="damping-value">0.85</output>
</label>
</div>
<div id="camera-help">Drag to orbit · Scroll to zoom · Double-click to reset view</div>
<div id="world-labels"></div>
</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 canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x09151d);
scene.fog = new THREE.Fog(0x09151d, 25, 48);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const orbit = {
target: new THREE.Vector3(0, 1.25, -0.15),
yaw: 0.51,
pitch: 0.42,
radius: 20.5
};
function updateCamera() {
const horizontalRadius = Math.cos(orbit.pitch) * orbit.radius;
camera.position.set(
orbit.target.x + Math.sin(orbit.yaw) * horizontalRadius,
orbit.target.y + Math.sin(orbit.pitch) * orbit.radius,
orbit.target.z + Math.cos(orbit.yaw) * horizontalRadius
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.yaw = 0.51;
orbit.pitch = 0.42;
orbit.radius = window.innerWidth < 700 ? 25 : 20.5;
updateCamera();
}
const hemisphere = new THREE.HemisphereLight(0xcce9f4, 0x14202a, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff6e8, 3.0);
sun.position.set(-7, 14, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 13;
sun.shadow.camera.bottom = -13;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.00035;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x8bd9ef, 1.25);
rimLight.position.set(8, 7, -10);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0x071119,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.91;
ground.receiveShadow = true;
scene.add(ground);
// -------------------------------------------------------------------------
// Terrain geometry
// -------------------------------------------------------------------------
const TRAY_HALF_WIDTH = 6;
const TRAY_HALF_LENGTH = 8;
const TRAY_BOTTOM = -0.24;
function smoothstep(min, max, value) {
const t = THREE.MathUtils.clamp((value - min) / (max - min), 0, 1);
return t * t * (3 - 2 * t);
}
function terrainHeight(x, z) {
// A broad downhill grade through the demonstration chute.
const downhill = 2.45 - (z + 8) * 0.145;
// Raised, faceted snowpack banks outside the chute.
const bankMask = smoothstep(2.48, 5.35, Math.abs(x));
const irregularity =
0.22 * Math.sin(x * 1.7 + z * 0.43) +
0.14 * Math.cos(z * 1.08 - x * 0.72);
const bankHeight = bankMask * (1.55 + irregularity);
const shallowCrown = 0.025 * x * x;
return downhill + bankHeight + shallowCrown;
}
function surfaceNormal(x, z, target = new THREE.Vector3()) {
const epsilon = 0.055;
const dx =
(terrainHeight(x + epsilon, z) -
terrainHeight(x - epsilon, z)) /
(2 * epsilon);
const dz =
(terrainHeight(x, z + epsilon) -
terrainHeight(x, z - epsilon)) /
(2 * epsilon);
return target.set(-dx, 1, -dz).normalize();
}
function createTerrainTop() {
const nx = 34;
const nz = 44;
const positions = [];
const colors = [];
const indices = [];
const packedColor = new THREE.Color(0x91aab4);
const snowColor = new THREE.Color(0xeaf4f6);
const blueSnowColor = new THREE.Color(0xc8dde4);
const workingColor = new THREE.Color();
for (let iz = 0; iz <= nz; iz++) {
const z = -TRAY_HALF_LENGTH + (iz / nz) * TRAY_HALF_LENGTH * 2;
for (let ix = 0; ix <= nx; ix++) {
const x = -TRAY_HALF_WIDTH + (ix / nx) * TRAY_HALF_WIDTH * 2;
const y = terrainHeight(x, z);
positions.push(x, y, z);
const bankAmount = smoothstep(2.45, 4.25, Math.abs(x));
const variation =
0.04 * Math.sin(x * 2.4 + z * 0.7) +
0.025 * Math.cos(z * 1.8 - x * 1.2);
workingColor.copy(packedColor).lerp(snowColor, bankAmount);
workingColor.lerp(blueSnowColor, variation + 0.15);
colors.push(workingColor.r, workingColor.g, workingColor.b);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.93,
metalness: 0,
flatShading: true,
side: THREE.DoubleSide
});
const terrain = new THREE.Mesh(geometry, material);
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
}
function createTerrainSkirt() {
const positions = [];
function pushTriangle(a, b, c) {
positions.push(...a, ...b, ...c);
}
function pushQuad(a, b, c, d) {
pushTriangle(a, b, c);
pushTriangle(a, c, d);
}
const segments = 32;
for (let i = 0; i < segments; i++) {
const z0 = -8 + (i / segments) * 16;
const z1 = -8 + ((i + 1) / segments) * 16;
for (const x of [-6, 6]) {
pushQuad(
[x, terrainHeight(x, z0), z0],
[x, terrainHeight(x, z1), z1],
[x, TRAY_BOTTOM, z1],
[x, TRAY_BOTTOM, z0]
);
}
}
for (let i = 0; i < segments; i++) {
const x0 = -6 + (i / segments) * 12;
const x1 = -6 + ((i + 1) / segments) * 12;
for (const z of [-8, 8]) {
pushQuad(
[x0, terrainHeight(x0, z), z],
[x1, terrainHeight(x1, z), z],
[x1, TRAY_BOTTOM, z],
[x0, TRAY_BOTTOM, z]
);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
const skirt = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: 0x405966,
roughness: 0.9,
flatShading: true,
side: THREE.DoubleSide
})
);
skirt.castShadow = true;
skirt.receiveShadow = true;
scene.add(skirt);
}
createTerrainTop();
createTerrainSkirt();
const trayBase = new THREE.Mesh(
new THREE.BoxGeometry(12.5, 0.6, 16.6),
new THREE.MeshStandardMaterial({
color: 0x1e313b,
roughness: 0.75,
metalness: 0.12
})
);
trayBase.position.y = -0.55;
trayBase.castShadow = true;
trayBase.receiveShadow = true;
scene.add(trayBase);
// -------------------------------------------------------------------------
// Stylized solid forms: snow pillows, chute barriers, markers, and rocks
// -------------------------------------------------------------------------
const snowPillowGeometry = new THREE.IcosahedronGeometry(1, 1);
const barrierGeometry = new THREE.IcosahedronGeometry(1, 0);
const rockGeometry = new THREE.DodecahedronGeometry(1, 0);
const snowMaterials = [
new THREE.MeshStandardMaterial({
color: 0xeaf5f7,
roughness: 0.95,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0xd5e7ec,
roughness: 0.96,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0xbdd6df,
roughness: 0.96,
flatShading: true
})
];
function addSnowPillow(x, z, sx, sy, sz, rotation, materialIndex) {
const pillow = new THREE.Mesh(
snowPillowGeometry,
snowMaterials[materialIndex % snowMaterials.length]
);
pillow.position.set(x, terrainHeight(x, z) + sy * 0.32, z);
pillow.scale.set(sx, sy, sz);
pillow.rotation.set(
rotation * 0.35,
rotation,
rotation * 0.2
);
pillow.castShadow = true;
pillow.receiveShadow = true;
scene.add(pillow);
}
let pillowSeed = 13;
function seededRandom() {
pillowSeed = (pillowSeed * 16807) % 2147483647;
return (pillowSeed - 1) / 2147483646;
}
for (const side of [-1, 1]) {
for (let i = 0; i < 9; i++) {
const z = -7.1 + i * 1.72 + seededRandom() * 0.35;
const x = side * (3.45 + seededRandom() * 1.75);
addSnowPillow(
x,
z,
0.75 + seededRandom() * 0.75,
0.48 + seededRandom() * 0.48,
0.9 + seededRandom() * 0.7,
seededRandom() * Math.PI,
i
);
}
}
// Repeated low-poly barriers visually define the confined chute.
for (const side of [-1, 1]) {
for (let i = 0; i < 9; i++) {
const z = -6.85 + i * 1.73;
const x = side * 2.72;
const barrier = new THREE.Mesh(
barrierGeometry,
snowMaterials[(i + (side > 0 ? 1 : 0)) % snowMaterials.length]
);
barrier.position.set(x, terrainHeight(x, z) + 0.26, z);
barrier.scale.set(0.48, 0.7, 0.87);
barrier.rotation.set(0.08 * i, 0.35 * i + side * 0.2, side * 0.04);
barrier.castShadow = true;
barrier.receiveShadow = true;
scene.add(barrier);
}
}
const stakeMaterial = new THREE.MeshStandardMaterial({
color: 0xffad62,
roughness: 0.62,
metalness: 0.05
});
const stakeGeometry = new THREE.CylinderGeometry(0.045, 0.055, 0.82, 6);
const capGeometry = new THREE.OctahedronGeometry(0.095, 0);
for (const side of [-1, 1]) {
for (let i = 0; i < 5; i++) {
const z = -5.9 + i * 3.15;
const x = side * 2.77;
const ground = terrainHeight(x, z);
const stake = new THREE.Mesh(stakeGeometry, stakeMaterial);
stake.position.set(x, ground + 0.95, z);
stake.castShadow = true;
scene.add(stake);
const cap = new THREE.Mesh(capGeometry, stakeMaterial);
cap.position.set(x, ground + 1.38, z);
cap.castShadow = true;
scene.add(cap);
}
}
// A fractured cornice at the release area.
for (let i = 0; i < 6; i++) {
const x = -1.75 + i * 0.7;
const z = -7.25 + (i % 2) * 0.14;
const cornice = new THREE.Mesh(
barrierGeometry,
snowMaterials[i % snowMaterials.length]
);
cornice.position.set(x, terrainHeight(x, z) + 0.35, z);
cornice.scale.set(0.56, 0.52 + (i % 3) * 0.08, 0.62);
cornice.rotation.set(0.1, i * 0.4, 0.06 * (i % 2));
cornice.castShadow = true;
cornice.receiveShadow = true;
scene.add(cornice);
}
// Dark faceted rocks add scale and reinforce the stylized solid aesthetic.
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x445b64,
roughness: 1,
flatShading: true
});
for (const side of [-1, 1]) {
for (let i = 0; i < 4; i++) {
const z = -5.7 + i * 3.6;
const x = side * (4.55 + seededRandom() * 0.75);
const rock = new THREE.Mesh(rockGeometry, rockMaterial);
rock.position.set(x, terrainHeight(x, z) + 0.18, z);
rock.scale.set(
0.32 + seededRandom() * 0.25,
0.28 + seededRandom() * 0.22,
0.4 + seededRandom() * 0.35
);
rock.rotation.set(seededRandom(), seededRandom(), seededRandom());
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
}
// Muted direction dashes embedded in the packed chute.
const dashMaterial = new THREE.MeshStandardMaterial({
color: 0x5c929f,
roughness: 0.85
});
const dashGeometry = new THREE.BoxGeometry(0.085, 0.025, 0.58);
for (let i = 0; i < 10; i++) {
const z = -5.5 + i * 1.22;
const dash = new THREE.Mesh(dashGeometry, dashMaterial);
dash.position.set(0, terrainHeight(0, z) + 0.025, z);
dash.rotation.x = 0.144;
dash.receiveShadow = true;
scene.add(dash);
}
// Catch dam at the lower end of the chute.
const catchDam = new THREE.Mesh(
new THREE.BoxGeometry(5.2, 0.58, 0.38),
new THREE.MeshStandardMaterial({
color: 0x49616b,
roughness: 0.9,
flatShading: true
})
);
catchDam.position.set(0, terrainHeight(0, 7.15) + 0.24, 7.15);
catchDam.castShadow = true;
catchDam.receiveShadow = true;
scene.add(catchDam);
// -------------------------------------------------------------------------
// World-space HTML labels
// -------------------------------------------------------------------------
const labelsRoot = document.querySelector("#world-labels");
const worldLabels = [];
function addWorldLabel(text, position) {
const element = document.createElement("div");
element.className = "world-label";
element.textContent = text;
labelsRoot.appendChild(element);
worldLabels.push({ element, position });
}
addWorldLabel(
"Snowpack",
new THREE.Vector3(-4.55, terrainHeight(-4.55, -2.8) + 1.0, -2.8)
);
addWorldLabel(
"Confined chute",
new THREE.Vector3(0, terrainHeight(0, -1.8) + 0.55, -1.8)
);
addWorldLabel(
"Catch berm",
new THREE.Vector3(0, terrainHeight(0, 7.15) + 0.85, 7.15)
);
const projected = new THREE.Vector3();
function updateWorldLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const label of worldLabels) {
projected.copy(label.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.12 &&
Math.abs(projected.y) < 1.12;
label.element.style.opacity = visible ? "0.92" : "0";
label.element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
label.element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
}
}
// -------------------------------------------------------------------------
// Illustrative granular particle system
// -------------------------------------------------------------------------
const MAX_GRAINS = 28;
const CHUTE_LIMIT = 2.43;
const Z_MIN = -7.35;
const Z_MAX = 7.02;
const particleGeometry = new THREE.IcosahedronGeometry(1, 0);
const particleMaterials = [
0xf4fbfd,
0xdcecf2,
0xbdd7e1,
0x94bac8
].map(
(color) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.74,
metalness: 0,
flatShading: true
})
);
const particles = [];
for (let i = 0; i < MAX_GRAINS; i++) {
const mesh = new THREE.Mesh(
particleGeometry,
particleMaterials[i % particleMaterials.length]
);
mesh.visible = false;
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
particles.push({
mesh,
active: false,
position: new THREE.Vector3(),
velocity: new THREE.Vector3(),
radius: 0.16 + Math.random() * 0.08,
spin: Math.random() * Math.PI * 2
});
}
let gravity = 10.5;
let damping = 0.85;
const releaseButton = document.querySelector("#release");
const resetButton = document.querySelector("#reset");
const stateElement = document.querySelector("#state");
const countElement = document.querySelector("#grain-count");
const gravityInput = document.querySelector("#gravity");
const dampingInput = document.querySelector("#damping");
const gravityValue = document.querySelector("#gravity-value");
const dampingValue = document.querySelector("#damping-value");
gravityInput.addEventListener("input", () => {
gravity = Number(gravityInput.value);
gravityValue.value = gravity.toFixed(1);
});
dampingInput.addEventListener("input", () => {
damping = Number(dampingInput.value);
dampingValue.value = damping.toFixed(2);
});
function resetParticles() {
for (const particle of particles) {
particle.active = false;
particle.mesh.visible = false;
}
stateElement.textContent = "Ready";
countElement.textContent = `0 / ${MAX_GRAINS} grains`;
}
function releaseParticles() {
resetParticles();
particles.forEach((particle, index) => {
const x = (Math.random() - 0.5) * 2.45;
const z = -6.85 + (Math.random() - 0.5) * 0.5;
const floor = terrainHeight(x, z);
particle.active = true;
particle.mesh.visible = true;
particle.position.set(
x,
floor + 0.48 + Math.random() * 1.25,
z
);
particle.velocity.set(
(Math.random() - 0.5) * 0.75,
-0.1 + Math.random() * 0.25,
0.22 + Math.random() * 0.42
);
particle.mesh.position.copy(particle.position);
particle.mesh.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
});
stateElement.textContent = "Released";
countElement.textContent = `${MAX_GRAINS} / ${MAX_GRAINS} grains`;
}
releaseButton.addEventListener("click", releaseParticles);
resetButton.addEventListener("click", resetParticles);
const normal = new THREE.Vector3();
const gravityVector = new THREE.Vector3();
const tangentialGravity = new THREE.Vector3();
const separation = new THREE.Vector3();
const relativeVelocity = new THREE.Vector3();
function resolveFloor(particle, restitution = 0.08) {
const height = terrainHeight(particle.position.x, particle.position.z);
surfaceNormal(particle.position.x, particle.position.z, normal);
const minimumY = height + particle.radius;
if (particle.position.y < minimumY) {
particle.position.y = minimumY;
const normalVelocity = particle.velocity.dot(normal);
if (normalVelocity < 0) {
particle.velocity.addScaledVector(
normal,
-(1 + restitution) * normalVelocity
);
}
}
}
function resolveBoundaries(particle) {
const xLimit = CHUTE_LIMIT - particle.radius * 0.8;
const zLimit = Z_MAX - particle.radius;
if (particle.position.x > xLimit) {
particle.position.x = xLimit;
particle.velocity.x = -Math.abs(particle.velocity.x) * 0.38;
} else if (particle.position.x < -xLimit) {
particle.position.x = -xLimit;
particle.velocity.x = Math.abs(particle.velocity.x) * 0.38;
}
if (particle.position.z > zLimit) {
particle.position.z = zLimit;
particle.velocity.z = -Math.abs(particle.velocity.z) * 0.24;
} else if (particle.position.z < Z_MIN + particle.radius) {
particle.position.z = Z_MIN + particle.radius;
particle.velocity.z = Math.abs(particle.velocity.z) * 0.24;
}
}
function solveParticleContacts() {
for (let i = 0; i < particles.length; i++) {
const a = particles[i];
if (!a.active) continue;
for (let j = i + 1; j < particles.length; j++) {
const b = particles[j];
if (!b.active) continue;
separation.subVectors(b.position, a.position);
const minimumDistance = (a.radius + b.radius) * 0.9;
const distanceSquared = separation.lengthSq();
if (distanceSquared >= minimumDistance * minimumDistance) continue;
let distance = Math.sqrt(distanceSquared);
if (distance < 0.0001) {
separation.set(
Math.random() - 0.5,
Math.random() - 0.5,
Math.random() - 0.5
);
distance = separation.length();
}
separation.multiplyScalar(1 / distance);
const overlap = (minimumDistance - distance) * 0.5;
a.position.addScaledVector(separation, -overlap);
b.position.addScaledVector(separation, overlap);
relativeVelocity.subVectors(b.velocity, a.velocity);
const separatingVelocity = relativeVelocity.dot(separation);
if (separatingVelocity < 0) {
const impulse = -separatingVelocity * 0.48;
a.velocity.addScaledVector(separation, -impulse);
b.velocity.addScaledVector(separation, impulse);
}
}
}
}
function physicsStep(deltaTime) {
for (const particle of particles) {
if (!particle.active) continue;
const height = terrainHeight(
particle.position.x,
particle.position.z
);
const grounded =
particle.position.y <= height + particle.radius + 0.035;
if (grounded) {
particle.position.y = height + particle.radius;
surfaceNormal(particle.position.x, particle.position.z, normal);
const normalVelocity = particle.velocity.dot(normal);
if (normalVelocity < 0) {
particle.velocity.addScaledVector(
normal,
-1.08 * normalVelocity
);
}
// Project gravity onto the local slope to create downhill motion.
gravityVector.set(0, -gravity, 0);
tangentialGravity
.copy(gravityVector)
.addScaledVector(
normal,
-gravityVector.dot(normal)
);
particle.velocity.addScaledVector(
tangentialGravity,
deltaTime
);
particle.velocity.multiplyScalar(
Math.exp(-damping * deltaTime)
);
} else {
particle.velocity.y -= gravity * deltaTime;
// Slight air damping, much weaker than contact damping.
particle.velocity.multiplyScalar(
Math.exp(-damping * 0.08 * deltaTime)
);
}
particle.position.addScaledVector(
particle.velocity,
deltaTime
);
resolveFloor(particle);
resolveBoundaries(particle);
}
solveParticleContacts();
// Contact corrections can move a grain slightly; keep it legal again.
for (const particle of particles) {
if (!particle.active) continue;
resolveFloor(particle, 0.03);
resolveBoundaries(particle);
}
}
// -------------------------------------------------------------------------
// Direct camera controls — no external control modules
// -------------------------------------------------------------------------
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
orbit.yaw -= deltaX * 0.005;
orbit.pitch = THREE.MathUtils.clamp(
orbit.pitch + deltaY * 0.004,
0.16,
1.08
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
13,
30
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Resize and animation loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
resetCamera();
const fixedStep = 1 / 90;
let accumulator = 0;
let previousTime = performance.now();
let statusTimer = 0;
function animate(now) {
requestAnimationFrame(animate);
const frameDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
accumulator += frameDelta;
while (accumulator >= fixedStep) {
physicsStep(fixedStep);
accumulator -= fixedStep;
}
let averageSpeed = 0;
let activeCount = 0;
for (const particle of particles) {
if (!particle.active) continue;
activeCount++;
averageSpeed += particle.velocity.length();
particle.mesh.position.copy(particle.position);
particle.mesh.rotation.x +=
(particle.velocity.z * 0.8 + particle.spin * 0.12) * frameDelta;
particle.mesh.rotation.z -=
particle.velocity.x * 0.9 * frameDelta;
}
if (activeCount > 0) {
averageSpeed /= activeCount;
statusTimer += frameDelta;
if (statusTimer > 0.45) {
statusTimer = 0;
stateElement.textContent =
averageSpeed < 0.12 ? "Settled" : "Moving";
}
}
updateWorldLabels();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
// Start with one small release so the demonstration is immediately visible.
const autoRelease = window.setTimeout(releaseParticles, 900);
releaseButton.addEventListener("click", () => {
clearTimeout(autoRelease);
});
</script>
</body>
</html>
```