Prompt specification
Build or customize the Three.js 3D scene "Warehouse inspection teaching diorama" 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: Warehouse inspection teaching diorama
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/warehouse-inspection-teaching-diorama-x1763
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts base rates and predictive values of a detector. Compose a fictional conveyor and review bins with explicit synthetic counts; explain why many flags can be false when defects are rare without implying detector parameters are measured. Voxel style.
Technical checks: Balance the synthetic count table across all four outcomes. With 10,000 items and 1,000 flagged items, show 9,000 unflagged items, including 8,980 unflagged nondefective items in the given scenario.
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 (warehouse-inspection-teaching-diorama-x1763):
```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="#08111f">
<link rel="icon" href="data:,">
<title>Voxel Review — Base rara, sinalizações e valores preditivos</title>
<style>
:root {
color-scheme: dark;
--bg: #08111f;
--panel: rgba(10, 21, 37, 0.9);
--line: rgba(151, 181, 218, 0.22);
--text: #edf5ff;
--muted: #9eb2ca;
--cyan: #56d9ff;
--green: #43dc9a;
--amber: #ffc15a;
--red: #ff5d78;
--purple: #d878ff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
color: var(--text);
}
canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
}
canvas.dragging { cursor: grabbing; }
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(10px);
}
#intro {
top: 16px;
left: 16px;
width: min(390px, calc(100vw - 32px));
padding: 16px 18px;
border-left: 4px solid var(--cyan);
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 2.3vw, 34px);
line-height: 1.03;
letter-spacing: -0.04em;
}
#intro p {
margin: 9px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
#metrics {
top: 16px;
right: 16px;
width: min(430px, calc(100vw - 32px));
padding: 12px;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.metric {
min-height: 88px;
padding: 10px 12px;
background: rgba(255, 255, 255, 0.035);
border: 1px solid rgba(255, 255, 255, 0.07);
}
.metric .name {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric .value {
margin-top: 3px;
font-size: 24px;
font-weight: 900;
line-height: 1;
}
.metric .formula {
margin-top: 6px;
color: #b8c7d9;
font-size: 10px;
}
.metric.base .value { color: var(--cyan); }
.metric.ppv .value { color: var(--amber); }
.metric.npv .value { color: var(--green); }
.metric.flag .value { color: var(--red); }
#story {
left: 16px;
bottom: 16px;
width: min(760px, calc(100vw - 32px));
padding: 14px 16px;
border-left: 4px solid var(--amber);
}
#story-title {
margin-bottom: 6px;
color: var(--amber);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
}
#story-text {
color: #d9e5f4;
font-size: 12px;
line-height: 1.55;
}
#story-text strong { color: #fff; }
#disclaimer {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
#controls {
right: 16px;
bottom: 16px;
width: min(430px, calc(100vw - 32px));
padding: 12px;
}
.buttons {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
button {
appearance: none;
border: 1px solid #39506b;
border-radius: 2px;
padding: 9px 10px;
background: #14263d;
color: #dceaff;
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
cursor: pointer;
text-transform: uppercase;
letter-spacing: 0.04em;
}
button:hover,
button:focus-visible {
border-color: var(--cyan);
background: #1a3551;
outline: none;
}
button[aria-pressed="true"] {
border-color: var(--cyan);
background: #174a62;
color: #fff;
}
#audit {
margin-top: 9px;
color: var(--green);
font-size: 10px;
line-height: 1.4;
}
#hint {
margin-top: 5px;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
@media (max-width: 900px) {
#intro { width: 310px; }
#metrics { top: auto; bottom: 154px; width: 310px; }
#story { width: calc(100vw - 32px); }
#controls { display: none; }
.metric { min-height: 72px; }
.metric .value { font-size: 20px; }
}
@media (max-width: 620px) {
#intro { width: calc(100vw - 32px); }
#intro p { display: none; }
#metrics { display: none; }
#story { width: calc(100vw - 32px); }
}
</style>
</head>
<body>
<div id="intro" class="panel">
<div class="eyebrow">Voxel review · exemplo sintético · não medido</div>
<h1>SINALIZADO<br>≠ DEFEITO</h1>
<p>Uma base rara de defeitos pode produzir muitas sinalizações sem defeito. Os volumes nos bins são contados um a um.</p>
</div>
<section id="metrics" class="panel" aria-label="Métricas da matriz sintética">
<div class="metric-grid">
<div class="metric base">
<div class="name">Taxa de base de defeito</div>
<div class="value">0,40%</div>
<div class="formula">40 defeitos ÷ 10.000 itens</div>
</div>
<div class="metric ppv">
<div class="name">PPV · valor preditivo positivo</div>
<div class="value">2,00%</div>
<div class="formula">20 ÷ 1.000 sinalizados</div>
</div>
<div class="metric npv">
<div class="name">NPV · valor preditivo negativo</div>
<div class="value">99,78%</div>
<div class="formula">8.980 ÷ 9.000 não sinalizados</div>
</div>
<div class="metric flag">
<div class="name">Sinalizações sem defeito</div>
<div class="value">98,00%</div>
<div class="formula">980 falsos ÷ 1.000 sinalizados</div>
</div>
</div>
</section>
<section id="story" class="panel" aria-live="polite">
<div id="story-title">Matriz completa: 10.000 itens</div>
<div id="story-text">
<strong>1.000 sinalizados + 9.000 não sinalizados = 10.000.</strong>
A matriz fictícia contém 20 verdadeiros positivos (TP), 980 falsos positivos (FP),
20 falsos negativos (FN) e 8.980 verdadeiros negativos (TN).
</div>
<div id="disclaimer">
Exemplo inteiramente sintético, criado para explicar a aritmética. Não representa calibração,
medição, sensibilidade, especificidade ou desempenho real de qualquer detector.
</div>
</section>
<nav id="controls" class="panel" aria-label="Controles da cena">
<div class="buttons">
<button type="button" data-filter="all" aria-pressed="true">Todos</button>
<button type="button" data-filter="flagged" aria-pressed="false">1.000 sinalizados</button>
<button type="button" data-filter="unflagged" aria-pressed="false">9.000 não sinalizados</button>
<button type="button" id="flow-button" aria-pressed="true">Pausar fluxo</button>
<button type="button" id="camera-button">Repor câmara</button>
</div>
<div id="audit">A conferir: matriz e geometria…</div>
<div id="hint">Arraste para orbitar; use a roda para ampliar. Clique num volume para isolar TP, FP, TN ou FN.</div>
</nav>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Single, internally consistent synthetic confusion matrix.
// Every colored voxel represents exactly one synthetic item.
// ---------------------------------------------------------------------
const DATA = Object.freeze({
total: 10000,
flagged: 1000,
unflagged: 9000,
tp: 20,
fp: 980,
fn: 20,
tn: 8980,
defects: 40,
nondefects: 9960
});
const OUTCOMES = {
tp: {
key: "tp", count: DATA.tp, flagged: true,
title: "TP · 20",
subtitle: "com defeito — sinalizado",
color: 0xff5d78, emissive: 0x7d1028,
center: [6.25, -4.0], cols: 5, rows: 2, layers: 2,
binWidth: 1.25, binDepth: 1.05
},
fp: {
key: "fp", count: DATA.fp, flagged: true,
title: "FP · 980",
subtitle: "sem defeito — falso sinal",
color: 0xffc15a, emissive: 0x7a4700,
center: [3.0, -4.0], cols: 14, rows: 14, layers: 5,
binWidth: 2.65, binDepth: 2.65
},
tn: {
key: "tn", count: DATA.tn, flagged: false,
title: "TN · 8.980",
subtitle: "sem defeito — não sinalizado",
color: 0x43dc9a, emissive: 0x075c3a,
center: [4.0, 3.0], cols: 30, rows: 30, layers: 10,
binWidth: 5.85, binDepth: 5.85
},
fn: {
key: "fn", count: DATA.fn, flagged: false,
title: "FN · 20",
subtitle: "com defeito — não sinalizado",
color: 0xd878ff, emissive: 0x59146c,
center: [8.3, 3.0], cols: 5, rows: 2, layers: 2,
binWidth: 1.25, binDepth: 1.05
}
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111f);
scene.fog = new THREE.Fog(0x08111f, 31, 58);
const camera = new THREE.OrthographicCamera(-15, 15, 9, -9, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Cena 3D voxel de uma esteira e bins de revisão");
document.body.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xbfe8ff, 0x142039, 2.25);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-7, 15, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 15;
keyLight.shadow.camera.bottom = -15;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x56d9ff, 1.25);
rimLight.position.set(12, 8, -12);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa53d, 14, 18, 2);
warmLight.position.set(6, 7, -5);
scene.add(warmLight);
const floorBase = new THREE.Mesh(
new THREE.BoxGeometry(27.5, 0.34, 15.5),
new THREE.MeshStandardMaterial({ color: 0x0a1728, roughness: 0.92, metalness: 0.06 })
);
floorBase.position.set(-0.4, -0.25, 0);
floorBase.receiveShadow = true;
scene.add(floorBase);
// Procedural tiled floor.
const tileGeometry = new THREE.BoxGeometry(1.91, 0.075, 1.84);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff, roughness: 0.88, metalness: 0.08
});
const tileCount = 14 * 8;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
const dummy = new THREE.Object3D();
const tileColorA = new THREE.Color(0x10243a);
const tileColorB = new THREE.Color(0x132b43);
let tileIndex = 0;
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 14; col++) {
dummy.position.set(-12.55 + col * 1.96, -0.035, -6.75 + row * 1.93);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
tiles.setColorAt(tileIndex, (row + col) % 2 ? tileColorA : tileColorB);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
scene.add(tiles);
function box(w, h, d, x, y, z, color, options = {}) {
const material = new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.78,
metalness: options.metalness ?? 0.08,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
});
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = true;
scene.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 makeLabel(title, subtitle, worldWidth, background, border, x, y, z) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 12, 12, 1000, 232, 18);
ctx.fillStyle = background;
ctx.fill();
ctx.lineWidth = 8;
ctx.strokeStyle = border;
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#f7fbff";
ctx.font = "800 64px ui-monospace, monospace";
ctx.fillText(title, 512, 92, 940);
ctx.fillStyle = "#d5e4f3";
ctx.font = "600 32px ui-monospace, monospace";
ctx.fillText(subtitle, 512, 176, 930);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldWidth * 0.25, 1);
sprite.position.set(x, y, z);
sprite.renderOrder = 20;
scene.add(sprite);
return sprite;
}
// Conveyor, deliberately schematic: the exact item populations live in the review bins.
const conveyor = new THREE.Group();
scene.add(conveyor);
const conveyorBase = new THREE.Mesh(
new THREE.BoxGeometry(12.2, 0.52, 3.45),
new THREE.MeshStandardMaterial({ color: 0x23384e, roughness: 0.72, metalness: 0.28 })
);
conveyorBase.position.set(-6.7, 0.36, 0);
conveyorBase.castShadow = true;
conveyorBase.receiveShadow = true;
conveyor.add(conveyorBase);
const belt = new THREE.Mesh(
new THREE.BoxGeometry(11.85, 0.18, 2.55),
new THREE.MeshStandardMaterial({ color: 0x07101b, roughness: 0.96, metalness: 0.02 })
);
belt.position.set(-6.7, 0.72, 0);
belt.castShadow = true;
belt.receiveShadow = true;
conveyor.add(belt);
for (const z of [-1.48, 1.48]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(12.15, 0.34, 0.24),
new THREE.MeshStandardMaterial({ color: 0x6a829c, roughness: 0.6, metalness: 0.38 })
);
rail.position.set(-6.7, 0.88, z);
rail.castShadow = true;
conveyor.add(rail);
}
for (let i = 0; i < 16; i++) {
const slat = box(0.34, 0.045, 2.34, -12.2 + i * 0.72, 0.84, 0,
i % 2 ? 0x1d2f42 : 0x263b50,
{ castShadow: false, metalness: 0.2 });
slat.material.transparent = true;
slat.material.opacity = 0.68;
}
for (const x of [-11.6, -8.2, -4.8, -1.8]) {
box(0.34, 1.05, 0.34, x, 0.02, -1.28, 0x425a73);
box(0.34, 1.05, 0.34, x, 0.02, 1.28, 0x425a73);
}
// Voxel scanner gantry.
box(0.48, 3.35, 0.48, -2.35, 1.64, -1.9, 0x5a7896, { metalness: 0.38 });
box(0.48, 3.35, 0.48, -2.35, 1.64, 1.9, 0x5a7896, { metalness: 0.38 });
box(0.65, 0.48, 4.2, -2.35, 3.25, 0, 0x7593ae, { metalness: 0.42 });
box(0.72, 0.58, 0.72, -2.35, 2.88, 0, 0x193b50, {
emissive: 0x0a7898, emissiveIntensity: 0.9, metalness: 0.25
});
const scanBar = box(0.10, 0.10, 2.26, -10.5, 0.99, 0, 0x56d9ff, {
emissive: 0x18bde8, emissiveIntensity: 1.7, transparent: true, opacity: 0.85,
castShadow: false
});
// Small block arrows communicate flow without implying a second item population.
for (const x of [-10.1, -7.5, -4.9]) {
box(0.52, 0.06, 0.18, x, 0.98, -0.52, 0x2a8fb0, {
emissive: 0x0d6078, emissiveIntensity: 0.45, castShadow: false
});
box(0.18, 0.06, 0.50, x + 0.32, 0.98, -0.52, 0x2a8fb0, {
emissive: 0x0d6078, emissiveIntensity: 0.45, castShadow: false
});
}
makeLabel(
"10.000 ITENS SINTÉTICOS",
"40 com defeito · base de 0,40%",
5.8,
"rgba(7,29,47,0.96)",
"#56d9ff",
-6.7, 3.75, 0
);
// ---------------------------------------------------------------------
// Four physical review bins. Instance counts exactly match the labels.
// ---------------------------------------------------------------------
const categoryMeshes = [];
const categoryVisuals = {};
function createReviewBin(def) {
const [cx, cz] = def.center;
const w = def.binWidth;
const d = def.binDepth;
const group = new THREE.Group();
group.position.set(cx, 0, cz);
scene.add(group);
const baseMat = new THREE.MeshStandardMaterial({
color: 0x172b40,
roughness: 0.7,
metalness: 0.22,
emissive: def.color,
emissiveIntensity: 0.035
});
const base = new THREE.Mesh(new THREE.BoxGeometry(w, 0.22, d), baseMat);
base.position.y = 0.16;
base.receiveShadow = true;
group.add(base);
const edgeMat = new THREE.MeshStandardMaterial({
color: def.color,
roughness: 0.6,
metalness: 0.16,
emissive: def.color,
emissiveIntensity: 0.04,
transparent: true,
opacity: 0.76
});
const edgeHeight = Math.min(0.58, 0.22 + def.layers * 0.045);
const edgeThickness = 0.10;
const edgeY = 0.29 + edgeHeight / 2;
const edges = [
[w, edgeHeight, edgeThickness, 0, edgeY, -d / 2],
[edgeThickness, edgeHeight, d, -w / 2, edgeY, 0],
[edgeThickness, edgeHeight, d, w / 2, edgeY, 0]
];
for (const [ew, eh, ed, ex, ey, ez] of edges) {
const edge = new THREE.Mesh(new THREE.BoxGeometry(ew, eh, ed), edgeMat);
edge.position.set(ex, ey, ez);
edge.castShadow = true;
group.add(edge);
}
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.15, 0.82, 0.15),
edgeMat
);
post.position.set(sx * (w / 2 - 0.06), 0.48, sz * (d / 2 - 0.06));
post.castShadow = true;
group.add(post);
}
}
const cubeSize = 0.145;
const pitch = 0.18;
const geometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);
const material = new THREE.MeshStandardMaterial({
color: def.color,
roughness: 0.72,
metalness: 0.06,
emissive: def.emissive,
emissiveIntensity: 0.25
});
const mesh = new THREE.InstancedMesh(geometry, material, def.count);
mesh.userData.outcome = def.key;
mesh.userData.count = def.count;
mesh.receiveShadow = true;
mesh.castShadow = false;
mesh.frustumCulled = false;
const transform = new THREE.Object3D();
for (let i = 0; i < def.count; i++) {
const layer = Math.floor(i / (def.cols * def.rows));
const withinLayer = i % (def.cols * def.rows);
const row = Math.floor(withinLayer / def.cols);
const col = withinLayer % def.cols;
transform.position.set(
(col - (def.cols - 1) / 2) * pitch,
0.36 + layer * pitch,
(row - (def.rows - 1) / 2) * pitch
);
transform.rotation.set(0, 0, 0);
transform.scale.set(1, 1, 1);
transform.updateMatrix();
mesh.setMatrixAt(i, transform.matrix);
}
mesh.instanceMatrix.needsUpdate = true;
group.add(mesh);
categoryMeshes.push(mesh);
const labelY = def.key === "tn" ? 2.65 : 1.42;
const labelWidth = def.key === "tn" ? 4.45 : (def.key === "fp" ? 3.15 : 2.55);
const label = makeLabel(
def.title,
def.subtitle,
labelWidth,
"rgba(6,18,31,0.95)",
"#" + def.color.toString(16).padStart(6, "0"),
cx, labelY, cz
);
categoryVisuals[def.key] = { mesh, label, group, base, edgeMat };
}
Object.values(OUTCOMES).forEach(createReviewBin);
makeLabel(
"SINALIZADOS · 1.000",
"10% do total · revisar o sinal",
5.15,
"rgba(58,38,8,0.96)",
"#ffc15a",
4.55, 3.15, -4.0
);
makeLabel(
"NÃO SINALIZADOS · 9.000",
"90% do total · revisar a ausência do sinal",
6.15,
"rgba(5,49,38,0.96)",
"#43dc9a",
5.0, 3.45, 3.0
);
// Small voxel connector from the conveyor toward the review area.
for (let i = 0; i < 5; i++) {
box(0.26, 0.06, 0.26, -0.2 + i * 0.44, 0.08, 0, 0x2f7897, {
emissive: 0x0b4f68, emissiveIntensity: 0.4, castShadow: false
});
}
// ---------------------------------------------------------------------
// Arithmetic and geometry validation.
// ---------------------------------------------------------------------
const auditElement = document.getElementById("audit");
function validateDataAndGeometry() {
const checks = [
[DATA.tp + DATA.fp === DATA.flagged, "TP + FP deve等于 sinalizados"],
[DATA.fn + DATA.tn === DATA.unflagged, "FN + TN deve igual não sinalizados"],
[DATA.tp + DATA.fn === DATA.defects, "TP + FN deve igual defeitos"],
[DATA.fp + DATA.tn === DATA.nondefects, "FP + TN deve igual não defeitos"],
[DATA.flagged + DATA.unflagged === DATA.total, "Total de revisões incorreto"],
[DATA.tp + DATA.fp + DATA.fn + DATA.tn === DATA.total, "Soma da matriz incorreta"]
];
for (const [ok, message] of checks) {
if (!ok) throw new Error("Falha na auditoria: " + message);
}
for (const def of Object.values(OUTCOMES)) {
const visual = categoryVisuals[def.key];
if (!visual || visual.mesh.count !== def.count) {
throw new Error(`Geometria inconsistente em ${def.key.toUpperCase()}`);
}
}
auditElement.textContent =
"✓ OK · 10.000 = 1.000 + 9.000 · matriz = 20 + 980 + 20 + 8.980 · voxels conferidos";
}
validateDataAndGeometry();
// ---------------------------------------------------------------------
// Direct camera controls: orbit by dragging and zoom with the wheel.
// ---------------------------------------------------------------------
const target = new THREE.Vector3(-0.8, 0.15, 0);
let yaw = 0.61;
let pitch = 0.73;
let zoom = 1;
const minimumPitch = 0.28;
const maximumPitch = 1.18;
function applyCamera() {
const distance = 28;
const horizontal = Math.cos(pitch) * distance;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
camera.zoom = zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
yaw = 0.61;
pitch = 0.73;
zoom = 1;
applyCamera();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const minimumWidth = 28;
const baseHeight = 17;
let viewHeight = baseHeight;
let viewWidth = viewHeight * aspect;
if (viewWidth < minimumWidth) {
viewWidth = minimumWidth;
viewHeight = viewWidth / aspect;
}
camera.left = -viewWidth / 2;
camera.right = viewWidth / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
applyCamera();
resize();
window.addEventListener("resize", resize);
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
let dragging = false;
let pointerStart = null;
let previousPointer = null;
let dragDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragDistance = 0;
pointerStart = { x: event.clientX, y: event.clientY };
previousPointer = { x: event.clientX, y: event.clientY };
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging || !previousPointer) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
dragDistance += Math.abs(dx) + Math.abs(dy);
yaw -= dx * 0.006;
pitch = THREE.MathUtils.clamp(pitch + dy * 0.005, minimumPitch, maximumPitch);
previousPointer = { x: event.clientX, y: event.clientY };
applyCamera();
});
function endPointer(event) {
if (!dragging) return;
dragging = false;
renderer.domElement.classList.remove("dragging");
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (dragDistance < 7 && pointerStart) {
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;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(categoryMeshes, false);
if (hits.length) {
const key = hits[0].object.userData.outcome;
selectOutcome(key);
}
}
pointerStart = null;
previousPointer = null;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
zoom = THREE.MathUtils.clamp(zoom * Math.exp(-event.deltaY * 0.001), 0.68, 1.85);
applyCamera();
}, { passive: false });
// ---------------------------------------------------------------------
// Local interaction states. Counts never change; only emphasis changes.
// ---------------------------------------------------------------------
const storyTitle = document.getElementById("story-title");
const storyText = document.getElementById("story-text");
const filterButtons = [...document.querySelectorAll("[data-filter]")];
function setStory(title, html) {
storyTitle.textContent = title;
storyText.innerHTML = html;
}
function applySelection(selectedKeys) {
for (const def of Object.values(OUTCOMES)) {
const visual = categoryVisuals[def.key];
const selected = selectedKeys === null || selectedKeys.has(def.key);
visual.mesh.material.transparent = !selected;
visual.mesh.material.opacity = selected ? 1 : 0.10;
visual.mesh.material.depthWrite = selected;
visual.mesh.material.emissiveIntensity = selected ? 0.33 : 0.04;
visual.mesh.material.needsUpdate = true;
visual.label.material.opacity = selected ? 1 : 0.20;
visual.base.material.emissiveIntensity = selected ? 0.10 : 0.015;
visual.edgeMat.opacity = selected ? 0.82 : 0.18;
visual.edgeMat.emissiveIntensity = selected ? 0.09 : 0.015;
}
}
function selectOutcome(key) {
const def = OUTCOMES[key];
filterButtons.forEach(button => button.setAttribute("aria-pressed", "false"));
applySelection(new Set([key]));
if (key === "tp") {
setStory(
"TP · 20 verdadeiros positivos",
"Dos <strong>1.000 itens sinalizados</strong>, <strong>20 têm defeito</strong>. " +
"O valor preditivo positivo é <strong>20 ÷ 1.000 = 2,00%</strong>."
);
} else if (key === "fp") {
setStory(
"FP · 980 falsos positivos",
"Dos <strong>1.000 itens sinalizados</strong>, <strong>980 não têm defeito</strong>. " +
"Portanto, <strong>98,00% das sinalizações são falsos sinalamentos</strong> neste exemplo."
);
} else if (key === "tn") {
setStory(
"TN · 8.980 verdadeiros negativos",
"Dos <strong>9.000 itens não sinalizados</strong>, <strong>8.980 não têm defeito</strong>. " +
"O valor preditivo negativo é <strong>8.980 ÷ 9.000 = 99,78%</strong>."
);
} else if (key === "fn") {
setStory(
"FN · 20 falsos negativos",
"Dos <strong>9.000 itens não sinalizados</strong>, <strong>20 têm defeito</strong>. " +
"Restam <strong>8.980 sem defeito</strong>, e não 9.960."
);
}
}
function selectFilter(mode) {
let selected = null;
if (mode === "flagged") selected = new Set(["tp", "fp"]);
if (mode === "unflagged") selected = new Set(["fn", "tn"]);
filterButtons.forEach(button => {
button.setAttribute("aria-pressed", String(button.dataset.filter === mode));
});
applySelection(selected);
if (mode === "flagged") {
setStory(
"1.000 sinalizados · apenas 20 defeituosos",
"<strong>1.000 sinalizados = 20 TP + 980 FP.</strong> " +
"Assim, somente <strong>2,00% das flags</strong> correspondem a defeitos neste conjunto fictício; " +
"<strong>980 flags</strong> não têm defeito."
);
} else if (mode === "unflagged") {
setStory(
"9.000 não sinalizados · 8.980 sem defeito",
"<strong>9.000 não sinalizados = 20 FN + 8.980 TN.</strong> " +
"Restam <strong>8.980 itens sem defeito</strong>, não 9.960. " +
"O NPV deste exemplo é <strong>99,78%</strong>."
);
} else {
setStory(
"Matriz completa: 10.000 itens",
"<strong>1.000 sinalizados + 9.000 não sinalizados = 10.000.</strong> " +
"A matriz fictícia contém 20 verdadeiros positivos (TP), 980 falsos positivos (FP), " +
"20 falsos negativos (FN) e 8.980 verdadeiros negativos (TN)."
);
}
}
filterButtons.forEach(button => {
button.addEventListener("click", () => selectFilter(button.dataset.filter));
});
let flowRunning = true;
const flowButton = document.getElementById("flow-button");
flowButton.addEventListener("click", () => {
flowRunning = !flowRunning;
flowButton.textContent = flowRunning ? "Pausar fluxo" : "Animar fluxo";
flowButton.setAttribute("aria-pressed", String(flowRunning));
});
document.getElementById("camera-button").addEventListener("click", resetCamera);
// Animation is only a scan pulse; it does not add or remove item voxels.
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
if (flowRunning) {
const phase = (elapsed * 0.17) % 1;
scanBar.position.x = -11.6 + phase * 9.45;
scanBar.material.emissiveIntensity = 1.25 + Math.sin(elapsed * 4) * 0.35;
}
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```