Prompt specification
Build or customize the Three.js 3D scene "Lifetime Changes a Toy Impact 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: Lifetime Changes a Toy Impact Comparison
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/lifetime-changes-a-toy-impact-comparison-x3952
Scene Description Prompt:
Lifetime changes a toy impact comparison. Create a lifecycle arithmetic model with explicitly fictional per-stage impact factors. Vary reuse count and loss rate, showing sensitivity rather than presenting the values as real assessments. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Show both towers in full across the loss-control range, including at 55% and 60%. Keep the comparison and numerical readings visible as reuse and loss change.
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 (lifetime-changes-a-toy-impact-comparison-x3952):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ciclo de vida de um cenário de brinquedo — modelo sintético</title>
<style>
:root {
--ink: #21302d;
--muted: #667571;
--paper: #f6f4ec;
--panel: #fffdf8;
--line: #d9dfd8;
--teal: #327d74;
--teal-light: #d9ebe5;
--coral: #c96857;
--coral-light: #f5dfd8;
--gold: #d5a343;
--blue: #557ca8;
--gray: #87938f;
--warning: #9b5d23;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #e8eee7;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, input { font: inherit; }
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
width: 100%;
height: 100%;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #e8eee7;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active { cursor: grabbing; }
.scene-hud {
position: absolute;
inset: 0;
pointer-events: none;
}
.scene-heading {
position: absolute;
top: 22px;
left: 24px;
max-width: min(560px, calc(100% - 48px));
padding: 15px 17px 14px;
border: 1px solid rgba(54, 79, 72, 0.15);
border-radius: 16px;
background: rgba(255, 253, 248, 0.88);
box-shadow: 0 12px 35px rgba(40, 57, 52, 0.10);
backdrop-filter: blur(8px);
}
.scene-heading h1 {
margin: 0 0 5px;
font-size: clamp(19px, 2.1vw, 29px);
line-height: 1.08;
letter-spacing: -0.025em;
}
.scene-heading p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.synthetic-stamp {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 8px;
padding: 5px 8px;
border: 1px solid #d9a56f;
border-radius: 999px;
color: var(--warning);
background: #fff1da;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.10em;
text-transform: uppercase;
}
.synthetic-stamp::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: #d68737;
content: "";
}
.scene-tools {
position: absolute;
right: 20px;
bottom: 20px;
display: flex;
align-items: center;
gap: 10px;
pointer-events: auto;
}
.hint {
padding: 8px 11px;
border-radius: 10px;
color: #52625e;
background: rgba(255, 253, 248, 0.82);
font-size: 11px;
box-shadow: 0 6px 18px rgba(40, 57, 52, 0.08);
}
.tool-button {
border: 1px solid rgba(54, 79, 72, 0.18);
border-radius: 10px;
padding: 9px 12px;
color: var(--ink);
background: rgba(255, 253, 248, 0.92);
cursor: pointer;
box-shadow: 0 6px 18px rgba(40, 57, 52, 0.08);
}
.tool-button:hover { background: #fff; }
.tool-button:focus-visible { outline: 3px solid rgba(50, 125, 116, 0.35); }
#panel {
min-width: 0;
height: 100%;
overflow-y: auto;
border-left: 1px solid #d8dfd8;
background: var(--panel);
box-shadow: -8px 0 30px rgba(50, 66, 61, 0.06);
scrollbar-color: #b7c2bc transparent;
}
.panel-inner { padding: 23px 23px 34px; }
.eyebrow {
margin: 0 0 7px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.panel h2 {
margin: 0 0 8px;
font-size: 23px;
line-height: 1.12;
letter-spacing: -0.025em;
}
.intro {
margin: 0 0 15px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.notice {
margin: 0 0 20px;
padding: 11px 12px;
border-left: 4px solid #d08a3d;
border-radius: 8px;
color: #6e4b29;
background: #fff1dc;
font-size: 11px;
line-height: 1.45;
}
.control-section {
margin: 0 0 19px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: #fff;
}
.control-section h3,
.chart-section h3 {
margin: 0 0 13px;
font-size: 13px;
letter-spacing: 0.01em;
}
.control-row + .control-row { margin-top: 16px; }
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 14px;
margin-bottom: 8px;
font-size: 12px;
font-weight: 700;
}
.control-label output {
color: var(--teal);
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.control-help {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 5px 0;
border-radius: 999px;
accent-color: var(--teal);
cursor: pointer;
}
.presets {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 14px;
}
.preset {
border: 1px solid #cdd8d2;
border-radius: 999px;
padding: 7px 10px;
color: #425651;
background: #f5f8f5;
font-size: 10px;
font-weight: 700;
cursor: pointer;
}
.preset:hover { border-color: var(--teal); color: var(--teal); }
.preset:focus-visible { outline: 3px solid rgba(50, 125, 116, 0.25); }
.readings {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 11px;
}
.reading {
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: #fff;
}
.reading.scenario { border-top: 4px solid var(--teal); }
.reading.control { border-top: 4px solid var(--coral); }
.reading-label {
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.reading-value {
font-size: 25px;
font-weight: 800;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.reading-unit {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.delta {
padding: 9px 11px;
border-radius: 10px;
color: var(--muted);
background: #eef2ef;
font-size: 11px;
line-height: 1.4;
}
.delta.positive { color: #8d4e3f; background: var(--coral-light); }
.delta.negative { color: #28675f; background: var(--teal-light); }
.table-wrap {
overflow-x: auto;
border: 1px solid var(--line);
border-radius: 11px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th, td {
padding: 9px 8px;
border-bottom: 1px solid #e6eae5;
text-align: right;
white-space: nowrap;
}
th:first-child, td:first-child { text-align: left; }
th {
color: #596762;
background: #f5f7f4;
font-size: 9px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
tr:last-child td { border-bottom: 0; }
tbody tr.total td { font-weight: 800; background: #fafbf9; }
.stage-name {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
flex: 0 0 auto;
}
.small-note {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.chart-section {
margin-top: 19px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 14px;
background: #fff;
}
.chart-section h3 { margin-bottom: 4px; }
.chart-subtitle {
margin: 0 0 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.chart-wrap {
width: 100%;
overflow: hidden;
border-radius: 9px;
background: #f7f9f6;
}
.chart-wrap svg {
display: block;
width: 100%;
height: auto;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 8px;
color: var(--muted);
font-size: 9px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
display: inline-block;
width: 15px;
height: 3px;
border-radius: 2px;
background: var(--teal);
}
.legend i.reference { background: transparent; border-top: 2px dashed var(--coral); }
details {
margin-top: 18px;
padding: 13px 14px;
border: 1px solid var(--line);
border-radius: 13px;
background: #fff;
}
summary {
cursor: pointer;
font-size: 12px;
font-weight: 800;
}
.formula {
margin: 12px 0;
padding: 10px;
border-radius: 9px;
color: #40504c;
background: #f1f4f1;
font: 11px/1.55 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
overflow-wrap: anywhere;
}
details p {
margin: 9px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
#fallback {
position: absolute;
inset: 0;
display: none;
place-items: center;
padding: 30px;
color: #6f4137;
background: #f7e8e2;
text-align: center;
}
@media (max-width: 900px) {
html, body { overflow: auto; }
#app {
display: block;
height: auto;
min-height: 100%;
}
#stage {
height: 60vh;
min-height: 440px;
}
#panel {
height: auto;
overflow: visible;
border-top: 1px solid #d8dfd8;
border-left: 0;
}
.scene-heading {
top: 14px;
left: 14px;
max-width: calc(100% - 28px);
}
.scene-tools { right: 14px; bottom: 14px; }
.hint { display: none; }
}
@media (max-width: 460px) {
.panel-inner { padding: 20px 15px 28px; }
.scene-heading { padding: 12px 13px; }
.scene-heading p { display: none; }
.readings { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<main id="app">
<section id="stage" aria-label="Comparação tridimensional sintética entre dois ciclos de vida">
<div class="scene-hud">
<div class="scene-heading">
<div class="synthetic-stamp">Fatores e resultados fictícios</div>
<h1>Cenário de brinquedo:.codec lifetime comparison</h1>
<p>
As duas torres usam a mesma escala. Cada segmento representa uma etapa da aritmética.
Reutilização e perda alteram simultaneamente os dados e a geometria.
</p>
</div>
<div class="scene-tools">
<span class="hint">Arraste para orbitar · roda para afastar</span>
<button id="fitButton" class="tool-button" type="button">Enquadrar tudo</button>
</div>
</div>
<div id="fallback" role="alert">
Não foi possível iniciar o WebGL neste navegador.
</div>
</section>
<aside id="panel" aria-label="Controles e resultados do modelo sintético">
<div class="panel-inner">
<p class="eyebrow">Laboratório aritmético</p>
<h2>Impacto por sessão de uso</h2>
<p class="intro">
Compare um cenário compartilhado, sujeito a reuso e perda, com uma unidade de controle.
O experimento altera somente a vida útil do cenário.
</p>
<div class="notice">
<strong>Não é uma avaliação ambiental.</strong> Todos os fatores são deliberadamente inventados.
“u.s.” significa unidade sintética, não kg CO₂e, energia real ou dano real.
</div>
<section class="control-section" aria-labelledby="controlsTitle">
<h3 id="controlsTitle">Parâmetros do cenário</h3>
<div class="control-row">
<label class="control-label" for="reuseInput">
<span>Reutilizações adicionais</span>
<output id="reuseOutput" for="reuseInput">8</output>
</label>
<input id="reuseInput" type="range" min="0" max="20" step="1" value="8">
<div class="control-help">Total de usos planejados: N = 1 + reusos.</div>
</div>
<div class="control-row">
<label class="control-label" for="lossInput">
<span>Perda após cada uso</span>
<output id="lossOutput" for="lossInput">10%</output>
</label>
<input id="lossInput" type="range" min="0" max="95" step="1" value="10">
<div class="control-help">Probabilidade sintética de a unidade se perder antes do uso seguinte.</div>
</div>
<div class="presets" aria-label="Casos de sensibilidade pré-definidos">
<button class="preset" type="button" data-reuse="8" data-loss="10">Equilíbrio</button>
<button class="preset" type="button" data-reuse="8" data-loss="55">55% de perda</button>
<button class="preset" type="button" data-reuse="8" data-loss="60">60% de perda</button>
<button class="preset" type="button" data-reuse="8" data-loss="95">Alta perda</button>
</div>
</section>
<section aria-labelledby="readingTitle">
<h3 id="readingTitle" class="sr-only">Leituras atuais</h3>
<div class="readings">
<article class="reading scenario">
<div class="reading-label">Cenário compartilhado</div>
<div id="scenarioValue" class="reading-value">—</div>
<div class="reading-unit">unidades sintéticas / sessão</div>
</article>
<article class="reading control">
<div class="reading-label">Controle individual</div>
<div id="controlValue" class="reading-value">—</div>
<div class="reading-unit">unidades sintéticas / sessão</div>
</article>
</div>
<div id="deltaSummary" class="delta" aria-live="polite">—</div>
</section>
<section class="control-section" style="margin-top: 14px;" aria-labelledby="factorTitle">
<h3 id="factorTitle">Fatores fixos por estágio — todos fictícios</h3>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Estágio</th>
<th>Cenário</th>
<th>Controle</th>
</tr>
</thead>
<tbody id="factorRows"></tbody>
</table>
</div>
<p class="small-note">
No cenário, produção, distribuição e descarte são Rateados por unidade produzida.
O uso entra uma vez por sessão. No controle, cada fator ocorre uma vez por sessão.
</p>
</section>
<section class="control-section" aria-labelledby="stageTitle">
<h3 id="stageTitle">Contribuição atual por estágio</h3>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Segmento da torre</th>
<th>Cenário</th>
<th>Controle</th>
</tr>
</thead>
<tbody id="stageRows"></tbody>
</table>
</div>
<p class="small-note">
A altura de cada segmento é proporcional a estes números. As bandeiras são adornos e não entram na escala.
</p>
</section>
<section class="chart-section" aria-labelledby="reuseChartTitle">
<h3 id="reuseChartTitle">Sensibilidade ao reuso</h3>
<p class="chart-subtitle">Cenário mantendo a perda atual; controle em 22 u.s.</p>
<div class="chart-wrap">
<svg id="reuseChart" viewBox="0 0 320 125" role="img" aria-label="Sensibilidade sintética à quantidade de reusos"></svg>
</div>
<div class="legend">
<span><i></i> Cenário</span>
<span><i class="reference"></i> Controle</span>
</div>
</section>
<section class="chart-section" aria-labelledby="lossChartTitle">
<h3 id="lossChartTitle">Sensibilidade à perda</h3>
<p class="chart-subtitle">Cenário mantendo o número atual de reusos; controle em 22 u.s.</p>
<div class="chart-wrap">
<svg id="lossChart" viewBox="0 0 320 125" role="img" aria-label="Sensibilidade sintética à taxa de perda"></svg>
</div>
</section>
<details>
<summary>Ver a aritmética do modelo</summary>
<div class="formula">
N = 1 + reusos<br>
S = Σ[k = 0 … N−1] (1 − perda)^k<br>
unidades esperadas = N / S<br>
etapa amortizada = fator × unidades / N<br>
total do cenário = (30 + 4 + 2) × unidades/N + 3
</div>
<p>
<strong>S</strong> é o número médio de usos úteis de uma unidade antes da perda, limitado ao horizonte N.
ParaOSS-loss zero, S = N. O controle soma 18 + 2 + 1 + 1 = 22 u.s. por sessão.
</p>
<p>
Os gráficos exploram uma variável por vez. Eles são uma demonstração de sensibilidade matemática,
não uma previsão, recomendação ou medição.
</p>
</details>
</div>
</aside>
</main>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
const stageElement = document.getElementById('stage');
const fallbackElement = document.getElementById('fallback');
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
} catch (error) {
fallbackElement.style.display = 'grid';
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute('aria-label', 'Cenas tridimensional低 de dois torre de impacto sintético');
stageElement.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8eee7);
scene.fog = new THREE.Fog(0xe8eee7, 13, 27);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 60);
const orbit = {
yaw: 0.18,
pitch: 0.16,
distance: 10,
target: new THREE.Vector3(0, 1.75, 0)
};
const hemisphere = new THREE.HemisphereLight(0xfff8e8, 0x6d8a82, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d4, 3.1);
sun.position.set(-4.5, 9, 6.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -5;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 25;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rim = new THREE.DirectionalLight(0xa8d9d0, 1.0);
rim.position.set(5, 4, -5);
scene.add(rim);
const AXIS_MAX = 45;
const PLOT_HEIGHT = 3.2;
const BASE_Y = 0.12;
const stageColors = [0xc96857, 0xd5a343, 0x4f8294, 0x87938f];
const stageNames = ['Fabricação', 'Distribuição', 'Uso', 'Fim de vida'];
const stageColorCSS = ['#c96857', '#d5a343', '#4f8294', '#87938f'];
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(36, 30),
new THREE.MeshStandardMaterial({ color: 0xdde7dd, roughness: 1, metalness: 0 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.27;
ground.receiveShadow = true;
scene.add(ground);
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(7.25, 0.24, 3.25),
new THREE.MeshStandardMaterial({ color: 0xf7f0df, roughness: 0.92, metalness: 0 })
);
plinth.position.set(0, -0.12, 0);
plinth.castShadow = true;
plinth.receiveShadow = true;
scene.add(plinth);
const plinthInset = new THREE.Mesh(
new THREE.BoxGeometry(6.65, 0.035, 2.65),
new THREE.MeshStandardMaterial({ color: 0xe7eee5, roughness: 0.95 })
);
plinthInset.position.set(0, 0.018, 0);
plinthInset.receiveShadow = true;
scene.add(plinthInset);
function makeLowPolyTree(x, z, scale, color) {
const group = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.11, 0.15, 1.05, 5),
new THREE.MeshStandardMaterial({ color: 0x8c6548, roughness: 1, flatShading: true })
);
trunk.position.y = 0.525;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.68, 1.65, 5),
new THREE.MeshStandardMaterial({ color, roughness: 0.96, flatShading: true })
);
crown.position.y = 1.55;
crown.castShadow = true;
group.add(crown);
group.position.set(x, -0.27, z);
group.scale.setScalar(scale);
scene.add(group);
}
makeLowPolyTree(-4.6, -4.4, 1.25, 0x7fa88d);
makeLowPolyTree(4.7, -4.7, 1.05, 0x91b198);
makeLowPolyTree(-5.8, -3.7, 0.72, 0xa5b99a);
function makeMountain(x, z, radius, height, color) {
const mountain = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 4),
new THREE.MeshStandardMaterial({ color, roughness: 1, flatShading: true })
);
mountain.position.set(x, height / 2 - 0.3, z);
mountain.rotation.y = Math.PI / 4;
mountain.receiveShadow = true;
scene.add(mountain);
}
makeMountain(-3.8, -6.8, 2.8, 3.0, 0xcbd9c5);
makeMountain(3.8, -6.5, 2.55, 2.6, 0xd4dfcd);
function makeToyBlock(x, y, z, size, color, rotation = 0) {
const block = new THREE.Mesh(
new THREE.BoxGeometry(size, size, size),
new THREE.MeshStandardMaterial({ color, roughness: 0.82, flatShading: true })
);
block.position.set(x, y, z);
block.rotation.y = rotation;
block.castShadow = true;
block.receiveShadow = true;
scene.add(block);
const stud = new THREE.Mesh(
new THREE.CylinderGeometry(size * 0.16, size * 0.16, size * 0.10, 6),
new THREE.MeshStandardMaterial({ color, roughness: 0.82, flatShading: true })
);
stud.position.set(x, y + size * 0.55, z);
stud.castShadow = true;
scene.add(stud);
}
makeToyBlock(-3.0, 0.18, -1.12, 0.32, 0xe1aa4d, 0.18);
makeToyBlock(2.93, 0.17, -1.10, 0.30, 0x6a9d91, -0.24);
makeToyBlock(3.25, 0.16, -0.78, 0.26, 0xc97562, 0.14);
function roundedRectPath(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + width - r, y);
context.quadraticCurveTo(x + width, y, x + width, y + r);
context.lineTo(x + width, y + height - r);
context.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
context.lineTo(x + r, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function makeTextSprite(text, options = {}) {
const lines = String(text).split('\n');
const canvas = document.createElement('canvas');
canvas.width = 1024;
canvas.height = options.multiline ? 300 : 190;
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
if (options.background !== false) {
context.fillStyle = options.background || 'rgba(255,253,248,0.94)';
context.strokeStyle = options.border || 'rgba(54,79,72,0.18)';
context.lineWidth = 4;
roundedRectPath(context, 18, 14, canvas.width - 36, canvas.height - 28, 38);
context.fill();
context.stroke();
}
context.fillStyle = options.color || '#263a35';
context.textAlign = 'center';
context.textBaseline = 'middle';
const fontSize = options.fontSize || (lines.length > 1 ? 54 : 72);
context.font = `800 ${fontSize}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
const lineHeight = fontSize * 1.15;
const firstY = canvas.height / 2 - ((lines.length - 1) * lineHeight) / 2;
lines.forEach((line, index) => {
context.fillText(line, canvas.width / 2, firstY + index * lineHeight);
});
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
const worldWidth = options.worldWidth || 1.5;
sprite.scale.set(worldWidth, worldWidth * canvas.height / canvas.width, 1);
sprite.renderOrder = 20;
return sprite;
}
function addTextSprite(text, position, options = {}) {
const sprite = makeTextSprite(text, options);
sprite.position.copy(position);
scene.add(sprite);
return sprite;
}
const axisGroup = new THREE.Group();
scene.add(axisGroup);
const axisMaterial = new THREE.MeshBasicMaterial({ color: 0x71817b });
const axisLine = new THREE.Mesh(
new THREE.BoxGeometry(0.018, PLOT_HEIGHT, 0.018),
axisMaterial
);
axisLine.position.set(-2.65, BASE_Y + PLOT_HEIGHT / 2, -0.62);
axisGroup.add(axisLine);
[0, 15, 30, 45].forEach(value => {
const y = BASE_Y + (value / AXIS_MAX) * PLOT_HEIGHT;
const tick = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.015, 0.015),
axisMaterial
);
tick.position.set(-2.58, y, -0.62);
axisGroup.add(tick);
const label = makeTextSprite(String(value), {
worldWidth: value === 45 ? 0.72 : 0.48,
fontSize: 62,
background: false,
color: '#667571'
});
label.position.set(-2.98, y, -0.60);
axisGroup.add(label);
});
const axisTitle = makeTextSprite('u.s. / sessão', {
worldWidth: 1.15,
fontSize: 58,
background: false,
color: '#667571'
});
axisTitle.position.set(-2.63, BASE_Y + PLOT_HEIGHT + 0.42, -0.60);
axisGroup.add(axisTitle);
function disposeObject(object) {
object.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const materials = Array.isArray(child.material) ? child.material : [child.material];
materials.forEach(material => {
if (material.map) material.map.dispose();
material.dispose();
});
}
});
}
function makeFlag(top, color) {
const group = new THREE.Group();
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.024, 0.34, 5),
new THREE.MeshStandardMaterial({ color: 0x665b4d, roughness: 0.8, flatShading: true })
);
pole.position.set(-0.14, top + 0.17, 0);
pole.castShadow = true;
group.add(pole);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute([
-0.14, top + 0.32, 0,
0.22, top + 0.25, 0,
-0.14, top + 0.15, 0
], 3));
geometry.computeVertexNormals();
const flag = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({ color, side: THREE.DoubleSide, roughness: 0.88, flatShading: true })
);
flag.castShadow = true;
group.add(flag);
return group;
}
function buildTower({ x, name, stages, total, baseColor, flagColor }) {
const group = new THREE.Group();
group.name = name;
group.position.x = x;
group.userData.impactTotal = total;
group.userData.stageContributions = stages.slice();
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.78, 0.83, 0.12, 6),
new THREE.MeshStandardMaterial({ color: baseColor, roughness: 0.78, flatShading: true })
);
base.position.y = 0.06;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
let cursor = BASE_Y;
stages.forEach((contribution, index) => {
const height = (contribution / AXIS_MAX) * PLOT_HEIGHT;
const geometry = new THREE.CylinderGeometry(0.53, 0.59, height, 6, 1, false);
const material = new THREE.MeshStandardMaterial({
color: stageColors[index],
roughness: 0.86,
metalness: 0,
flatShading: true
});
const segment = new THREE.Mesh(geometry, material);
segment.position.y = cursor + height / 2;
segment.castShadow = true;
segment.receiveShadow = true;
segment.userData.stage = stageNames[index];
segment.userData.contribution = contribution;
group.add(segment);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({ color: 0x304641, transparent: true, opacity: 0.35 })
);
edges.position.copy(segment.position);
group.add(edges);
cursor += height;
});
group.add(makeFlag(cursor, flagColor));
const valueLabel = makeTextSprite(`${formatNumber(total)} u.s.`, {
worldWidth: 1.45,
fontSize: 68,
color: '#243a35',
border: 'rgba(54,79,72,0.22)'
});
valueLabel.position.set(0, cursor + 0.62, 0);
group.add(valueLabel);
const nameLabel = makeTextSprite(name, {
multiline: true,
worldWidth: 2.05,
fontSize: 54,
color: '#243a35',
border: 'rgba(54,79,72,0.16)'
});
nameLabel.position.set(0, -0.02, 1.02);
group.add(nameLabel);
scene.add(group);
return group;
}
const formatNumber = value => new Intl.NumberFormat('pt-BR', {
minimumFractionDigits: 1,
maximumFractionDigits: 1
}).format(value);
function computeModel(reuse, lossPercent) {
const n = Math.round(reuse) + 1;
const loss = THREE.MathUtils.clamp(lossPercent, 0, 95) / 100;
const survival = 1 - loss;
const usefulUses = loss === 0
? n
: (1 - Math.pow(survival, n)) / (1 - survival);
const expectedUnits = n / usefulUses;
const amortization = expectedUnits / n;
const scenario = [
30 * amortization,
4 * amortization,
3,
2 * amortization
];
const control = [18, 2, 1, 1];
return {
n,
loss,
usefulUses,
expectedUnits,
scenario,
control,
scenarioTotal: scenario.reduce((sum, value) => sum + value, 0),
controlTotal: control.reduce((sum, value) => sum + value, 0)
};
}
let currentModel = null;
let scenarioTower = null;
let controlTower = null;
function renderFactorTable() {
const factors = [
['Fabricação', 30, 18],
['Distribuição', 4, 2],
['Uso', 3, 1],
['Fim de vida', 2, 1]
];
document.getElementById('factorRows').innerHTML = factors.map((row, index) => `
<tr>
<td>
<span class="stage-name">
<span class="swatch" style="background:${stageColorCSS[index]}"></span>
${row[0]}
</span>
</td>
<td>${row[1]} u.s.</td>
<td>${row[2]} u.s.</td>
</tr>
`).join('');
}
function renderStageTable(model) {
const rows = stageNames.map((name, index) => `
<tr>
<td>
<span class="stage-name">
<span class="swatch" style="background:${stageColorCSS[index]}"></span>
${name}
</span>
</td>
<td>${formatNumber(model.scenario[index])}</td>
<td>${formatNumber(model.control[index])}</td>
</tr>
`).join('');
document.getElementById('stageRows').innerHTML = rows + `
<tr class="total">
<td>Total / sessão</td>
<td>${formatNumber(model.scenarioTotal)}</td>
<td>${formatNumber(model.controlTotal)}</td>
</tr>
`;
}
function renderSummary(model) {
document.getElementById('scenarioValue').textContent = formatNumber(model.scenarioTotal);
document.getElementById('controlValue').textContent = formatNumber(model.controlTotal);
const difference = model.scenarioTotal - model.controlTotal;
const percent = (difference / model.controlTotal) * 100;
const delta = document.getElementById('deltaSummary');
delta.classList.remove('positive', 'negative');
if (Math.abs(difference) < 0.05) {
delta.textContent = 'Cenário e controle coincidem nesta configuração sintética.';
} else {
delta.classList.add(difference > 0 ? 'positive' : 'negative');
const direction = difference > 0 ? 'acima' : 'abaixo';
delta.textContent =
`Cenário ${formatNumber(Math.abs(difference))} u.s. ${direction} do controle ` +
`(${percent > 0 ? '+' : ''}${formatNumber(percent)}%).`;
}
delta.setAttribute(
'aria-label',
`Cenário: ${formatNumber(model.scenarioTotal)} unidades sintéticas. ` +
`Controle: ${formatNumber(model.controlTotal)}. Diferença: ${formatNumber(difference)}.`
);
}
function svgChart(svg, values, currentX, xLabel, ariaLabel) {
const width = 320;
const height = 125;
const left = 33;
const right = 10;
const top = 10;
const bottom = 25;
const plotWidth = width - left - right;
const plotHeight = height - top - bottom;
const xMax = values[values.length - 1].x;
const toX = value => left + (value / xMax) * plotWidth;
const toY = value => top + (1 - value / AXIS_MAX) * plotHeight;
const grid = [0, 15, 30, 45].map(value => {
const y = toY(value);
return `
<line x1="${left}" y1="${y}" x2="${width - right}" y2="${y}" stroke="#dfe6df" stroke-width="1"/>
<text x="${left - 6}" y="${y + 3}" text-anchor="end" fill="#7a8782" font-size="8">${value}</text>
`;
}).join('');
const scenarioPoints = values.map(point => `${toX(point.x)},${toY(point.y)}`).join(' ');
const referenceY = toY(22);
const markerX = toX(currentX);
const markerY = toY(values.find(point => point.x === currentX)?.y ?? values[0].y);
svg.setAttribute('aria-label', ariaLabel);
svg.innerHTML = `
<title>${ariaLabel}</title>
${grid}
<line x1="${left}" y1="${referenceY}" x2="${width - right}" y2="${referenceY}"
stroke="#c96857" stroke-width="1.5" stroke-dasharray="5 4"/>
<polyline points="${scenarioPoints}" fill="none" stroke="#327d74" stroke-width="2.5"
stroke-linejoin="round" stroke-linecap="round"/>
<circle cx="${markerX}" cy="${markerY}" r="4" fill="#327d74" stroke="#fff" stroke-width="2"/>
<text x="${left}" y="${height - 6}" fill="#6e7c77" font-size="8">0</text>
<text x="${width - right}" y="${height - 6}" text-anchor="end" fill="#6e7c77" font-size="8">${xLabel}</text>
<text x="${left + plotWidth / 2}" y="${height - 6}" text-anchor="middle" fill="#6e7c77" font-size="8">${xLabel}</text>
`;
}
function renderSensitivity(model) {
const reuseValues = [];
for (let reuse = 0; reuse <= 20; reuse++) {
reuseValues.push({
x: reuse,
y: computeModel(reuse, model.loss * 100).scenarioTotal
});
}
const lossValues = [];
for (let loss = 0; loss <= 95; loss++) {
lossValues.push({
x: loss,
y: computeModel(model.n - 1, loss).scenarioTotal
});
}
svgChart(
document.getElementById('reuseChart'),
reuseValues,
model.n - 1,
'reusos',
'Cenário sintético em função do número de reusos, com perda constante'
);
svgChart(
document.getElementById('lossChart'),
lossValues,
model.loss * 100,
'perda (%)',
'Cenário sintético em função da taxa de perda, com reusos constantes'
);
}
function updateScene(model) {
if (scenarioTower) {
scene.remove(scenarioTower);
disposeObject(scenarioTower);
}
if (controlTower) {
scene.remove(controlTower);
disposeObject(controlTower);
}
scenarioTower = buildTower({
x: -1.28,
name: 'CENÁRIO\nCOMPARTILHADO',
stages: model.scenario,
total: model.scenarioTotal,
baseColor: 0x327d74,
flagColor: 0xe0aa46
});
controlTower = buildTower({
x: 1.28,
name: 'CONTROLE\nINDIVIDUAL',
stages: model.control,
total: model.controlTotal,
baseColor: 0xc96857,
flagColor: 0x557ca8
});
}
function update() {
const reuse = Number(document.getElementById('reuseInput').value);
const loss = Number(document.getElementById('lossInput').value);
document.getElementById('reuseOutput').textContent = String(reuse);
document.getElementById('lossOutput').textContent = `${loss}%`;
currentModel = computeModel(reuse, loss);
renderSummary(currentModel);
renderStageTable(currentModel);
renderSensitivity(currentModel);
updateScene(currentModel);
}
renderFactorTable();
update();
document.getElementById('reuseInput').addEventListener('input', update);
document.getElementById('lossInput').addEventListener('input', update);
document.querySelectorAll('.preset').forEach(button => {
button.addEventListener('click', () => {
document.getElementById('reuseInput').value = button.dataset.reuse;
document.getElementById('lossInput').value = button.dataset.loss;
update();
});
});
function directionFromOrbit() {
const cosPitch = Math.cos(orbit.pitch);
return new THREE.Vector3(
Math.sin(orbit.yaw) * cosPitch,
Math.sin(orbit.pitch),
Math.cos(orbit.yaw) * cosPitch
).normalize();
}
function requiredFitDistance(direction) {
const verticalFov = THREE.MathUtils.degToRad(camera.fov);
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * camera.aspect);
const tanVertical = Math.tan(verticalFov / 2);
const tanHorizontal = Math.tan(horizontalFov / 2);
const viewDirection = direction.clone().multiplyScalar(-1);
const right = new THREE.Vector3().crossVectors(viewDirection, new THREE.Vector3(0, 1, 0)).normalize();
const up = new THREE.Vector3().crossVectors(right, viewDirection).normalize();
const corners = [];
const xValues = [-3.22, 3.22];
const yValues = [-0.22, 4.28];
const zValues = [-1.05, 1.20];
xValues.forEach(x => yValues.forEach(y => zValues.forEach(z => {
corners.push(new THREE.Vector3(x, y, z));
})));
let distance = 0;
corners.forEach(corner => {
const relative = corner.clone().sub(orbit.target);
const towardCamera = relative.dot(direction);
const x = Math.abs(relative.dot(right));
const y = Math.abs(relative.dot(up));
distance = Math.max(
distance,
towardCamera + x / tanHorizontal,
towardCamera + y / tanVertical
);
});
return distance * 1.055;
}
function applyCamera() {
const direction = directionFromOrbit();
const minimumDistance = requiredFitDistance(direction);
orbit.distance = Math.max(orbit.distance, minimumDistance);
camera.position.copy(orbit.target).addScaledVector(direction, orbit.distance);
camera.lookAt(orbit.target);
camera.updateMatrixWorld();
}
function resetCamera() {
orbit.yaw = 0.18;
orbit.pitch = 0.16;
orbit.distance = requiredFitDistance(directionFromOrbit()) * 1.015;
applyCamera();
}
document.getElementById('fitButton').addEventListener('click', resetCamera);
const resizeObserver = new ResizeObserver(() => {
const width = Math.max(1, stageElement.clientWidth);
const height = Math.max(1, stageElement.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
applyCamera();
});
resizeObserver.observe(stageElement);
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener('pointerdown', event => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener('pointermove', event => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
orbit.yaw -= deltaX * 0.006;
orbit.pitch = THREE.MathUtils.clamp(orbit.pitch + deltaY * 0.0045, 0.08, 0.72);
applyCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener('pointerup', stopDragging);
renderer.domElement.addEventListener('pointercancel', stopDragging);
renderer.domElement.addEventListener('lostpointercapture', () => { dragging = false; });
renderer.domElement.addEventListener('wheel', event => {
event.preventDefault();
const minimum = requiredFitDistance(directionFromOrbit());
const factor = Math.exp(event.deltaY * 0.001);
orbit.distance = THREE.MathUtils.clamp(orbit.distance * factor, minimum, 20);
applyCamera();
}, { passive: false });
renderer.domElement.addEventListener('dblclick', resetCamera);
const initialWidth = Math.max(1, stageElement.clientWidth);
const initialHeight = Math.max(1, stageElement.clientHeight);
renderer.setSize(initialWidth, initialHeight, false);
camera.aspect = initialWidth / initialHeight;
camera.updateProjectionMatrix();
resetCamera();
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>
</body>
</html>
```