Prompt specification
Build or customize the Three.js 3D scene "Equivalent fractions tile alignment" 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: Equivalent fractions tile alignment
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/equivalent-fractions-tile-alignment-x1694
Scene Description Prompt:
Please use Three.js from cdnjs for a stylized scene based on this idea: equivalent fractions tile alignment. Place one-half, two-fourths, and four-eighths bars with equal total lengths; align their boundaries to show equal quantities despite different partition counts. Return one self-contained HTML file.
Technical checks: Make all three bars the same length. Show the divisions and matching shaded portions for 1/2, 2/4, and 4/8 clearly from the teaching view.
Return one complete HTML document that works with the cdnjs Three.js r160 module inside a sandbox with scripts allowed. Make the requested subject visible at the default camera. Use procedural assets and local button handlers. Do not use native form submission, pointer lock, external assets or runtime requests other than Three.js.
Working Three.js Starter (equivalent-fractions-tile-alignment-x1694):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f5f0e7">
<link rel="icon" href="data:,">
<title>Equivalência de Frações — 1/2, 2/4 e 4/8</title>
<style>
:root {
color-scheme: light;
--ink: #17243d;
--muted: #627087;
--paper: #f7f2e9;
--panel: rgba(255, 255, 255, 0.88);
--teal: #20c9aa;
--blue: #5684f7;
--coral: #f47765;
--gold: #d99a28;
--border: rgba(23, 36, 61, 0.13);
--shadow: 0 16px 42px rgba(35, 48, 75, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.title-card {
position: fixed;
top: 24px;
left: 26px;
z-index: 5;
width: min(520px, calc(100vw - 52px));
pointer-events: none;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 9px;
padding: 7px 11px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.72);
color: #53627a;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.eyebrow::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--gold);
box-shadow: 0 0 0 4px rgba(217, 154, 40, 0.15);
}
h1 {
margin: 0;
max-width: 500px;
font-size: clamp(27px, 3.4vw, 47px);
line-height: 1.04;
letter-spacing: -0.045em;
text-wrap: balance;
}
.title-card p {
margin: 11px 0 0;
color: var(--muted);
font-size: clamp(13px, 1.4vw, 16px);
line-height: 1.5;
}
.equivalence-key {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 15px;
}
.equivalence-key span {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.78);
color: #44536b;
font-size: 12px;
font-weight: 750;
box-shadow: 0 5px 16px rgba(36, 48, 72, 0.06);
}
.equivalence-key i {
width: 9px;
height: 9px;
border-radius: 3px;
background: var(--dot);
}
.info-card {
position: fixed;
top: 24px;
right: 26px;
z-index: 6;
width: 260px;
padding: 16px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
pointer-events: none;
}
.info-card .label {
color: #8792a4;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.info-card h2 {
margin: 5px 0 6px;
font-size: 18px;
line-height: 1.2;
letter-spacing: -0.02em;
}
.info-card p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.info-card .hint {
display: flex;
gap: 8px;
align-items: center;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--border);
color: #53627a;
font-size: 11px;
font-weight: 700;
}
.info-card .hint::before {
content: "↗";
display: grid;
place-items: center;
width: 23px;
height: 23px;
flex: 0 0 auto;
border-radius: 8px;
background: #eef2f7;
color: var(--ink);
font-size: 14px;
}
.toolbar-wrap {
position: fixed;
z-index: 10;
left: 50%;
bottom: 20px;
width: max-content;
max-width: calc(100vw - 28px);
transform: translateX(-50%);
}
.toolbar {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 7px;
padding: 8px;
border: 1px solid var(--border);
border-radius: 17px;
background: rgba(255, 255, 255, 0.91);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
}
button {
appearance: none;
min-height: 40px;
padding: 9px 13px;
border: 1px solid transparent;
border-radius: 11px;
background: #eef1f5;
color: #3c4a62;
font: inherit;
font-size: 12px;
font-weight: 780;
cursor: pointer;
transition: transform 140ms ease, background 140ms ease, color 140ms ease,
box-shadow 140ms ease;
}
button:hover {
transform: translateY(-1px);
background: #e5eaf1;
}
button:active {
transform: translateY(0);
}
button:focus-visible {
outline: 3px solid rgba(86, 132, 247, 0.32);
outline-offset: 2px;
}
button.active {
background: var(--ink);
color: white;
box-shadow: 0 6px 16px rgba(23, 36, 61, 0.22);
}
button.accent {
background: #fff1cf;
color: #81550d;
}
button.accent[aria-pressed="true"] {
background: var(--gold);
color: white;
}
.status {
position: fixed;
z-index: 8;
left: 26px;
bottom: 91px;
max-width: min(560px, calc(100vw - 52px));
padding: 11px 14px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(255, 255, 255, 0.91);
color: #4f5e74;
box-shadow: 0 10px 28px rgba(35, 48, 75, 0.11);
font-size: 12px;
font-weight: 700;
line-height: 1.4;
opacity: 0;
transform: translateY(8px);
transition: opacity 180ms ease, transform 180ms ease;
pointer-events: none;
}
.status.visible {
opacity: 1;
transform: translateY(0);
}
.status.success {
border-color: rgba(28, 163, 126, 0.27);
background: rgba(239, 253, 247, 0.94);
color: #176b57;
}
.status.error {
border-color: rgba(205, 70, 70, 0.3);
background: rgba(255, 240, 240, 0.95);
color: #963b3b;
}
@media (max-width: 820px) {
.title-card {
top: 17px;
left: 17px;
width: calc(100vw - 34px);
}
.title-card p {
display: none;
}
.equivalence-key {
margin-top: 11px;
}
.info-card {
top: auto;
right: 14px;
bottom: 151px;
width: min(250px, calc(100vw - 28px));
padding: 12px;
}
.info-card .hint {
display: none;
}
.status {
left: 14px;
bottom: 151px;
max-width: calc(100vw - 28px);
}
.toolbar-wrap {
bottom: 12px;
}
button {
min-height: 38px;
padding: 8px 10px;
font-size: 11px;
}
}
@media (max-height: 620px) {
.equivalence-key,
.info-card .hint {
display: none;
}
.title-card p {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="title-card">
<div class="eyebrow">Frações equivalentes</div>
<h1>A mesma quantidade, diferentes divisões</h1>
<p>
As três barras têm exatamente o mesmo comprimento. As divisões mostram
maneiras diferentes de representar <strong>50%</strong>.
</p>
<div class="equivalence-key" aria-label="Equações equivalentes">
<span><i style="--dot:var(--teal)"></i>1/2 = 1 × 1/2</span>
<span><i style="--dot:var(--blue)"></i>2/4 = 2 × 1/4</span>
<span><i style="--dot:var(--coral)"></i>4/8 = 4 × 1/8</span>
</div>
</header>
<aside class="info-card" aria-live="polite">
<div class="label">Peça selecionada</div>
<h2 id="selection-title">Clique em uma parte</h2>
<p id="selection-copy">
Cada porção tem um valor próprio. As partes de cada linha somam sempre
a mesma quantidade.
</p>
<div class="hint">Arraste para girar · role para aproximar</div>
</aside>
<div id="status" class="status" role="status" aria-live="polite"></div>
<div class="toolbar-wrap">
<nav class="toolbar" aria-label="Controles da cena">
<button type="button" class="active" data-camera="overview" aria-pressed="true">
Visão geral
</button>
<button type="button" data-camera="perspective" aria-pressed="false">
Perspectiva
</button>
<button type="button" data-camera="top" aria-pressed="false">
Topo
</button>
<button type="button" id="guides-button" class="accent" aria-pressed="true">
Guias: ligadas
</button>
<button type="button" id="validate-button">
Verificar geometria
</button>
</nav>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const mount = document.getElementById("scene");
const statusElement = document.getElementById("status");
const selectionTitle = document.getElementById("selection-title");
const selectionCopy = document.getElementById("selection-copy");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf7f2e9);
scene.fog = new THREE.Fog(0xf7f2e9, 24, 48);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
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.12;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Cena 3D interativa com barras equivalentes de frações"
);
mount.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xfffdf6, 0x8793aa, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff2d9, 3.1);
keyLight.position.set(-5, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xc9ddff, 1.2);
fillLight.position.set(8, 6, -7);
scene.add(fillLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(50, 40),
new THREE.MeshStandardMaterial({ color: 0xeee8dd, roughness: 0.96 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.52;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(32, 32, 0x9aa5b5, 0xb8b3aa);
grid.position.y = -0.505;
grid.material.transparent = true;
grid.material.opacity = 0.17;
scene.add(grid);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(14.9, 0.28, 8.7),
new THREE.MeshStandardMaterial({
color: 0xf2ece1,
roughness: 0.88,
metalness: 0.02
})
);
platform.position.set(0, -0.36, 0.05);
platform.receiveShadow = true;
platform.castShadow = true;
scene.add(platform);
const platformEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(platform.geometry),
new THREE.LineBasicMaterial({
color: 0xc7beae,
transparent: true,
opacity: 0.72
})
);
platformEdges.position.copy(platform.position);
scene.add(platformEdges);
const BAR_LENGTH = 9.2;
const BAR_HEIGHT = 0.56;
const BAR_DEPTH = 1.0;
const TILE_GAP = 0.075;
const GUIDE_Y = 0.74;
const rowDefinitions = [
{
fraction: "1/2",
parts: 1,
partLabel: "1/2",
partName: "1 parte",
z: -2.08,
colors: [0x2bcfaf],
cssColor: "#20c9aa"
},
{
fraction: "2/4",
parts: 2,
partLabel: "1/4",
partName: "2 partes",
z: 0,
colors: [0x6d98ff, 0x4d78e8],
cssColor: "#5684f7"
},
{
fraction: "4/8",
parts: 4,
partLabel: "1/8",
partName: "4 partes",
z: 2.08,
colors: [0xff9a73, 0xf77b62, 0xf46e78, 0xeb6574],
cssColor: "#f47765"
}
];
function roundedRectPath(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + width - r, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
ctx.lineTo(x + width, y + height - r);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
ctx.lineTo(x + r, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function makeTextSprite(lines, worldHeight, options = {}) {
const {
background = "rgba(255,255,255,0.96)",
foreground = "#17243d",
border = "rgba(23,36,61,0.2)",
primarySize = 82,
secondarySize = 34
} = options;
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 240;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.shadowColor = "rgba(24,36,58,0.20)";
ctx.shadowBlur = 18;
ctx.shadowOffsetY = 7;
roundedRectPath(ctx, 12, 12, 616, 216, 38);
ctx.fillStyle = background;
ctx.fill();
ctx.restore();
ctx.lineWidth = 5;
ctx.strokeStyle = border;
roundedRectPath(ctx, 14, 14, 612, 212, 36);
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = foreground;
if (lines.length === 1) {
ctx.font = `850 ${primarySize}px system-ui, sans-serif`;
ctx.fillText(lines[0], 320, 120);
} else {
ctx.font = `850 ${primarySize}px system-ui, sans-serif`;
ctx.fillText(lines[0], 320, 91);
ctx.font = `760 ${secondarySize}px system-ui, sans-serif`;
ctx.fillText(lines[1], 320, 166);
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
const aspect = canvas.width / canvas.height;
sprite.scale.set(worldHeight * aspect, worldHeight, 1);
sprite.renderOrder = 30;
return sprite;
}
const segmentMeshes = [];
const rails = [];
const alignmentGroup = new THREE.Group();
scene.add(alignmentGroup);
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x1b2c47,
roughness: 0.62,
metalness: 0.12
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x17243d,
transparent: true,
opacity: 0.72
});
rowDefinitions.forEach((definition, rowIndex) => {
const rowGroup = new THREE.Group();
rowGroup.position.z = definition.z;
scene.add(rowGroup);
const rail = new THREE.Mesh(
new THREE.BoxGeometry(BAR_LENGTH, 0.2, 1.15),
railMaterial
);
rail.position.y = 0.03;
rail.castShadow = true;
rail.receiveShadow = true;
rail.userData.logicalLength = BAR_LENGTH;
rowGroup.add(rail);
rails.push(rail);
const unitLength = BAR_LENGTH / definition.parts;
const visibleWidth = unitLength - TILE_GAP;
for (let partIndex = 0; partIndex < definition.parts; partIndex++) {
const centerX = -BAR_LENGTH / 2 + unitLength / 2 + partIndex * unitLength;
const color = definition.colors[partIndex % definition.colors.length];
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.38,
metalness: 0.03,
emissive: 0x000000,
emissiveIntensity: 0
});
const tile = new THREE.Mesh(
new THREE.BoxGeometry(visibleWidth, BAR_HEIGHT, BAR_DEPTH),
material
);
tile.position.set(centerX, 0.36, 0);
tile.castShadow = true;
tile.receiveShadow = true;
tile.userData = {
rowIndex,
partIndex,
row: definition,
centerX,
logicalUnitLength: unitLength,
visibleWidth
};
rowGroup.add(tile);
segmentMeshes.push(tile);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(tile.geometry),
edgeMaterial
);
edges.renderOrder = 3;
tile.add(edges);
const shine = new THREE.Mesh(
new THREE.PlaneGeometry(visibleWidth * 0.82, 0.12),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.17,
depthWrite: false
})
);
shine.rotation.x = -Math.PI / 2;
shine.position.set(0, BAR_HEIGHT / 2 + 0.008, -0.27);
shine.renderOrder = 4;
tile.add(shine);
const partBadge = makeTextSprite(
[definition.partLabel],
definition.parts === 1 ? 0.47 : definition.parts === 2 ? 0.42 : 0.37,
{
background: "rgba(255,255,255,0.95)",
foreground: "#17243d",
border: "rgba(23,36,61,0.22)",
primarySize: 94
}
);
partBadge.position.set(centerX, 0.91, 0.01);
rowGroup.add(partBadge);
}
const rowBadge = makeTextSprite(
[definition.fraction, definition.partName],
0.68,
{
background: definition.cssColor,
foreground: "#ffffff",
border: "rgba(255,255,255,0.8)",
primarySize: 88,
secondarySize: 34
}
);
rowBadge.position.set(-5.28, 0.52, 0.02);
rowGroup.add(rowBadge);
const equalityBadge = makeTextSprite(
["= 50%"],
0.43,
{
background: "rgba(255,255,255,0.95)",
foreground: "#17243d",
border: "rgba(217,154,40,0.58)",
primarySize: 72
}
);
equalityBadge.position.set(5.18, 0.49, 0.02);
rowGroup.add(equalityBadge);
});
function makeAlignmentGuide(x, label) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(x, GUIDE_Y, -3.42),
new THREE.Vector3(x, GUIDE_Y, 3.42)
]);
const material = new THREE.LineDashedMaterial({
color: 0xd99a28,
dashSize: 0.18,
gapSize: 0.12,
transparent: true,
opacity: 0.82
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
line.renderOrder = 8;
alignmentGroup.add(line);
rowDefinitions.forEach((definition) => {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.09, 16, 12),
new THREE.MeshStandardMaterial({
color: 0xf2b84c,
roughness: 0.35,
emissive: 0xa95c00,
emissiveIntensity: 0.12
})
);
marker.position.set(x, GUIDE_Y + 0.015, definition.z);
marker.castShadow = true;
alignmentGroup.add(marker);
});
const labelSprite = makeTextSprite(
[label],
0.31,
{
background: "rgba(255,248,226,0.94)",
foreground: "#8a5a13",
border: "rgba(217,154,40,0.45)",
primarySize: 58
}
);
labelSprite.position.set(x, 0.95, 3.48);
alignmentGroup.add(labelSprite);
}
makeAlignmentGuide(-BAR_LENGTH / 2, "mesmo início");
makeAlignmentGuide(BAR_LENGTH / 2, "mesmo fim");
const target = new THREE.Vector3(0, 0.12, 0);
let responsiveFactor = 1;
let currentCamera = { theta: 0.025, phi: 0.84, radius: 15.8 };
let desiredCamera = { ...currentCamera };
const presets = {
overview: { theta: 0.025, phi: 0.84, radius: 15.8 },
perspective: { theta: 0.48, phi: 0.78, radius: 15.2 },
top: { theta: 0, phi: 0.37, radius: 16.2 }
};
function updateResponsiveFactor() {
const aspect = window.innerWidth / window.innerHeight;
const nextFactor = Math.max(1, 1.36 / aspect);
if (Math.abs(nextFactor - responsiveFactor) > 0.001) {
const ratio = nextFactor / responsiveFactor;
currentCamera.radius *= ratio;
desiredCamera.radius *= ratio;
responsiveFactor = nextFactor;
}
}
function applyCamera() {
const sinPhi = Math.sin(currentCamera.phi);
camera.position.set(
target.x + currentCamera.radius * sinPhi * Math.sin(currentCamera.theta),
target.y + currentCamera.radius * Math.cos(currentCamera.phi),
target.z + currentCamera.radius * sinPhi * Math.cos(currentCamera.theta)
);
camera.lookAt(target);
}
function setCameraPreset(name) {
const preset = presets[name];
desiredCamera = {
theta: preset.theta,
phi: preset.phi,
radius: preset.radius * responsiveFactor
};
document.querySelectorAll("[data-camera]").forEach((button) => {
const active = button.dataset.camera === name;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
}
document.querySelectorAll("[data-camera]").forEach((button) => {
button.addEventListener("click", () => setCameraPreset(button.dataset.camera));
});
const guidesButton = document.getElementById("guides-button");
guidesButton.addEventListener("click", () => {
const visible = !alignmentGroup.visible;
alignmentGroup.visible = visible;
guidesButton.textContent = visible ? "Guias: ligadas" : "Guias: desligadas";
guidesButton.setAttribute("aria-pressed", String(visible));
showStatus(
visible
? "Guias ligadas: os limites inicial e final coincidem nas três barras."
: "Guias desligadas. As bordas escuras mantêm cada divisão visível.",
visible ? "" : "success"
);
});
let selectedTile = null;
function refreshTileMaterials() {
segmentMeshes.forEach((tile) => {
if (tile === selectedTile) {
tile.material.emissive.setHex(0xffffff);
tile.material.emissiveIntensity = 0.28;
} else {
tile.material.emissive.setHex(0x000000);
tile.material.emissiveIntensity = 0;
}
});
}
function selectTile(tile) {
selectedTile = tile;
refreshTileMaterials();
if (!tile) {
selectionTitle.textContent = "Clique em uma parte";
selectionCopy.textContent =
"Cada porção tem um valor próprio. As partes de cada linha somam sempre a mesma quantidade.";
return;
}
const { row, partIndex } = tile.userData;
const partValue = 100 / row.parts;
const partValueText = Number.isInteger(partValue)
? String(partValue)
: partValue.toFixed(1).replace(".", ",");
selectionTitle.textContent = `${row.fraction} — peça ${partIndex + 1} de ${row.parts}`;
selectionCopy.textContent =
`Cada peça vale ${partValueText}% do inteiro. ` +
`${row.parts} × ${row.partLabel} = ${row.fraction} = 50%. ` +
`Portanto, a barra inteira equivale à mesma quantidade das outras duas.`;
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = null;
let dragging = false;
function pointerToNDC(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickTile(event) {
pointerToNDC(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(segmentMeshes, false);
return intersections.length ? intersections[0].object : null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointerDown = { x: event.clientX, y: event.clientY };
dragging = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - pointerDown.x;
const dy = event.clientY - pointerDown.y;
if (Math.hypot(dx, dy) > 4) dragging = true;
if (dragging) {
desiredCamera.theta = THREE.MathUtils.clamp(
desiredCamera.theta - dx * 0.006,
-0.7,
0.7
);
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi + dy * 0.005,
0.32,
1.08
);
}
return;
}
renderer.domElement.style.cursor = pickTile(event) ? "pointer" : "grab";
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (pointerDown && !dragging) {
selectTile(pickTile(event));
}
pointerDown = null;
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius + event.deltaY * 0.012,
13.2 * responsiveFactor,
27 * responsiveFactor
);
},
{ passive: false }
);
renderer.domElement.addEventListener("keydown", (event) => {
const key = event.key;
if (key === "ArrowLeft") desiredCamera.theta -= 0.08;
else if (key === "ArrowRight") desiredCamera.theta += 0.08;
else if (key === "ArrowUp") desiredCamera.phi -= 0.06;
else if (key === "ArrowDown") desiredCamera.phi += 0.06;
else if (key === "+" || key === "=") desiredCamera.radius -= 0.7;
else if (key === "-") desiredCamera.radius += 0.7;
else return;
event.preventDefault();
desiredCamera.theta = THREE.MathUtils.clamp(
desiredCamera.theta,
-0.7,
0.7
);
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi,
0.32,
1.08
);
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius,
13.2 * responsiveFactor,
27 * responsiveFactor
);
});
let statusTimer = 0;
function showStatus(message, type = "") {
window.clearTimeout(statusTimer);
statusElement.textContent = message;
statusElement.className = `status visible ${type}`.trim();
statusTimer = window.setTimeout(() => {
statusElement.classList.remove("visible");
}, 5200);
}
function validateGeometry(showMessage = true) {
scene.updateMatrixWorld(true);
const errors = [];
rowDefinitions.forEach((row) => {
const rowTiles = segmentMeshes.filter(
(tile) => tile.userData.rowIndex === rowDefinitions.indexOf(row)
);
const unitLength = BAR_LENGTH / row.parts;
const expectedVisibleWidth = unitLength - TILE_GAP;
if (rowTiles.length !== row.parts) {
errors.push(`${row.fraction}: contagem de peças incorreta.`);
}
rowTiles.forEach((tile, index) => {
const expectedCenter =
-BAR_LENGTH / 2 + unitLength / 2 + index * unitLength;
const actualWidth = tile.geometry.parameters.width;
if (Math.abs(tile.position.x - expectedCenter) > 0.0001) {
errors.push(`${row.fraction}: posição da peça ${index + 1} incorreta.`);
}
if (Math.abs(actualWidth - expectedVisibleWidth) > 0.0001) {
errors.push(`${row.fraction}: largura da peça ${index + 1} incorreta.`);
}
});
const railWidth = rowTiles.length
? rails[rowDefinitions.indexOf(row)].geometry.parameters.width
: 0;
if (Math.abs(railWidth - BAR_LENGTH) > 0.0001) {
errors.push(`${row.fraction}: comprimento total incorreto.`);
}
});
const railWidths = rails.map((rail) => rail.geometry.parameters.width);
const allEqual =
railWidths.every((width) => Math.abs(width - railWidths[0]) < 0.0001);
if (!allEqual) {
errors.push("As três barras não têm o mesmo comprimento.");
}
const logicalLengths = rowDefinitions.map(
(row) => row.parts * (BAR_LENGTH / row.parts)
);
if (!logicalLengths.every((length) => Math.abs(length - BAR_LENGTH) < 0.0001)) {
errors.push("A soma lógica das partes não corresponde ao comprimento da barra.");
}
if (showMessage) {
if (errors.length) {
showStatus(`Falha na verificação: ${errors.join(" ")}`, "error");
} else {
showStatus(
"✓ Verificação concluída: 3/3 barras têm 9,20 unidades de comprimento; " +
"as divisões reais são 1, 2 e 4 peças, e todas somam 1/2.",
"success"
);
}
}
return { valid: errors.length === 0, errors };
}
document
.getElementById("validate-button")
.addEventListener("click", () => validateGeometry(true));
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
updateResponsiveFactor();
}
window.addEventListener("resize", onResize);
updateResponsiveFactor();
applyCamera();
const initialValidation = validateGeometry(false);
if (initialValidation.valid) {
showStatus(
"Cena pronta: as três barras têm o mesmo comprimento e as divisões estão separadas.",
"success"
);
}
function animate() {
requestAnimationFrame(animate);
currentCamera.theta = THREE.MathUtils.lerp(
currentCamera.theta,
desiredCamera.theta,
0.085
);
currentCamera.phi = THREE.MathUtils.lerp(
currentCamera.phi,
desiredCamera.phi,
0.085
);
currentCamera.radius = THREE.MathUtils.lerp(
currentCamera.radius,
desiredCamera.radius,
0.085
);
applyCamera();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```