Prompt specification
Build or customize the Three.js 3D scene "Uniform and nonuniform scaling 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: Uniform and nonuniform scaling comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/uniform-and-nonuniform-scaling-comparison-x1734
Scene Description Prompt:
Create a standalone stylized scene in one HTML file using Three.js from cdnjs. Scale one asymmetric object uniformly and stretch another along one axis; show preserved versus changed angles and distinguish similarity from generic shape enlargement.
Technical checks: Convert measured angles from radians to degrees before displaying them. Compare the angles consistently and show which are preserved by uniform scaling.
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 (uniform-and-nonuniform-scaling-comparison-x1734):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laboratório de Escala — Semelhança e ampliação</title>
<style>
:root {
--ink: #173a3b;
--muted: #617274;
--paper: #f5f1e8;
--card: rgba(255, 255, 255, 0.88);
--teal: #26aaa6;
--teal-dark: #147b79;
--coral: #ef7b68;
--coral-dark: #b94e40;
--gold: #f2b84b;
--line: rgba(23, 58, 59, 0.13);
--shadow: 0 14px 40px rgba(31, 53, 52, 0.12);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body { overflow: hidden; }
button, input { font: inherit; }
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
width: 100%;
height: 100vh;
min-height: 650px;
}
#stage {
position: relative;
min-width: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 30%, rgba(255,255,255,.8), transparent 52%),
#eee9df;
}
#stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
.stage-heading {
position: absolute;
z-index: 3;
top: 24px;
left: 26px;
max-width: 410px;
pointer-events: none;
}
.eyebrow {
margin: 0 0 7px;
color: var(--teal-dark);
font-size: 11px;
font-weight: 850;
letter-spacing: .16em;
text-transform: uppercase;
}
.stage-heading h1 {
margin: 0;
font-size: clamp(25px, 3vw, 42px);
line-height: 1.02;
letter-spacing: -.045em;
}
.stage-heading p {
margin: 10px 0 0;
max-width: 390px;
color: var(--muted);
font-size: 14px;
line-height: 1.45;
}
.stage-legend {
position: absolute;
z-index: 3;
left: 26px;
bottom: 24px;
display: flex;
flex-wrap: wrap;
gap: 8px;
pointer-events: none;
}
.legend-chip {
display: flex;
align-items: center;
gap: 7px;
padding: 8px 11px;
border: 1px solid rgba(23, 58, 59, .12);
border-radius: 999px;
background: rgba(255,255,255,.76);
box-shadow: 0 6px 20px rgba(31,53,52,.08);
color: #43595a;
font-size: 11px;
font-weight: 700;
backdrop-filter: blur(8px);
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: currentColor;
}
.dot.teal { color: var(--teal); }
.dot.coral { color: var(--coral); }
.dot.ghost { color: #9ca7a5; }
.dot.angle { color: var(--gold); }
.scene-label,
.angle-label {
position: absolute;
z-index: 4;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.scene-label {
padding: 8px 12px;
border-radius: 10px;
background: rgba(255,255,255,.9);
border: 1px solid var(--line);
box-shadow: 0 8px 22px rgba(23,58,59,.12);
font-size: 11px;
font-weight: 850;
letter-spacing: .035em;
}
.scene-label.teal { border-left: 4px solid var(--teal); }
.scene-label.coral { border-left: 4px solid var(--coral); }
.angle-label {
padding: 7px 10px;
border-radius: 9px;
background: #203f40;
color: #fff8e8;
border: 2px solid var(--gold);
box-shadow: 0 8px 22px rgba(23,58,59,.2);
font-size: 12px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.angle-label::after {
content: "";
position: absolute;
width: 7px;
height: 7px;
left: 50%;
bottom: -11px;
transform: translateX(-50%) rotate(45deg);
background: #203f40;
border-right: 2px solid var(--gold);
border-bottom: 2px solid var(--gold);
}
aside {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 25px 23px 28px;
background: rgba(250, 248, 242, .96);
border-left: 1px solid rgba(23,58,59,.1);
box-shadow: -18px 0 45px rgba(31,53,52,.08);
}
aside::-webkit-scrollbar { width: 9px; }
aside::-webkit-scrollbar-thumb {
border: 3px solid transparent;
border-radius: 99px;
background: rgba(23,58,59,.2);
background-clip: padding-box;
}
.panel-intro {
margin-bottom: 18px;
padding-bottom: 18px;
border-bottom: 1px solid var(--line);
}
.panel-intro h2 {
margin: 0 0 8px;
font-size: 25px;
line-height: 1.06;
letter-spacing: -.035em;
}
.panel-intro p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.control-card {
margin-top: 13px;
padding: 17px;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--card);
box-shadow: var(--shadow);
}
.control-card.teal { border-top: 4px solid var(--teal); }
.control-card.coral { border-top: 4px solid var(--coral); }
.control-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.object-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 900;
letter-spacing: .06em;
text-transform: uppercase;
}
.object-name .swatch {
width: 12px;
height: 12px;
border-radius: 4px;
box-shadow: inset 0 0 0 1px rgba(0,0,0,.08);
}
.teal .swatch { background: var(--teal); }
.coral .swatch { background: var(--coral); }
.status {
padding: 5px 8px;
border-radius: 999px;
font-size: 9px;
font-weight: 900;
letter-spacing: .045em;
text-align: center;
}
.status.similar {
color: #0b6967;
background: #d8f1eb;
}
.status.different {
color: #a84538;
background: #fde2db;
}
.status.original {
color: #5f6f70;
background: #e8ecea;
}
.control-card h3 {
margin: 0 0 12px;
font-size: 18px;
letter-spacing: -.02em;
}
.range-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
output {
color: var(--ink);
font-variant-numeric: tabular-nums;
font-weight: 900;
}
input[type="range"] {
width: 100%;
height: 22px;
margin: 0;
accent-color: var(--teal);
cursor: pointer;
}
.coral input[type="range"] { accent-color: var(--coral); }
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.metric {
padding: 9px 10px;
border-radius: 10px;
background: rgba(23,58,59,.045);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .05em;
text-transform: uppercase;
}
.metric b {
display: block;
margin-top: 3px;
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.angle-readout {
display: grid;
grid-template-columns: 1fr auto;
gap: 4px 12px;
align-items: center;
margin: 12px 0;
padding: 11px 12px;
border: 1px solid rgba(242,184,75,.48);
border-radius: 12px;
background: rgba(255,248,218,.64);
}
.angle-readout span {
color: #796234;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: .05em;
}
.angle-readout b {
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.angle-readout small {
grid-column: 1 / -1;
color: #796234;
font-size: 11px;
line-height: 1.35;
}
.angle-table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.angle-table th {
padding: 4px 3px 7px;
color: var(--muted);
font-size: 9px;
letter-spacing: .05em;
text-align: right;
text-transform: uppercase;
}
.angle-table th:first-child,
.angle-table td:first-child { text-align: left; }
.angle-table td {
padding: 5px 3px;
border-top: 1px solid rgba(23,58,59,.08);
text-align: right;
}
.same { color: var(--teal-dark); font-weight: 800; }
.changed { color: var(--coral-dark); font-weight: 900; }
.explanation {
margin: 10px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.explanation strong { color: var(--ink); }
.preset-row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 16px;
}
button {
border: 0;
border-radius: 10px;
padding: 10px 8px;
background: #e6ece9;
color: var(--ink);
font-size: 11px;
font-weight: 850;
cursor: pointer;
transition: transform .15s ease, background .15s ease, box-shadow .15s ease;
}
button:hover {
transform: translateY(-1px);
background: #dce6e2;
box-shadow: 0 6px 14px rgba(23,58,59,.09);
}
button:active { transform: translateY(0); }
button.primary {
background: var(--ink);
color: white;
}
button.primary:hover { background: #235052; }
.test-card {
margin-top: 14px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255,255,255,.62);
}
.test-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.test-head strong {
font-size: 12px;
}
#testStatus {
color: var(--teal-dark);
font-size: 11px;
font-weight: 900;
}
#liveGeometry {
margin: 9px 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.formula {
margin: 11px 0 9px;
padding: 10px 11px;
border-radius: 10px;
background: #203f40;
color: #e9f4ef;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.5;
}
.test-card p {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.test-card button { width: 100%; margin-top: 11px; }
@media (max-width: 900px) {
body { overflow: auto; }
#app {
grid-template-columns: 1fr;
height: auto;
min-height: 100vh;
}
#stage { height: 64vh; min-height: 470px; }
aside {
overflow: visible;
border-left: 0;
border-top: 1px solid var(--line);
}
.stage-heading { top: 18px; left: 18px; }
.stage-heading p { max-width: 320px; }
.stage-legend { left: 18px; bottom: 16px; }
}
@media (max-width: 520px) {
.stage-heading h1 { font-size: 27px; }
.stage-heading p { display: none; }
.legend-chip { padding: 7px 9px; font-size: 9px; }
.angle-label { font-size: 10px; }
aside { padding: 21px 14px; }
}
</style>
</head>
<body>
<main id="app">
<section id="stage" aria-label="Cena tridimensional comparando escala uniforme e alongamento horizontal">
<div class="stage-heading">
<p class="eyebrow">Laboratório de escala</p>
<h1>Crescer não é o mesmo que preservar a forma.</h1>
<p>Compare o mesmo polígono assimétrico: um recebe escala uniforme; o outro é alongado apenas no eixo horizontal.</p>
</div>
<div class="stage-legend" aria-hidden="true">
<div class="legend-chip"><span class="dot ghost"></span>Forma original</div>
<div class="legend-chip"><span class="dot teal"></span>Escala uniforme</div>
<div class="legend-chip"><span class="dot coral"></span>Alongamento X</div>
<div class="legend-chip"><span class="dot angle"></span>Ângulo marcado</div>
</div>
<div id="uniformStageLabel" class="scene-label teal">TURQUESA · UNIFORME</div>
<div id="stretchStageLabel" class="scene-label coral">CORAL · EIXO X</div>
<div id="uniformAngleLabel" class="angle-label">106,5° → 106,5°</div>
<div id="stretchAngleLabel" class="angle-label">106,5° → 130,8°</div>
</section>
<aside>
<header class="panel-intro">
<p class="eyebrow">Semelhança × ampliação</p>
<h2>Observe as proporções, não só o tamanho.</h2>
<p>Uma figura ampliada pode deixar de ser semelhante quando seus lados ou ângulos mudam de proporção.</p>
</header>
<section class="control-card teal">
<div class="control-top">
<div class="object-name"><span class="swatch"></span>Turquesa</div>
<span id="uniformStatus" class="status similar">SEMELHANTE</span>
</div>
<h3>Escala uniforme</h3>
<label class="range-label" for="uniformScale">
Fator em X e Y
<output id="uniformOutput" for="uniformScale">1,35×</output>
</label>
<input id="uniformScale" type="range" min="1" max="1.6" step="0.05" value="1.35">
<div class="metrics">
<div class="metric"><span>Área</span><b id="uniformArea">1,82×</b></div>
<div class="metric"><span>Razões dos lados</span><b id="uniformRatios">1,35–1,35</b></div>
</div>
<div class="angle-readout">
<span>Ângulo marcado</span>
<b id="uniformAngle">106,5° → 106,5°</b>
<small id="uniformDelta">Variação: 0,0°. Os cinco ângulos foram preservados.</small>
</div>
<table class="angle-table" aria-label="Ângulos da forma turquesa">
<thead><tr><th>Vértice</th><th>Original</th><th>Agora</th></tr></thead>
<tbody id="uniformAngleRows"></tbody>
</table>
<p class="explanation"><strong>Semelhança:</strong> todos os lados crescem pelo mesmo fator e todos os ângulos permanecem iguais.</p>
</section>
<section class="control-card coral">
<div class="control-top">
<div class="object-name"><span class="swatch"></span>Coral</div>
<span id="stretchStatus" class="status different">NÃO SEMELHANTE</span>
</div>
<h3>Alongamento no eixo X</h3>
<label class="range-label" for="xStretch">
Fator somente em X
<output id="stretchOutput" for="xStretch">1,65×</output>
</label>
<input id="xStretch" type="range" min="1" max="2.2" step="0.05" value="1.65">
<div class="metrics">
<div class="metric"><span>Área</span><b id="stretchArea">1,65×</b></div>
<div class="metric"><span>Razões dos lados</span><b id="stretchRatios">0,87–1,99</b></div>
</div>
<div class="angle-readout">
<span>Ângulo marcado</span>
<b id="stretchAngle">106,5° → 130,8°</b>
<small id="stretchDelta">Variação: +24,3°. O ângulo foi alterado pelo alongamento.</small>
</div>
<table class="angle-table" aria-label="Ângulos da forma coral">
<thead><tr><th>Vértice</th><th>Original</th><th>Agora</th></tr></thead>
<tbody id="stretchAngleRows"></tbody>
</table>
<p class="explanation"><strong>Ampliação genérica:</strong> a área aumenta, mas as distâncias horizontal e vertical não mantêm a mesma proporção.</p>
</section>
<div class="preset-row" aria-label="Estados de comparação">
<button type="button" data-preset="baseline">Original</button>
<button type="button" data-preset="balanced">Contraste</button>
<button type="button" data-preset="extreme">Extremo</button>
</div>
<section class="test-card">
<div class="test-head">
<strong>Teste geométrico</strong>
<span id="testStatus" role="status" aria-live="polite">27/27 testes passaram</span>
</div>
<div id="liveGeometry">Turquesa: 0 ângulos alterados · Coral: 5 ângulos alterados</div>
<div class="formula">θ graus = acos((u·v)/(|u||v|)) × 180/π<br>Semelhante ⇔ razões dos lados iguais + ângulos iguais</div>
<p>Os cálculos convertem radianos para graus antes da exibição e da comparação. A classificação usa os comprimentos reais dos lados e os ângulos da geometria atual.</p>
<button id="runTests" class="primary" type="button">Executar testes novamente</button>
</section>
</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 $ = (selector) => document.querySelector(selector);
const stage = $('#stage');
const numberFormat = new Intl.NumberFormat('pt-BR', {
minimumFractionDigits: 1,
maximumFractionDigits: 1
});
const formatNumber = (value) => numberFormat.format(value);
const formatFactor = (value) => `${formatNumber(value)}×`;
const degreesEqual = (a, b, epsilon = 1e-6) => Math.abs(a - b) <= epsilon;
// O mesmo polígono assimétrico é usado nas duas comparações.
const BASE_POINTS = [
{ x: -1.04, y: 0.16 },
{ x: -0.56, y: 0.96 },
{ x: 0.56, y: 0.80 },
{ x: 1.04, y: -0.24 },
{ x: -0.16, y: -0.80 }
];
const SELECTED_VERTEX = 4;
const ANGLE_EPSILON = 0.05;
function transformedPoints(points, scaleX, scaleY = 1) {
return points.map((point) => ({
x: point.x * scaleX,
y: point.y * scaleY
}));
}
function sideLengths(points) {
return points.map((point, index) => {
const next = points[(index + 1) % points.length];
return Math.hypot(next.x - point.x, next.y - point.y);
});
}
function internalAnglesInDegrees(points) {
return points.map((point, index) => {
const previous = points[(index - 1 + points.length) % points.length];
const next = points[(index + 1) % points.length];
const ux = previous.x - point.x;
const uy = previous.y - point.y;
const vx = next.x - point.x;
const vy = next.y - point.y;
const cosine = (ux * vx + uy * vy) / (Math.hypot(ux, uy) * Math.hypot(vx, vy));
const radians = Math.acos(THREE.MathUtils.clamp(cosine, -1, 1));
// A conversão para graus ocorre uma única vez, na fronteira de cálculo.
return radians * 180 / Math.PI;
});
}
function polygonArea(points) {
let sum = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
sum += a.x * b.y - b.x * a.y;
}
return Math.abs(sum) / 2;
}
function analyzeGeometry(points) {
const baseLengths = sideLengths(BASE_POINTS);
const currentLengths = sideLengths(points);
return {
points,
degrees: internalAnglesInDegrees(points),
sideRatios: currentLengths.map((length, index) => length / baseLengths[index]),
area: polygonArea(points)
};
}
function classifyAsSimilar(base, current) {
const anglesPreserved = current.degrees.every(
(value, index) => degreesEqual(value, base.degrees[index], 1e-5)
);
const ratio = current.sideRatios[0];
const sidesPreserved = current.sideRatios.every(
(value) => degreesEqual(value, ratio, 1e-6)
);
return anglesPreserved && sidesPreserved;
}
const state = {
uniform: 1.35,
stretch: 1.65,
uniformAnalysis: null,
stretchAnalysis: null,
baseAnalysis: analyzeGeometry(BASE_POINTS)
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeee9df);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 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', 'Comparação tridimensional de escala uniforme e horizontal');
stage.prepend(renderer.domElement);
const camera = new THREE.OrthographicCamera(-6, 6, 5, -5, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.05, 0.15);
camera.position.set(0, 7.2, 9.4);
camera.lookAt(cameraTarget);
const hemisphere = new THREE.HemisphereLight(0xfff7e8, 0x78918d, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff4dc, 3.1);
keyLight.position.set(-4, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x9edbd5, 1.25);
rimLight.position.set(6, 3, -5);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({ color: 0xe9e4da, roughness: 0.94, metalness: 0 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.11;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(30, 30, 0x8ea29e, 0x9dadaa);
grid.position.y = -0.095;
grid.material.transparent = true;
grid.material.opacity = 0.12;
scene.add(grid);
function roundedRectangle(width, height, radius) {
const shape = new THREE.Shape();
const left = -width / 2;
const right = width / 2;
const bottom = -height / 2;
const top = height / 2;
shape.moveTo(left + radius, bottom);
shape.lineTo(right - radius, bottom);
shape.quadraticCurveTo(right, bottom, right, bottom + radius);
shape.lineTo(right, top - radius);
shape.quadraticCurveTo(right, top, right - radius, top);
shape.lineTo(left + radius, top);
shape.quadraticCurveTo(left, top, left, top - radius);
shape.lineTo(left, bottom + radius);
shape.quadraticCurveTo(left, bottom, left + radius, bottom);
shape.closePath();
return shape;
}
function createPlatform(x, accentColor) {
const group = new THREE.Group();
group.position.set(x, 0, 0.2);
const platformGeometry = new THREE.ExtrudeGeometry(
roundedRectangle(4.85, 3.55, 0.24),
{
depth: 0.12,
bevelEnabled: true,
bevelThickness: 0.045,
bevelSize: 0.045,
bevelSegments: 3,
curveSegments: 8
}
);
platformGeometry.rotateX(-Math.PI / 2);
const platform = new THREE.Mesh(
platformGeometry,
new THREE.MeshStandardMaterial({
color: 0xf8f5ee,
roughness: 0.76,
metalness: 0.02
})
);
platform.castShadow = true;
platform.receiveShadow = true;
group.add(platform);
const trimGeometry = new THREE.TorusGeometry(0.17, 0.035, 12, 36);
trimGeometry.rotateX(Math.PI / 2);
for (const z of [-1.48, 1.48]) {
const trim = new THREE.Mesh(
trimGeometry,
new THREE.MeshStandardMaterial({ color: accentColor, roughness: 0.42 })
);
trim.position.set(-2.12, 0.19, z);
group.add(trim);
}
scene.add(group);
return group;
}
function addGhostOutline(group) {
const closed = [...BASE_POINTS, BASE_POINTS[0]];
const geometry = new THREE.BufferGeometry().setFromPoints(
closed.map((point) => new THREE.Vector3(point.x, 0.185, -point.y))
);
const material = new THREE.LineDashedMaterial({
color: 0x81918f,
dashSize: 0.085,
gapSize: 0.06,
transparent: true,
opacity: 0.58
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
group.add(line);
}
const uniformGroup = createPlatform(-2.55, 0x26aaa6);
const stretchGroup = createPlatform(2.55, 0xef7b68);
addGhostOutline(uniformGroup);
addGhostOutline(stretchGroup);
const uniformDynamic = new THREE.Group();
const stretchDynamic = new THREE.Group();
uniformGroup.add(uniformDynamic);
stretchGroup.add(stretchDynamic);
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) => material.dispose());
}
});
}
function clearDynamic(group) {
while (group.children.length) {
const child = group.children.pop();
disposeObject(child);
}
}
function buildExtrudedShape(points, color, outlineColor) {
const shape = new THREE.Shape();
shape.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
shape.lineTo(points[i].x, points[i].y);
}
shape.closePath();
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: 0.27,
bevelEnabled: true,
bevelThickness: 0.045,
bevelSize: 0.038,
bevelSegments: 3,
curveSegments: 1
});
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color,
roughness: 0.34,
metalness: 0.05
})
);
mesh.rotation.x = -Math.PI / 2;
mesh.position.y = 0.16;
mesh.castShadow = true;
mesh.receiveShadow = true;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 24),
new THREE.LineBasicMaterial({
color: outlineColor,
transparent: true,
opacity: 0.75
})
);
mesh.add(edges);
return mesh;
}
function buildAngleArc(points, radius = 0.29, height = 0.50) {
const current = points[SELECTED_VERTEX];
const previous = points[(SELECTED_VERTEX - 1 + points.length) % points.length];
const next = points[(SELECTED_VERTEX + 1) % points.length];
// Os ângulos são calculados no plano da figura; o eixo Y do Three.js
// corresponde à coordenada Z negated nesta disposição horizontal.
const previousVector = { x: previous.x - current.x, y: previous.y - current.y };
const nextVector = { x: next.x - current.x, y: next.y - current.y };
const start = Math.atan2(-previousVector.y, previousVector.x);
const end = Math.atan2(-nextVector.y, nextVector.x);
const delta = Math.atan2(Math.sin(end - start), Math.cos(end - start));
const arcPoints = [];
for (let i = 0; i <= 32; i++) {
const angle = start + delta * (i / 32);
arcPoints.push(new THREE.Vector3(
current.x + Math.cos(angle) * radius,
height,
-current.y + Math.sin(angle) * radius
));
}
return new THREE.Line(
new THREE.BufferGeometry().setFromPoints(arcPoints),
new THREE.LineBasicMaterial({ color: 0xf2b84b })
);
}
function applyVisual(group, dynamic, analysis, color, outlineColor) {
clearDynamic(dynamic);
const mesh = buildExtrudedShape(analysis.points, color, outlineColor);
dynamic.add(mesh);
const arc = buildAngleArc(analysis.points);
dynamic.add(arc);
const selected = analysis.points[SELECTED_VERTEX];
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.055, 16, 12),
new THREE.MeshStandardMaterial({
color: 0xf2b84b,
emissive: 0x5b3500,
emissiveIntensity: 0.18,
roughness: 0.35
})
);
marker.position.set(selected.x, 0.54, -selected.y);
dynamic.add(marker);
const baseSelected = BASE_POINTS[SELECTED_VERTEX];
const connectorGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(baseSelected.x, 0.53, -baseSelected.y),
new THREE.Vector3(selected.x, 0.53, -selected.y)
]);
const connector = new THREE.Line(
connectorGeometry,
new THREE.LineDashedMaterial({
color: 0x546c6d,
dashSize: 0.045,
gapSize: 0.035,
transparent: true,
opacity: 0.65
})
);
connector.computeLineDistances();
dynamic.add(connector);
}
function changedAngleCount(base, current) {
return current.degrees.filter(
(value, index) => Math.abs(value - base.degrees[index]) > ANGLE_EPSILON
).length;
}
function fillAngleRows(target, base, current) {
target.innerHTML = current.degrees.map((value, index) => {
const changed = Math.abs(value - base.degrees[index]) > ANGLE_EPSILON;
return `
<tr>
<td>V${index + 1}</td>
<td>${formatNumber(base.degrees[index])}°</td>
<td class="${changed ? 'changed' : 'same'}">${formatNumber(value)}°</td>
</tr>
`;
}).join('');
}
function ratioRange(ratios) {
return `${formatNumber(Math.min(...ratios))}–${formatNumber(Math.max(...ratios))}`;
}
function updateUniformPanel() {
const base = state.baseAnalysis;
const current = state.uniformAnalysis;
const similar = classifyAsSimilar(base, current);
const changed = changedAngleCount(base, current);
const areaRatio = current.area / base.area;
const selectedDelta = current.degrees[SELECTED_VERTEX] - base.degrees[SELECTED_VERTEX];
$('#uniformOutput').value = formatFactor(state.uniform);
$('#uniformArea').textContent = formatFactor(areaRatio);
$('#uniformRatios').textContent = ratioRange(current.sideRatios);
$('#uniformAngle').textContent =
`${formatNumber(base.degrees[SELECTED_VERTEX])}° → ${formatNumber(current.degrees[SELECTED_VERTEX])}°`;
const deltaText = selectedDelta > ANGLE_EPSILON
? `Variação: ${selectedDelta > 0 ? '+' : ''}${formatNumber(selectedDelta)}°.`
: 'Variação: 0,0°.';
$('#uniformDelta').textContent = `${deltaText} ${
changed === 0 ? 'Os cinco ângulos foram preservados.' : `${changed} ângulo(s) alterado(s).`
}`;
const status = $('#uniformStatus');
if (state.uniform <= 1.0001) {
status.className = 'status original';
status.textContent = 'FORMA ORIGINAL';
} else {
status.className = 'status similar';
status.textContent = 'SEMELHANTE';
}
fillAngleRows($('#uniformAngleRows'), base, current);
$('#uniformAngleLabel').textContent =
`${formatNumber(base.degrees[SELECTED_VERTEX])}° → ${formatNumber(current.degrees[SELECTED_VERTEX])}°`;
}
function updateStretchPanel() {
const base = state.baseAnalysis;
const current = state.stretchAnalysis;
const similar = classifyAsSimilar(base, current);
const changed = changedAngleCount(base, current);
const areaRatio = current.area / base.area;
const selectedDelta = current.degrees[SELECTED_VERTEX] - base.degrees[SELECTED_VERTEX];
$('#stretchOutput').value = formatFactor(state.stretch);
$('#stretchArea').textContent = formatFactor(areaRatio);
$('#stretchRatios').textContent = ratioRange(current.sideRatios);
$('#stretchAngle').textContent =
`${formatNumber(base.degrees[SELECTED_VERTEX])}° → ${formatNumber(current.degrees[SELECTED_VERTEX])}°`;
const deltaText = selectedDelta > ANGLE_EPSILON
? `Variação: ${selectedDelta > 0 ? '+' : ''}${formatNumber(selectedDelta)}°.`
: 'Variação: 0,0°.';
$('#stretchDelta').textContent = `${deltaText} ${
changed === 0
? 'Nenhum ângulo foi alterado.'
: 'O alongamento alterou a proporção angular.'
}`;
const status = $('#stretchStatus');
if (state.stretch <= 1.0001) {
status.className = 'status original';
status.textContent = 'FORMA ORIGINAL';
} else if (similar) {
status.className = 'status similar';
status.textContent = 'SEMELHANTE';
} else {
status.className = 'status different';
status.textContent = 'NÃO SEMELHANTE';
}
fillAngleRows($('#stretchAngleRows'), base, current);
$('#stretchAngleLabel').textContent =
`${formatNumber(base.degrees[SELECTED_VERTEX])}° → ${formatNumber(current.degrees[SELECTED_VERTEX])}°`;
}
function runGeometryTests() {
const results = [];
const assert = (name, condition, detail = '') => {
results.push({ name, passed: Boolean(condition), detail });
};
const base = state.baseAnalysis;
assert('O polígono possui cinco vértices', base.degrees.length === 5);
assert(
'Todos os ângulos são finitos e estão entre 0° e 180°',
base.degrees.every((angle) => Number.isFinite(angle) && angle > 0 && angle < 180)
);
assert(
'O ângulo marcado é visivelmente obtuso na forma original',
base.degrees[SELECTED_VERTEX] > 90,
`${formatNumber(base.degrees[SELECTED_VERTEX])}°`
);
for (const factor of [1, 1.35, 1.6]) {
const analysis = analyzeGeometry(transformedPoints(BASE_POINTS, factor, factor));
assert(
`Escala uniforme ${formatFactor(factor)} preserva os ângulos`,
analysis.degrees.every((angle, index) => degreesEqual(angle, base.degrees[index], 1e-5))
);
assert(
`Escala uniforme ${formatFactor(factor)} é classificada como semelhante`,
classifyAsSimilar(base, analysis)
);
assert(
`Escala uniforme ${formatFactor(factor)} multiplica a área por ${formatNumber(factor * factor)}`,
degreesEqual(analysis.area / base.area, factor * factor, 1e-5)
);
}
for (const factor of [1.25, 1.65, 2.2]) {
const analysis = analyzeGeometry(transformedPoints(BASE_POINTS, factor));
const changed = changedAngleCount(base, analysis);
assert(
`Alongamento X ${formatFactor(factor)} altera ao menos um ângulo`,
changed > 0,
`${changed} ângulos alterados`
);
assert(
`Alongamento X ${formatFactor(factor)} não é classificado como semelhante`,
!classifyAsSimilar(base, analysis)
);
assert(
`Alongamento X ${formatFactor(factor)} multiplica a área por ${formatFactor(factor)}`,
degreesEqual(analysis.area / base.area, factor, 1e-5)
);
}
assert(
'A escala uniforme atual preserva os cinco ângulos',
state.uniformAnalysis.degrees.every(
(angle, index) => degreesEqual(angle, base.degrees[index], 1e-5)
)
);
assert(
'A escala uniforme atual é semelhante',
classifyAsSimilar(base, state.uniformAnalysis)
);
if (state.stretch > 1.0001) {
assert(
'O alongamento atual altera ângulos medidos em graus',
changedAngleCount(base, state.stretchAnalysis) > 0
);
assert(
'O alongamento atual não é semelhante',
!classifyAsSimilar(base, state.stretchAnalysis)
);
} else {
assert(
'Sem deformação, os ângulos permanecem iguais',
changedAngleCount(base, state.stretchAnalysis) === 0
);
assert(
'Sem deformação, a figura continua semelhante',
classifyAsSimilar(base, state.stretchAnalysis)
);
}
const displayedAngles = [
...state.uniformAnalysis.degrees,
...state.stretchAnalysis.degrees
];
assert(
'Todos os valores destinados à tela são graus válidos',
displayedAngles.every((angle) => angle > 0 && angle < 180)
);
const degreeDelta = Math.abs(
analyzeGeometry(transformedPoints(BASE_POINTS, 1.65)).degrees[SELECTED_VERTEX] -
base.degrees[SELECTED_VERTEX]
);
const radianDelta = degreeDelta * Math.PI / 180;
assert(
'A comparação angular não confunde graus com radianos',
degreeDelta > 5 && radianDelta < 2,
`${formatNumber(degreeDelta)}° = ${radianDelta.toFixed(3)} rad`
);
const passed = results.filter((result) => result.passed).length;
$('#testStatus').textContent = `${passed}/${results.length} testes passaram`;
$('#testStatus').style.color = passed === results.length ? 'var(--teal-dark)' : 'var(--coral-dark)';
const uniformChanged = changedAngleCount(base, state.uniformAnalysis);
const stretchChanged = changedAngleCount(base, state.stretchAnalysis);
$('#liveGeometry').textContent =
`Turquesa: ${uniformChanged} ângulos alterados · Coral: ${stretchChanged} ângulos alterados`;
return { passed, total: results.length, results };
}
function updateAll() {
state.uniform = Number($('#uniformScale').value);
state.stretch = Number($('#xStretch').value);
state.uniformAnalysis = analyzeGeometry(transformedPoints(BASE_POINTS, state.uniform, state.uniform));
state.stretchAnalysis = analyzeGeometry(transformedPoints(BASE_POINTS, state.stretch, 1));
applyVisual(uniformGroup, uniformDynamic, state.uniformAnalysis, 0x26aaa6, 0x116f6c);
applyVisual(stretchGroup, stretchDynamic, state.stretchAnalysis, 0xef7b68, 0xa74336);
updateUniformPanel();
updateStretchPanel();
runGeometryTests();
}
$('#uniformScale').addEventListener('input', updateAll);
$('#xStretch').addEventListener('input', updateAll);
document.querySelectorAll('[data-preset]').forEach((button) => {
button.addEventListener('click', () => {
const preset = button.dataset.preset;
if (preset === 'baseline') {
$('#uniformScale').value = '1';
$('#xStretch').value = '1';
} else if (preset === 'balanced') {
$('#uniformScale').value = '1.35';
$('#xStretch').value = '1.65';
} else {
$('#uniformScale').value = '1.6';
$('#xStretch').value = '2.2';
}
updateAll();
});
});
$('#runTests').addEventListener('click', () => {
updateAll();
const result = runGeometryTests();
const button = $('#runTests');
const original = button.textContent;
button.textContent = result.passed === result.total
? 'Tudo certo: geometria verificada'
: 'Revisar os testes';
setTimeout(() => { button.textContent = original; }, 1800);
});
function resizeRenderer() {
const width = Math.max(stage.clientWidth, 1);
const height = Math.max(stage.clientHeight, 1);
const aspect = width / height;
const verticalSize = Math.max(7.2, 11.4 / aspect);
const horizontalSize = verticalSize * aspect;
camera.left = -horizontalSize / 2;
camera.right = horizontalSize / 2;
camera.top = verticalSize / 2;
camera.bottom = -verticalSize / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
resizeRenderer();
function placeLabel(element, worldPosition, offsetX = 0, offsetY = 0) {
const projected = worldPosition.clone().project(camera);
const x = (projected.x * 0.5 + 0.5) * stage.clientWidth + offsetX;
const y = (-projected.y * 0.5 + 0.5) * stage.clientHeight + offsetY;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateProjectedLabels() {
const uniformSelected = state.uniformAnalysis.points[SELECTED_VERTEX];
const stretchSelected = state.stretchAnalysis.points[SELECTED_VERTEX];
placeLabel(
$('#uniformAngleLabel'),
new THREE.Vector3(
uniformGroup.position.x + uniformSelected.x,
0.69,
uniformGroup.position.z - uniformSelected.y
),
-7,
-8
);
placeLabel(
$('#stretchAngleLabel'),
new THREE.Vector3(
stretchGroup.position.x + stretchSelected.x,
0.69,
stretchGroup.position.z - stretchSelected.y
),
7,
-8
);
placeLabel(
$('#uniformStageLabel'),
new THREE.Vector3(uniformGroup.position.x, 0.28, uniformGroup.position.z + 1.72),
0,
0
);
placeLabel(
$('#stretchStageLabel'),
new THREE.Vector3(stretchGroup.position.x, 0.28, stretchGroup.position.z + 1.72),
0,
0
);
}
updateAll();
renderer.setAnimationLoop(() => {
updateProjectedLabels();
renderer.render(scene, camera);
});
// Diagnóstico programático do estado e dos testes reais da geometria.
window.__scaleLab = {
getState: () => ({
uniform: state.uniform,
stretch: state.stretch,
uniformAngles: [...state.uniformAnalysis.degrees],
stretchAngles: [...state.stretchAnalysis.degrees],
uniformIsSimilar: classifyAsSimilar(state.baseAnalysis, state.uniformAnalysis),
stretchIsSimilar: classifyAsSimilar(state.baseAnalysis, state.stretchAnalysis)
}),
runTests: runGeometryTests
};
</script>
</body>
</html>
```