Prompt specification
Build or customize the Three.js 3D scene "Rough and smooth track comparison" 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: Rough and smooth track comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rough-and-smooth-track-comparison-x1382
Scene Description Prompt:
Launch identical blocks with equal initial speeds along two tracks with different model friction coefficients; compare stopping distances without changing mass or initial conditions. Build this with Three.js from cdnjs as a stylized scene in one HTML file.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Start both tracks at 8.0 m/s with the distinct coefficients 0.25 and 0.45. Compute both stopping positions from the same motion model and stop each vehicle only when its speed reaches zero.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (rough-and-smooth-track-comparison-x1382):
```html
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Comparação de distâncias de parada</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: #0b1728;
--panel-2: #101f33;
--line: rgba(164, 197, 225, 0.16);
--text: #edf5fb;
--muted: #9db1c5;
--a: #43dfd5;
--b: #ff805f;
--good: #9ae66e;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button {
font: inherit;
}
#app {
width: 100vw;
height: 100dvh;
display: grid;
grid-template-columns: minmax(0, 1fr) clamp(300px, 25vw, 370px);
background: var(--bg);
}
#stage {
position: relative;
min-width: 0;
overflow: hidden;
isolation: isolate;
}
#canvas-host {
position: absolute;
inset: 0;
}
#canvas-host canvas {
display: block;
width: 100%;
height: 100%;
}
.stage-header {
position: absolute;
z-index: 3;
top: 0;
left: 0;
right: 0;
padding: 22px 26px 70px;
pointer-events: none;
background: linear-gradient(180deg, rgba(7, 17, 31, 0.96) 0%, rgba(7, 17, 31, 0.72) 58%, transparent 100%);
}
.eyebrow {
color: var(--a);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 7px;
max-width: 760px;
font-size: clamp(1.55rem, 3vw, 2.65rem);
line-height: 1.03;
letter-spacing: -0.035em;
}
.subtitle {
margin: 0;
max-width: 720px;
color: var(--muted);
font-size: clamp(0.78rem, 1.3vw, 0.95rem);
line-height: 1.45;
}
.scene-note {
position: absolute;
z-index: 3;
left: 22px;
bottom: 78px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(8, 20, 35, 0.82);
color: #b9cad9;
font-size: 0.7rem;
pointer-events: none;
backdrop-filter: blur(8px);
}
#summary {
position: absolute;
z-index: 4;
left: 20px;
right: 20px;
bottom: 18px;
min-height: 48px;
display: flex;
align-items: center;
justify-content: center;
padding: 12px 18px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(8, 18, 31, 0.91);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.22);
color: #dce8f2;
text-align: center;
font-size: clamp(0.76rem, 1.25vw, 0.92rem);
line-height: 1.4;
backdrop-filter: blur(10px);
}
#summary strong {
color: #fff;
}
#panel {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 22px;
border-left: 1px solid var(--line);
background:
radial-gradient(circle at 90% 0%, rgba(67, 223, 213, 0.08), transparent 32%),
var(--panel);
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel-heading h2 {
margin: 0 0 4px;
font-size: 1.05rem;
letter-spacing: -0.02em;
}
.panel-heading p {
margin: 0;
color: var(--muted);
font-size: 0.75rem;
line-height: 1.4;
}
.clock {
flex: 0 0 auto;
min-width: 66px;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 9px;
background: #0a1423;
text-align: center;
}
.clock span {
display: block;
color: var(--muted);
font-size: 0.62rem;
text-transform: uppercase;
letter-spacing: 0.1em;
}
.clock strong {
display: block;
margin-top: 2px;
font-variant-numeric: tabular-nums;
font-size: 1.02rem;
}
.card {
--accent: var(--a);
position: relative;
overflow: hidden;
margin-bottom: 12px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 13px;
background: linear-gradient(145deg, rgba(255, 255, 255, 0.025), rgba(255, 255, 255, 0.01)), var(--panel-2);
}
.card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--accent);
}
.card.b { --accent: var(--b); }
.card-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.identity {
display: flex;
align-items: center;
gap: 10px;
}
.badge {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border-radius: 10px;
background: var(--accent);
color: #06131d;
font-size: 1.15rem;
font-weight: 900;
box-shadow: 0 0 22px color-mix(in srgb, var(--accent) 24%, transparent);
}
.mu {
font-size: 0.92rem;
font-weight: 750;
}
.mu span {
color: var(--muted);
font-weight: 500;
}
.state {
padding: 5px 7px;
border-radius: 999px;
border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
background: color-mix(in srgb, var(--accent) 9%, transparent);
color: var(--accent);
font-size: 0.58rem;
font-weight: 850;
letter-spacing: 0.08em;
}
.readout {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
padding: 7px 0;
border-top: 1px solid rgba(164, 197, 225, 0.09);
}
.readout span {
color: var(--muted);
font-size: 0.72rem;
}
.readout strong {
font-size: 1.08rem;
font-variant-numeric: tabular-nums;
}
.readout strong small {
color: var(--muted);
font-size: 0.65rem;
font-weight: 600;
}
.progress {
height: 5px;
overflow: hidden;
margin-top: 8px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.07);
}
.progress > div {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--accent);
transition: width 80ms linear;
}
.conditions {
margin-top: 17px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(4, 12, 23, 0.32);
}
.conditions h3 {
margin: 0 0 10px;
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.11em;
color: #c8d7e4;
}
.condition-list {
display: grid;
gap: 8px;
margin: 0;
}
.condition-list div {
display: flex;
justify-content: space-between;
gap: 12px;
color: var(--muted);
font-size: 0.73rem;
}
.condition-list strong {
color: var(--text);
font-weight: 700;
text-align: right;
}
.formula {
margin-top: 12px;
padding: 10px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
color: #cbd9e6;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.69rem;
line-height: 1.55;
text-align: center;
}
.verification {
margin-top: 10px;
color: var(--muted);
font-size: 0.68rem;
line-height: 1.45;
}
.verification strong { color: var(--good); }
.controls {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
margin-top: 16px;
}
.controls button {
min-height: 42px;
border: 1px solid var(--line);
border-radius: 9px;
padding: 9px 14px;
background: #14243a;
color: var(--text);
font-weight: 750;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease, border-color 120ms ease;
}
.controls button:hover {
transform: translateY(-1px);
border-color: rgba(164, 197, 225, 0.35);
background: #192d46;
}
.controls button:focus-visible {
outline: 2px solid var(--a);
outline-offset: 2px;
}
.controls .primary {
border-color: transparent;
background: var(--a);
color: #06131d;
}
.controls .primary:hover {
background: #6ce9e1;
}
.schematic {
margin: 12px 0 0;
color: #7f95aa;
font-size: 0.65rem;
line-height: 1.45;
text-align: center;
}
@media (max-width: 820px) {
body { overflow: auto; }
#app {
height: auto;
min-height: 100dvh;
grid-template-columns: 1fr;
grid-template-rows: minmax(410px, 60dvh) auto;
}
#panel {
overflow: visible;
border-left: 0;
border-top: 1px solid var(--line);
padding: 18px;
}
.stage-header { padding: 17px 18px 55px; }
.scene-note { left: 14px; bottom: 72px; }
#summary { left: 12px; right: 12px; bottom: 12px; }
}
@media (max-width: 460px) {
.stage-header { padding-inline: 14px; }
h1 { font-size: 1.45rem; }
.subtitle { font-size: 0.72rem; }
.scene-note { font-size: 0.61rem; }
.controls { grid-template-columns: 1fr 1fr; }
}
</style>
</head>
<body>
<div id="app">
<main id="stage" aria-label="Cena tridimensional com dois blocos em trilhos paralelos">
<div id="canvas-host"></div>
<header class="stage-header">
<div class="eyebrow">Laboratório de movimento · atrito constante</div>
<h1>Qual coeficiente de atrito produz a menor parada?</h1>
<p class="subtitle">
A e B partem juntos, com a mesma massa e a mesma velocidade inicial.
A única diferença entre os modelos é o coeficiente de atrito, μ.
</p>
</header>
<div class="scene-note">Geometria esquemática em escala · 1 unidade da cena = 1 metro</div>
<div id="summary" role="status" aria-live="polite">
Preparando o lançamento simultâneo…
</div>
</main>
<aside id="panel" aria-label="Dados e controles do ensaio">
<div class="panel-heading">
<div>
<h2>Telemetria dos blocos</h2>
<p>Valores calculados a partir da mesma simulação que move a geometria.</p>
</div>
<div class="clock">
<span>tempo</span>
<strong id="clock">0,00 s</strong>
</div>
</div>
<article class="card a" aria-label="Dados do bloco A">
<div class="card-top">
<div class="identity">
<div class="badge">A</div>
<div class="mu">μ = 0,25 <span>· atrito menor</span></div>
</div>
<div class="state" id="stateA">AGUARDANDO</div>
</div>
<div class="readout">
<span>Velocidade atual</span>
<strong><b id="vA">8,00</b> <small>m/s</small></strong>
</div>
<div class="readout">
<span>Distância percorrida</span>
<strong><b id="dA">0,00</b> <small>m</small></strong>
</div>
<div class="readout">
<span>Parada calculada no modelo</span>
<strong><b id="sA">13,05</b> <small>m</small></strong>
</div>
<div class="progress" aria-hidden="true"><div id="pA"></div></div>
</article>
<article class="card b" aria-label="Dados do bloco B">
<div class="card-top">
<div class="identity">
<div class="badge">B</div>
<div class="mu">μ = 0,45 <span>· atrito maior</span></div>
</div>
<div class="state" id="stateB">AGUARDANDO</div>
</div>
<div class="readout">
<span>Velocidade atual</span>
<strong><b id="vB">8,00</b> <small>m/s</small></strong>
</div>
<div class="readout">
<span>Distância percorrida</span>
<strong><b id="dB">0,00</b> <small>m</small></strong>
</div>
<div class="readout">
<span>Parada calculada no modelo</span>
<strong><b id="sB">7,25</b> <small>m</small></strong>
</div>
<div class="progress" aria-hidden="true"><div id="pB"></div></div>
</article>
<section class="conditions" aria-label="Condições e modelo">
<h3>Condições mantidas</h3>
<div class="condition-list">
<div><span>Massa de A e B</span><strong>1,0 kg cada</strong></div>
<div><span>Velocidade inicial</span><strong>8,0 m/s para ambos</strong></div>
<div><span>Deslocamento</span><strong>Horizontal, sem inclinação</strong></div>
<div><span>Constante gravitacional</span><strong>9,81 m/s²</strong></div>
<div><span>Modelo de atrito</span><strong>Coeficiente constante</strong></div>
</div>
<div class="formula">
x(t) = v₀t − ½μgt²<br>
d<sub>parada</sub> = v₀² / (2μg)
</div>
<div class="verification" id="verification">
A verificação será exibida quando os dois blocos pararem.
</div>
</section>
<div class="controls">
<button class="primary" id="action" type="button">Iniciar</button>
<button id="reset" type="button">Reiniciar</button>
</div>
<p class="schematic">
Modelo sintético para comparação qualitative e quantitativa.
Os blocos, trilhos e marcas de distância são elementos esquemáticos;
as posições 3D e os cartões usam a mesma equação instantânea.
</p>
</aside>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const host = document.getElementById("canvas-host");
const numberFormat = new Intl.NumberFormat("pt-BR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
const V0 = 8.0;
const G = 9.81;
const MASS = 1.0;
const blocks = [
{ id: "A", mu: 0.25, color: 0x43dfd5, css: "#43dfd5", z: 1.18 },
{ id: "B", mu: 0.45, color: 0xff805f, css: "#ff805f", z: -1.18 }
];
for (const block of blocks) {
block.stopTime = V0 / (block.mu * G);
block.stopDistance = (V0 * V0) / (2 * block.mu * G);
}
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 24, 46);
const camera = new THREE.OrthographicCamera(-9, 9, 7, -7, 0.1, 100);
camera.position.set(6.3, 11.5, 14.5);
camera.lookAt(6.3, 0.2, 0);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x07111f, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
host.appendChild(renderer.domElement);
const ambient = new THREE.HemisphereLight(0xbfe7ff, 0x172033, 2.0);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-4, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4adfd7, 1.6);
rimLight.position.set(11, 7, -10);
scene.add(rimLight);
const materials = {
base: new THREE.MeshStandardMaterial({ color: 0x102238, roughness: 0.82, metalness: 0.05 }),
track: new THREE.MeshStandardMaterial({ color: 0x182b42, roughness: 0.78, metalness: 0.08 }),
rail: new THREE.MeshStandardMaterial({ color: 0x3b5269, roughness: 0.58, metalness: 0.32 }),
start: new THREE.MeshStandardMaterial({ color: 0xf2f7fb, roughness: 0.35 }),
ruler: new THREE.MeshBasicMaterial({ color: 0x8096aa, transparent: true, opacity: 0.65 })
};
function addBox(width, height, depth, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function makeTag(text, foreground, background = "rgba(7,17,31,0.88)") {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 144;
const ctx = canvas.getContext("2d");
roundedRect(ctx, 4, 4, 632, 136, 22);
ctx.fillStyle = background;
ctx.fill();
ctx.strokeStyle = "rgba(210,231,246,0.20)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = foreground;
ctx.font = "800 48px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 320, 73);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
function addSprite(sprite, x, y, z, worldWidth) {
sprite.position.set(x, y, z);
sprite.scale.set(worldWidth, worldWidth * 144 / 640, 1);
scene.add(sprite);
return sprite;
}
// Bancada esquemática: unidades do mundo equivalem a metros.
const base = addBox(16.5, 0.30, 6.65, materials.base, 6.3, -0.22, 0);
base.receiveShadow = true;
const gridMaterial = new THREE.LineBasicMaterial({
color: 0x38506a,
transparent: true,
opacity: 0.28
});
const gridPoints = [];
for (let x = -1; x <= 14; x += 1) {
gridPoints.push(new THREE.Vector3(x, -0.055, -3.15), new THREE.Vector3(x, -0.055, 3.15));
}
for (let z = -3; z <= 3; z += 0.75) {
gridPoints.push(new THREE.Vector3(-1.5, -0.055, z), new THREE.Vector3(14.1, -0.055, z));
}
const gridGeometry = new THREE.BufferGeometry().setFromPoints(gridPoints);
scene.add(new THREE.LineSegments(gridGeometry, gridMaterial));
for (const block of blocks) {
const track = addBox(14.55, 0.10, 1.28, materials.track, 6.75, 0, block.z);
track.receiveShadow = true;
const tint = new THREE.MeshStandardMaterial({
color: block.color,
transparent: true,
opacity: 0.11,
roughness: 0.72,
metalness: 0.05
});
addBox(14.35, 0.018, 0.34, tint, 6.75, 0.063, block.z);
addBox(14.55, 0.045, 0.035, materials.rail, 6.75, 0.07, block.z - 0.58);
addBox(14.55, 0.045, 0.035, materials.rail, 6.75, 0.07, block.z + 0.58);
}
// Linha de partida comum e régua métrica.
addBox(0.045, 0.035, 4.18, materials.start, 0, 0.09, 0);
addBox(14.25, 0.025, 0.025, materials.ruler, 7.125, 0.005, 2.73);
for (let meter = 0; meter <= 14; meter++) {
const major = meter % 2 === 0;
addBox(0.025, 0.026, major ? 0.29 : 0.17, materials.ruler, meter, 0.008, 2.67);
if (major) {
const label = makeTag(`${meter} m`, "#d8e5ef", "rgba(7,17,31,0.68)");
addSprite(label, meter, 0.28, 2.93, 0.92);
}
}
const startTag = makeTag("PARTIDA · 8,0 m/s", "#f3f8fc");
addSprite(startTag, 0.65, 1.65, 2.74, 2.35);
for (const block of blocks) {
const tag = makeTag(`${block.id} · μ ${block.mu.toFixed(2).replace(".", ",")}`, block.css);
addSprite(tag, 1.05, 1.18, block.z, 2.15);
}
// Blocos geometricamente idênticos; apenas a identificação cromática muda.
for (const block of blocks) {
const group = new THREE.Group();
group.position.set(0, 0, block.z);
scene.add(group);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: block.color,
roughness: 0.34,
metalness: 0.16,
emissive: block.color,
emissiveIntensity: 0.12
});
const body = new THREE.Mesh(new THREE.BoxGeometry(0.66, 0.54, 0.66), bodyMaterial);
body.position.y = 0.34;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const capMaterial = new THREE.MeshStandardMaterial({
color: 0xf3fbff,
roughness: 0.28,
metalness: 0.18
});
const cap = new THREE.Mesh(new THREE.BoxGeometry(0.36, 0.035, 0.36), capMaterial);
cap.position.y = 0.626;
cap.castShadow = true;
group.add(cap);
const letter = makeTag(block.id, "#07111f", block.css);
letter.position.set(0, 0.95, 0);
letter.scale.set(0.56, 0.126, 1);
group.add(letter);
const trailMaterial = new THREE.MeshBasicMaterial({
color: block.color,
transparent: true,
opacity: 0.28,
depthWrite: false
});
const trail = new THREE.Mesh(new THREE.BoxGeometry(1, 0.018, 0.16), trailMaterial);
trail.position.set(0, 0.085, block.z);
trail.scale.x = 0.001;
scene.add(trail);
const stopRingMaterial = new THREE.MeshBasicMaterial({
color: block.color,
transparent: true,
opacity: 0.85,
depthTest: false
});
const stopRing = new THREE.Mesh(new THREE.TorusGeometry(0.43, 0.025, 8, 48), stopRingMaterial);
stopRing.rotation.x = Math.PI / 2;
stopRing.position.set(0, 0.10, block.z);
stopRing.visible = false;
stopRing.renderOrder = 12;
scene.add(stopRing);
const resultLabel = makeTag(
`${block.id} · ${numberFormat.format(block.stopDistance)} m`,
block.css,
"rgba(7,17,31,0.94)"
);
resultLabel.position.set(block.stopDistance, 1.25, block.z);
resultLabel.scale.set(2.05, 0.461, 1);
resultLabel.visible = false;
scene.add(resultLabel);
block.group = group;
block.trail = trail;
block.stopRing = stopRing;
block.resultLabel = resultLabel;
}
const state = {
phase: "ready",
elapsed: 0,
lastFrame: performance.now()
};
const dom = {
clock: document.getElementById("clock"),
summary: document.getElementById("summary"),
action: document.getElementById("action"),
reset: document.getElementById("reset"),
verification: document.getElementById("verification")
};
function sample(block, time) {
const localTime = Math.min(time, block.stopTime);
const velocity = time >= block.stopTime
? 0
: V0 - block.mu * G * localTime;
const distance = V0 * localTime - 0.5 * block.mu * G * localTime * localTime;
return { velocity, distance, stopped: time >= block.stopTime };
}
function updateSceneAndCards() {
const samples = blocks.map(block => sample(block, state.elapsed));
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
const data = samples[i];
// A posição 3D é exatamente a mesma distância exibida no cartão.
block.group.position.x = data.distance;
block.trail.position.x = data.distance / 2;
block.trail.scale.x = Math.max(data.distance, 0.001);
block.trail.visible = data.distance > 0.015;
block.stopRing.position.x = data.distance;
block.stopRing.visible = data.stopped;
block.resultLabel.position.x = data.distance;
block.resultLabel.visible = data.stopped;
document.getElementById(`v${block.id}`).textContent = numberFormat.format(data.velocity);
document.getElementById(`d${block.id}`).textContent = numberFormat.format(data.distance);
document.getElementById(`s${block.id}`).textContent = numberFormat.format(block.stopDistance);
document.getElementById(`p${block.id}`).style.width =
`${Math.min(100, 100 * data.distance / block.stopDistance)}%`;
const stateLabel = document.getElementById(`state${block.id}`);
if (data.stopped) {
stateLabel.textContent = "PARADO";
} else if (state.phase === "running") {
stateLabel.textContent = "EM MOVIMENTO";
} else if (state.phase === "paused") {
stateLabel.textContent = "PAUSADO";
} else {
stateLabel.textContent = "AGUARDANDO";
}
}
dom.clock.textContent = `${numberFormat.format(state.elapsed)} s`;
if (state.phase === "ready") {
dom.summary.innerHTML = "Pronto: <strong>A e B partem juntos</strong> a 8,0 m/s, com massas iguais e μ diferente.";
dom.action.textContent = "Iniciar";
} else if (state.phase === "running") {
dom.summary.innerHTML =
`Em movimento · t = <strong>${numberFormat.format(state.elapsed)} s</strong> · ` +
`A: <strong>${numberFormat.format(samples[0].distance)} m</strong> · ` +
`B: <strong>${numberFormat.format(samples[1].distance)} m</strong>`;
dom.action.textContent = "Pausar";
} else if (state.phase === "paused") {
dom.summary.innerHTML = "Ensaio pausado · a posição e a telemetria permanecem sincronizadas.";
dom.action.textContent = "Retomar";
} else {
const ratio = blocks[0].stopDistance / blocks[1].stopDistance;
const reduction = 100 * (1 - blocks[1].stopDistance / blocks[0].stopDistance);
dom.summary.innerHTML =
`Resultado · A: <strong>${numberFormat.format(samples[0].distance)} m</strong> · ` +
`B: <strong>${numberFormat.format(samples[1].distance)} m</strong> · ` +
`A percorre <strong>${numberFormat.format(ratio)}×</strong> a distância de B.`;
dom.action.textContent = "Executar novamente";
dom.verification.innerHTML =
`<strong>Verificação concluída.</strong> Os blocos pararam nas mesmas posições marcadas na cena: ` +
`A = ${numberFormat.format(samples[0].distance)} m e B = ${numberFormat.format(samples[1].distance)} m. ` +
`Como μ<sub>B</sub> = 1,8 μ<sub>A</sub>, B percorre ${numberFormat.format(reduction)}% menos distância.`;
}
}
function startSimulation() {
if (state.phase === "finished") {
state.elapsed = 0;
state.phase = "running";
} else if (state.phase === "ready" || state.phase === "paused") {
state.phase = "running";
}
state.lastFrame = performance.now();
updateSceneAndCards();
}
function pauseSimulation() {
if (state.phase === "running") {
state.phase = "paused";
updateSceneAndCards();
}
}
function resetSimulation(autoRun = false) {
state.elapsed = 0;
state.phase = autoRun ? "running" : "ready";
state.lastFrame = performance.now();
updateSceneAndCards();
}
dom.action.addEventListener("click", () => {
if (state.phase === "running") {
pauseSimulation();
} else {
startSimulation();
}
});
dom.reset.addEventListener("click", () => resetSimulation(false));
document.addEventListener("keydown", event => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
if (state.phase === "running") pauseSimulation();
else startSimulation();
}
if (event.key.toLowerCase() === "r" && event.target === document.body) {
resetSimulation(false);
}
});
function resize() {
const width = Math.max(1, host.clientWidth);
const height = Math.max(1, host.clientHeight);
const aspect = width / height;
const halfWidth = 8.9;
const halfHeight = Math.max(5.25, halfWidth / aspect);
camera.left = -halfWidth;
camera.right = halfWidth;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(host);
resize();
updateSceneAndCards();
// Lançamento automático após uma breve leitura da cena.
const autoStartTimer = setTimeout(() => {
if (state.phase === "ready") startSimulation();
}, 900);
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min(0.05, Math.max(0, (now - state.lastFrame) / 1000));
state.lastFrame = now;
if (state.phase === "running") {
state.elapsed += dt;
const finalTime = Math.max(...blocks.map(block => block.stopTime));
if (state.elapsed >= finalTime) {
state.elapsed = finalTime;
state.phase = "finished";
clearTimeout(autoStartTimer);
}
}
updateSceneAndCards();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```