Prompt specification
Build or customize the Three.js 3D scene "Load-position comparison on branches" 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: Load-position comparison on branches
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/load-position-comparison-on-branches-x1090
Scene Description Prompt:
Move identical fruit weights along low-poly branches, showing exaggerated lever-related deflection in a schematic model. Three.js from cdnjs, one HTML file.
Working Three.js Starter (load-position-comparison-on-branches-x1090):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruit Lever Rig</title>
<style>
:root {
--ink: #203235;
--muted: #627276;
--paper: #f4f1e8;
--panel: rgba(250, 248, 240, 0.92);
--line: rgba(32, 50, 53, 0.14);
--teal: #287477;
--orange: #e87532;
--red: #c44e38;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e7dd;
color: var(--ink);
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;
outline: none;
}
.title-block {
position: fixed;
top: 24px;
left: 26px;
z-index: 3;
max-width: 430px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 8px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(30px, 4.5vw, 58px);
line-height: 0.96;
letter-spacing: -0.055em;
font-weight: 780;
}
.title-block p {
max-width: 360px;
margin: 15px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
.panel {
position: fixed;
top: 16px;
right: 16px;
z-index: 5;
width: 342px;
max-height: calc(100vh - 32px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 20px;
background: var(--panel);
box-shadow:
0 18px 50px rgba(39, 53, 52, 0.14),
inset 0 0 0 1px rgba(32, 50, 53, 0.05);
backdrop-filter: blur(16px) saturate(1.1);
}
.panel-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
margin-bottom: 16px;
}
.panel-title {
margin: 0;
font-size: 17px;
font-weight: 780;
letter-spacing: -0.02em;
}
.panel-subtitle {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.badge {
flex: none;
padding: 6px 8px;
border-radius: 999px;
background: rgba(40, 116, 119, 0.1);
color: var(--teal);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-label {
display: flex;
align-items: center;
gap: 8px;
margin: 17px 0 11px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-label::after {
content: "";
flex: 1;
height: 1px;
background: var(--line);
}
.control {
margin: 0 0 14px;
}
.control-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
font-size: 12px;
}
.control-row label {
font-weight: 680;
}
output {
color: var(--teal);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 750;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
appearance: none;
background: linear-gradient(
90deg,
rgba(40, 116, 119, 0.8),
rgba(40, 116, 119, 0.18)
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid var(--paper);
border-radius: 50%;
appearance: none;
background: var(--teal);
box-shadow: 0 1px 5px rgba(22, 48, 49, 0.28);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid var(--paper);
border-radius: 50%;
background: var(--teal);
box-shadow: 0 1px 5px rgba(22, 48, 49, 0.28);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 37px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.58);
color: var(--ink);
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
background 150ms ease,
transform 150ms ease,
border-color 150ms ease;
}
button:hover:not(:disabled) {
border-color: rgba(40, 116, 119, 0.35);
background: rgba(40, 116, 119, 0.09);
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:disabled {
opacity: 0.38;
cursor: default;
}
.primary {
border-color: transparent;
background: var(--teal);
color: #f7f5ec;
}
.primary:hover:not(:disabled) {
border-color: transparent;
background: #1f6265;
}
.check-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 11px;
color: var(--muted);
font-size: 11px;
cursor: pointer;
user-select: none;
}
.check-row input {
accent-color: var(--teal);
}
.load-list {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.38);
}
.load-row {
display: grid;
grid-template-columns: 32px 1fr 1fr 1fr;
align-items: center;
min-height: 43px;
padding: 0 11px;
border-bottom: 1px solid var(--line);
font-size: 10px;
transition: background 150ms ease;
}
.load-row:last-child {
border-bottom: 0;
}
.load-row.active {
background: rgba(232, 117, 50, 0.1);
}
.branch-id {
font-weight: 850;
color: var(--orange);
}
.load-row span:not(.branch-id) {
text-align: right;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.load-head {
color: var(--muted);
font-size: 9px;
font-weight: 750;
text-transform: uppercase;
}
.equation {
padding: 12px 13px;
border-radius: 12px;
background: #263f42;
color: #f5f1e6;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.65;
}
.equation strong {
color: #f2a16b;
font-weight: 700;
}
.summary {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.summary-card {
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.34);
}
.summary-card span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.summary-card strong {
display: block;
margin-top: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
}
.instructions {
position: fixed;
left: 24px;
bottom: 20px;
z-index: 3;
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
max-width: min(560px, calc(100vw - 48px));
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.55);
border-radius: 12px;
background: rgba(248, 246, 237, 0.74);
color: var(--muted);
font-size: 10px;
backdrop-filter: blur(10px);
pointer-events: none;
}
.instructions b {
color: var(--ink);
}
.branch-label {
position: fixed;
z-index: 2;
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 8px;
background: rgba(250, 248, 240, 0.82);
color: var(--ink);
box-shadow: 0 4px 14px rgba(32, 50, 53, 0.1);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 750;
white-space: nowrap;
pointer-events: none;
transform: translate(-50%, -50%);
}
.branch-label .label-key {
margin-right: 5px;
color: var(--orange);
}
.toast {
position: fixed;
left: 50%;
bottom: 28px;
z-index: 10;
padding: 10px 14px;
border-radius: 999px;
background: rgba(32, 50, 53, 0.92);
color: white;
font-size: 11px;
font-weight: 700;
opacity: 0;
transform: translate(-50%, 12px);
transition:
opacity 180ms ease,
transform 180ms ease;
pointer-events: none;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
.title-block {
top: 17px;
left: 17px;
max-width: calc(100vw - 34px);
}
.title-block p {
display: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
max-height: 43vh;
padding: 14px;
border-radius: 16px;
}
.panel-header {
margin-bottom: 10px;
}
.instructions {
display: none;
}
.branch-label {
font-size: 8px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive fruit lever simulation"></canvas>
<header class="title-block">
<div class="eyebrow">Mechanics study / 01</div>
<h1>Fruit lever rig</h1>
<p>
Identical hanging weights reveal how load position changes the moment,
the branch rotation, and the visible deflection.
</p>
</header>
<aside class="panel">
<div class="panel-header">
<div>
<h2 class="panel-title">Experiment controls</h2>
<p class="panel-subtitle">All fruit have the same mass.</p>
</div>
<div class="badge">Interactive</div>
</div>
<div class="section-label">Load properties</div>
<div class="control">
<div class="control-row">
<label for="mass">Identical fruit mass</label>
<output id="massValue">1.25 kg</output>
</div>
<input id="mass" type="range" min="0.25" max="3" step="0.25" value="1.25">
</div>
<div class="control">
<div class="control-row">
<label for="stiffness">Branch stiffness, k</label>
<output id="stiffnessValue">240 N·m/rad</output>
</div>
<input id="stiffness" type="range" min="120" max="500" step="10" value="240">
</div>
<div class="control">
<div class="control-row">
<label for="exaggeration">Deflection exaggeration</label>
<output id="exaggerationValue">2.2×</output>
</div>
<input id="exaggeration" type="range" min="1" max="3.5" step="0.1" value="2.2">
</div>
<div class="button-row">
<button class="primary" id="addFruit">+ Add fruit</button>
<button id="removeFruit" disabled>Remove selected</button>
<button id="resetWeights">Reset weights</button>
<button id="resetView">Reset view</button>
</div>
<label class="check-row">
<input id="guides" type="checkbox" checked>
Show unloaded reference and lever arms
</label>
<div class="section-label">Live load ledger</div>
<div class="load-list">
<div class="load-row load-head">
<span>Branch</span>
<span>Fruit</span>
<span>Moment</span>
<span>Angle</span>
</div>
<div class="load-row" id="rowA">
<span class="branch-id">A</span>
<span id="countA">0</span>
<span id="momentA">0.0 N·m</span>
<span id="angleA">0.0°</span>
</div>
<div class="load-row" id="rowB">
<span class="branch-id">B</span>
<span id="countB">0</span>
<span id="momentB">0.0 N·m</span>
<span id="angleB">0.0°</span>
</div>
</div>
<div class="section-label">Model</div>
<div class="equation">
<div>M = Σ (m · g · ℓ)</div>
<div>θ<sub>visible</sub> = (M / k) × <strong id="equationExaggeration">2.2</strong></div>
<div style="margin-top:5px;color:#b9c7c4;font-size:10px">
ℓ = horizontal distance from pivot
</div>
</div>
<div class="summary">
<div class="summary-card">
<span>Total moment</span>
<strong id="totalMoment">0.0 N·m</strong>
</div>
<div class="summary-card">
<span>Active fruit</span>
<strong id="fruitCount">0</strong>
</div>
</div>
</aside>
<div class="instructions">
<span><b>Drag fruit</b> along its branch</span>
<span><b>Drag background</b> to orbit</span>
<span><b>Scroll</b> to zoom</span>
</div>
<div class="toast" id="toast"></div>
<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 toast = document.querySelector("#toast");
const ui = {
mass: document.querySelector("#mass"),
stiffness: document.querySelector("#stiffness"),
exaggeration: document.querySelector("#exaggeration"),
massValue: document.querySelector("#massValue"),
stiffnessValue: document.querySelector("#stiffnessValue"),
exaggerationValue: document.querySelector("#exaggerationValue"),
equationExaggeration: document.querySelector("#equationExaggeration"),
guides: document.querySelector("#guides"),
addFruit: document.querySelector("#addFruit"),
removeFruit: document.querySelector("#removeFruit"),
resetWeights: document.querySelector("#resetWeights"),
resetView: document.querySelector("#resetView"),
totalMoment: document.querySelector("#totalMoment"),
fruitCount: document.querySelector("#fruitCount")
};
let renderer;
try {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
} catch (error) {
document.body.innerHTML =
'<p style="padding:30px;font:16px system-ui">WebGL could not be initialized.</p>';
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
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(0xe9e7dd);
scene.fog = new THREE.Fog(0xe9e7dd, 12, 27);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const controls = {
target: new THREE.Vector3(0, 2.05, 0),
yaw: 0.58,
pitch: 0.36,
radius: 10.2
};
function updateCamera() {
const cp = Math.cos(controls.pitch);
camera.position.set(
controls.target.x + controls.radius * cp * Math.sin(controls.yaw),
controls.target.y + controls.radius * Math.sin(controls.pitch),
controls.target.z + controls.radius * cp * Math.cos(controls.yaw)
);
camera.lookAt(controls.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xfff8e9, 0x61706c, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0d3, 3.4);
sun.position.set(-4.5, 8.5, 5.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -6;
sun.shadow.camera.right = 6;
sun.shadow.camera.top = 7;
sun.shadow.camera.bottom = -4;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 22;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9cc8cc, 1.1);
fill.position.set(5, 3, -5);
scene.add(fill);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xe5e1d5,
roughness: 0.97,
metalness: 0
});
const ground = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.13;
ground.receiveShadow = true;
scene.add(ground);
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(4.25, 4.45, 0.18, 36),
new THREE.MeshStandardMaterial({
color: 0xf0ede2,
roughness: 0.85
})
);
platform.position.y = -0.08;
platform.receiveShadow = true;
platform.castShadow = true;
scene.add(platform);
const grid = new THREE.GridHelper(8, 16, 0x8d9893, 0xb6b9af);
grid.position.y = 0.018;
grid.material.transparent = true;
grid.material.opacity = 0.23;
scene.add(grid);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.43, 0.61, 3.25, 7, 1, false),
new THREE.MeshStandardMaterial({
color: 0x5f4436,
roughness: 0.96,
flatShading: true
})
);
trunk.position.y = 1.625;
trunk.castShadow = true;
trunk.receiveShadow = true;
scene.add(trunk);
const collar = new THREE.Mesh(
new THREE.CylinderGeometry(0.28, 0.28, 0.31, 12),
new THREE.MeshStandardMaterial({
color: 0x294f52,
roughness: 0.48,
metalness: 0.12,
flatShading: true
})
);
collar.rotation.x = Math.PI / 2;
collar.position.set(0, 2.58, 0);
collar.castShadow = true;
scene.add(collar);
const guides = new THREE.Group();
scene.add(guides);
const branches = [
{
id: "A",
root: new THREE.Vector3(0, 2.58, 0),
direction: new THREE.Vector3(-1, 0.025, 0.08).normalize(),
length: 3.35,
radius: 0.145,
color: 0x694b39,
angle: 0,
angularVelocity: 0,
targetAngle: 0,
moment: 0,
fruits: [],
segments: 14,
sides: 6
},
{
id: "B",
root: new THREE.Vector3(0, 2.69, -0.03),
direction: new THREE.Vector3(1, 0.012, -0.14).normalize(),
length: 3.2,
radius: 0.135,
color: 0x76533f,
angle: 0,
angularVelocity: 0,
targetAngle: 0,
moment: 0,
fruits: [],
segments: 14,
sides: 6
}
];
branches.forEach((branch) => {
branch.horizontalLength =
branch.length *
Math.hypot(branch.direction.x, branch.direction.z);
const vertexCount = (branch.segments + 1) * branch.sides;
branch.positions = new Float32Array(vertexCount * 3);
branch.colors = new Float32Array(vertexCount * 3);
branch.points = Array.from(
{ length: branch.segments + 1 },
() => new THREE.Vector3()
);
const indices = [];
for (let i = 0; i < branch.segments; i++) {
for (let j = 0; j < branch.sides; j++) {
const a = i * branch.sides + j;
const b = i * branch.sides + ((j + 1) % branch.sides);
const c = (i + 1) * branch.sides + j;
const d = (i + 1) * branch.sides + ((j + 1) % branch.sides);
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(branch.positions, 3)
);
geometry.setAttribute(
"color",
new THREE.BufferAttribute(branch.colors, 3)
);
geometry.setIndex(indices);
branch.geometry = geometry;
branch.mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.96,
flatShading: true
})
);
branch.mesh.castShadow = true;
branch.mesh.receiveShadow = true;
branch.mesh.frustumCulled = false;
scene.add(branch.mesh);
const baseColor = new THREE.Color(branch.color);
const color = new THREE.Color();
for (let i = 0; i <= branch.segments; i++) {
for (let j = 0; j < branch.sides; j++) {
const index = (i * branch.sides + j) * 3;
const shade = 0.9 + ((i + j) % 3) * 0.045;
color.copy(baseColor).multiplyScalar(shade);
branch.colors[index] = color.r;
branch.colors[index + 1] = color.g;
branch.colors[index + 2] = color.b;
}
}
geometry.attributes.color.needsUpdate = true;
const referenceGeometry = new THREE.BufferGeometry().setFromPoints([
branch.root.clone(),
branch.root
.clone()
.addScaledVector(branch.direction, branch.length)
]);
branch.referenceLine = new THREE.Line(
referenceGeometry,
new THREE.LineDashedMaterial({
color: 0x4a6e70,
dashSize: 0.12,
gapSize: 0.095,
transparent: true,
opacity: 0.48
})
);
branch.referenceLine.computeLineDistances();
guides.add(branch.referenceLine);
const label = document.createElement("div");
label.className = "branch-label";
label.innerHTML =
`<span class="label-key">${branch.id}</span><span class="label-load">0.0 N·m</span>`;
document.body.appendChild(label);
branch.label = label;
branch.labelLoad = label.querySelector(".label-load");
});
function branchPoint(branch, t, target = new THREE.Vector3()) {
const distance = branch.length * t;
const drop =
branch.length *
(Math.sin(branch.angle) * t + 0.09 * branch.angle * t * t);
return target.set(
branch.root.x + branch.direction.x * distance,
branch.root.y + branch.direction.y * distance - drop,
branch.root.z + branch.direction.z * distance
);
}
const up = new THREE.Vector3(0, 1, 0);
const fallbackAxis = new THREE.Vector3(0, 0, 1);
const tangent = new THREE.Vector3();
const side = new THREE.Vector3();
const binormal = new THREE.Vector3();
function updateBranchGeometry(branch) {
for (let i = 0; i <= branch.segments; i++) {
branchPoint(branch, i / branch.segments, branch.points[i]);
}
for (let i = 0; i <= branch.segments; i++) {
const previous = branch.points[Math.max(0, i - 1)];
const next = branch.points[Math.min(branch.segments, i + 1)];
tangent.subVectors(next, previous).normalize();
side.crossVectors(tangent, up);
if (side.lengthSq() < 0.0001) {
side.crossVectors(tangent, fallbackAxis);
}
side.normalize();
binormal.crossVectors(side, tangent).normalize();
const t = i / branch.segments;
const radius = branch.radius * (1 - 0.56 * t);
for (let j = 0; j < branch.sides; j++) {
const angle = (j / branch.sides) * Math.PI * 2;
const index = (i * branch.sides + j) * 3;
const cos = Math.cos(angle) * radius;
const sin = Math.sin(angle) * radius;
branch.positions[index] =
branch.points[i].x + side.x * cos + binormal.x * sin;
branch.positions[index + 1] =
branch.points[i].y + side.y * cos + binormal.y * sin;
branch.positions[index + 2] =
branch.points[i].z + side.z * cos + binormal.z * sin;
}
}
branch.geometry.attributes.position.needsUpdate = true;
branch.geometry.computeVertexNormals();
}
const fruitGeometry = new THREE.IcosahedronGeometry(0.225, 1);
const stemGeometry = new THREE.CylinderGeometry(0.025, 0.034, 0.19, 5);
const stemMaterial = new THREE.MeshStandardMaterial({
color: 0x4e3929,
roughness: 1,
flatShading: true
});
const leafGeometry = new THREE.CircleGeometry(0.105, 4);
const leafMaterial = new THREE.MeshStandardMaterial({
color: 0x47764b,
roughness: 0.95,
side: THREE.DoubleSide,
flatShading: true
});
const ringGeometry = new THREE.TorusGeometry(0.272, 0.017, 4, 24);
const fruits = [];
const fruitPickMeshes = [];
let fruitId = 0;
let selectedFruit = null;
function createFruit(branch, t) {
const id = fruitId++;
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xe87532,
roughness: 0.62,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const body = new THREE.Mesh(fruitGeometry, bodyMaterial);
body.castShadow = true;
body.receiveShadow = true;
body.userData.fruitId = id;
group.add(body);
const stem = new THREE.Mesh(stemGeometry, stemMaterial);
stem.position.y = 0.305;
stem.castShadow = true;
group.add(stem);
const leaf = new THREE.Mesh(leafGeometry, leafMaterial);
leaf.position.set(0.075, 0.365, 0);
leaf.rotation.set(0.35, 0.2, -0.65);
group.add(leaf);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0x2b7779,
transparent: true,
opacity: 0.9
});
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.visible = false;
group.add(ring);
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.055, 7, 5),
new THREE.MeshStandardMaterial({
color: 0x2b7779,
roughness: 0.45
})
);
marker.castShadow = true;
const forceArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(),
0.65,
0xc44e38,
0.13,
0.08
);
forceArrow.line.material.transparent = true;
forceArrow.line.material.opacity = 0.78;
forceArrow.cone.material.transparent = true;
forceArrow.cone.material.opacity = 0.82;
const leverGeometry = new THREE.BufferGeometry();
leverGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const leverLine = new THREE.Line(
leverGeometry,
new THREE.LineBasicMaterial({
color: 0x2b7779,
transparent: true,
opacity: 0.5
})
);
leverLine.frustumCulled = false;
guides.add(leverLine);
const record = {
id,
branch,
t,
group,
body,
bodyMaterial,
ring,
ringMaterial,
marker,
forceArrow,
leverLine
};
body.userData.fruit = record;
scene.add(group);
scene.add(marker);
scene.add(forceArrow);
branch.fruits.push(record);
fruits.push(record);
fruitPickMeshes.push(body);
return record;
}
function removeFruit(record) {
if (!record) return;
const branch = record.branch;
branch.fruits = branch.fruits.filter((fruit) => fruit !== record);
fruits.splice(fruits.indexOf(record), 1);
const pickIndex = fruitPickMeshes.indexOf(record.body);
if (pickIndex !== -1) fruitPickMeshes.splice(pickIndex, 1);
scene.remove(record.group);
scene.remove(record.marker);
scene.remove(record.forceArrow);
guides.remove(record.leverLine);
record.bodyMaterial.dispose();
record.ringMaterial.dispose();
record.marker.geometry.dispose();
record.marker.material.dispose();
record.leverLine.geometry.dispose();
record.leverLine.material.dispose();
if (selectedFruit === record) {
selectedFruit = null;
}
}
function selectFruit(record) {
if (selectedFruit && selectedFruit !== record) {
selectedFruit.ring.visible = false;
}
selectedFruit = record;
if (selectedFruit) {
selectedFruit.ring.visible = true;
}
ui.removeFruit.disabled = !selectedFruit;
updateUI();
}
function resetWeights() {
[...fruits].forEach(removeFruit);
createFruit(branches[0], 0.32);
createFruit(branches[0], 0.68);
createFruit(branches[1], 0.43);
createFruit(branches[1], 0.82);
selectFruit(null);
}
function addFruit() {
if (fruits.length >= 10) {
showToast("Maximum of 10 fruit weights");
return;
}
let branch = selectedFruit
? selectedFruit.branch
: branches[0].fruits.length <= branches[1].fruits.length
? branches[0]
: branches[1];
const candidates = [0.23, 0.38, 0.53, 0.68, 0.83, 0.94];
let bestT = candidates[0];
let bestDistance = -1;
for (const candidate of candidates) {
let distance = Infinity;
for (const fruit of branch.fruits) {
distance = Math.min(distance, Math.abs(candidate - fruit.t));
}
if (distance > bestDistance) {
bestDistance = distance;
bestT = candidate;
}
}
const record = createFruit(branch, bestT);
selectFruit(record);
showToast(`Fruit added to branch ${branch.id}`);
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(showToast.timeout);
showToast.timeout = setTimeout(() => toast.classList.remove("show"), 1800);
}
const gravity = 9.81;
function stepPhysics(dt) {
const mass = Number(ui.mass.value);
const stiffness = Number(ui.stiffness.value);
const exaggeration = Number(ui.exaggeration.value);
for (const branch of branches) {
branch.moment = 0;
for (const fruit of branch.fruits) {
const leverArm = branch.horizontalLength * fruit.t;
branch.moment += mass * gravity * leverArm;
}
branch.targetAngle = Math.min(
0.7,
(branch.moment / stiffness) * exaggeration
);
const acceleration =
(branch.targetAngle - branch.angle) * 55 -
branch.angularVelocity * 10.5;
branch.angularVelocity += acceleration * dt;
branch.angularVelocity *= 0.996;
branch.angle += branch.angularVelocity * dt;
branch.angle = THREE.MathUtils.clamp(branch.angle, 0, 0.82);
}
}
const tempPoint = new THREE.Vector3();
const referenceEnd = new THREE.Vector3();
function updateVisuals() {
branches.forEach(updateBranchGeometry);
for (const fruit of fruits) {
branchPoint(fruit.branch, fruit.t, tempPoint);
fruit.group.position.set(
tempPoint.x,
tempPoint.y - 0.395,
tempPoint.z
);
fruit.marker.position.copy(tempPoint);
fruit.forceArrow.position.set(
tempPoint.x + 0.34,
tempPoint.y + 0.78,
tempPoint.z
);
referenceEnd
.copy(fruit.branch.root)
.addScaledVector(fruit.branch.direction, fruit.branch.length * fruit.t);
const positions = fruit.leverLine.geometry.attributes.position.array;
positions[0] = fruit.branch.root.x;
positions[1] = fruit.branch.root.y;
positions[2] = fruit.branch.root.z;
positions[3] = referenceEnd.x;
positions[4] = referenceEnd.y;
positions[5] = referenceEnd.z;
fruit.leverLine.geometry.attributes.position.needsUpdate = true;
}
}
const projected = new THREE.Vector3();
function updateLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const branch of branches) {
branchPoint(branch, 0.22, projected);
projected.y += 0.35;
projected.project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.1 &&
projected.x < 1.1 &&
projected.y > -1.1 &&
projected.y < 1.1;
branch.label.style.display = visible ? "block" : "none";
if (visible) {
branch.label.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
branch.label.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
}
}
}
function updateUI() {
const mass = Number(ui.mass.value);
const stiffness = Number(ui.stiffness.value);
const exaggeration = Number(ui.exaggeration.value);
ui.massValue.textContent = `${mass.toFixed(2).replace(/0$/, "")} kg`;
ui.stiffnessValue.textContent = `${stiffness} N·m/rad`;
ui.exaggerationValue.textContent = `${exaggeration.toFixed(1)}×`;
ui.equationExaggeration.textContent = exaggeration.toFixed(1);
ui.fruitCount.textContent = String(fruits.length);
ui.removeFruit.disabled = !selectedFruit;
let total = 0;
branches.forEach((branch) => {
total += branch.moment;
document.querySelector(`#count${branch.id}`).textContent =
String(branch.fruits.length);
document.querySelector(`#moment${branch.id}`).textContent =
`${branch.moment.toFixed(1)} N·m`;
document.querySelector(`#angle${branch.id}`).textContent =
`${THREE.MathUtils.radToDeg(branch.angle).toFixed(1)}°`;
branch.labelLoad.textContent = `${branch.moment.toFixed(1)} N·m`;
document
.querySelector(`#row${branch.id}`)
.classList.toggle(
"active",
selectedFruit && selectedFruit.branch === branch
);
});
ui.totalMoment.textContent = `${total.toFixed(1)} N·m`;
}
ui.mass.addEventListener("input", updateUI);
ui.stiffness.addEventListener("input", updateUI);
ui.exaggeration.addEventListener("input", updateUI);
ui.guides.addEventListener("change", () => {
guides.visible = ui.guides.checked;
});
ui.addFruit.addEventListener("click", addFruit);
ui.removeFruit.addEventListener("click", () => {
if (selectedFruit) {
removeFruit(selectedFruit);
selectFruit(null);
}
});
ui.resetWeights.addEventListener("click", () => {
resetWeights();
showToast("Initial weights restored");
});
ui.resetView.addEventListener("click", () => {
controls.yaw = 0.58;
controls.pitch = 0.36;
controls.radius = 10.2;
controls.target.set(0, 2.05, 0);
updateCamera();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let interactionMode = null;
let lastPointerX = 0;
let lastPointerY = 0;
function setPointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function closestTOnBranch(branch) {
let closestT = 0;
let closestDistance = Infinity;
const point = new THREE.Vector3();
for (let i = 0; i <= 70; i++) {
const t = i / 70;
branchPoint(branch, t, point);
const distance = raycaster.ray.distanceSqToPoint(point);
if (distance < closestDistance) {
closestDistance = distance;
closestT = t;
}
}
return closestT;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
setPointer(event);
const hits = raycaster.intersectObjects(fruitPickMeshes, false);
if (hits.length) {
const fruit = hits[0].object.userData.fruit;
selectFruit(fruit);
interactionMode = "fruit";
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
} else {
selectFruit(null);
interactionMode = "orbit";
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
}
event.preventDefault();
});
canvas.addEventListener("pointermove", (event) => {
setPointer(event);
if (interactionMode === "fruit" && selectedFruit) {
selectedFruit.t = closestTOnBranch(selectedFruit.branch);
return;
}
if (interactionMode === "orbit") {
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
controls.yaw -= deltaX * 0.006;
controls.pitch = THREE.MathUtils.clamp(
controls.pitch + deltaY * 0.005,
0.1,
1.18
);
updateCamera();
return;
}
const hits = raycaster.intersectObjects(fruitPickMeshes, false);
canvas.style.cursor = hits.length ? "grab" : "default";
});
function endPointer(event) {
interactionMode = null;
canvas.style.cursor = "default";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
controls.radius = THREE.MathUtils.clamp(
controls.radius * Math.exp(event.deltaY * 0.001),
6.4,
16
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetWeights();
updateVisuals();
updateUI();
let previousTime = performance.now();
let uiElapsed = 0;
renderer.setAnimationLoop((time) => {
const dt = Math.min((time - previousTime) / 1000, 0.033);
previousTime = time;
stepPhysics(dt);
updateVisuals();
renderer.render(scene, camera);
updateLabels();
uiElapsed += dt;
if (uiElapsed > 0.08) {
updateUI();
uiElapsed = 0;
}
});
</script>
</body>
</html>
```