Prompt specification
Build or customize the Three.js 3D scene "Wider Door Versus Alternate Route" 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: Wider Door Versus Alternate Route
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/wider-door-versus-alternate-route-x3716
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: wider door versus alternate route. Compare two modifications to the same toy crowd layout under identical arrivals. Measure simulated waiting and completion counts while stating the limitations of the chosen agent rules. Return one self-contained HTML file.
Technical checks: Send the same 32 arrivals through both scenarios. Let people complete their crossings in both runs and compare completions or waiting times from the simulated movement.
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 (wider-door-versus-alternate-route-x3716):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Porta larga ou rota alternativa?</title>
<link rel="icon" href="data:,">
<style>
:root {
color-scheme: dark;
--bg: #0b1220;
--panel: #121d30;
--panel-2: #17243a;
--line: #2b3b55;
--text: #eef4ff;
--muted: #a8b7ce;
--blue: #67b7ff;
--green: #55e3ad;
--amber: #ffd166;
--red: #ff7b8d;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
min-height: 100vh;
background:
radial-gradient(circle at 15% 0%, rgba(61, 128, 189, .16), transparent 34rem),
radial-gradient(circle at 90% 10%, rgba(55, 192, 139, .10), transparent 32rem),
var(--bg);
}
button {
appearance: none;
border: 1px solid #38506f;
border-radius: 10px;
background: #1b2a43;
color: var(--text);
padding: .65rem .82rem;
font: inherit;
font-size: .86rem;
font-weight: 700;
cursor: pointer;
transition: background .15s, transform .15s, border-color .15s;
}
button:hover {
background: #263b5d;
border-color: #5877a1;
transform: translateY(-1px);
}
button:focus-visible {
outline: 3px solid rgba(103, 183, 255, .45);
outline-offset: 2px;
}
button.primary {
background: #176b9d;
border-color: #479bd1;
}
button.test {
background: #3e3150;
border-color: #786090;
}
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
}
header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1.5rem;
padding: 1.05rem 1.25rem .85rem;
border-bottom: 1px solid rgba(91, 116, 151, .25);
}
.eyebrow {
color: var(--blue);
font-size: .72rem;
font-weight: 800;
letter-spacing: .13em;
text-transform: uppercase;
margin-bottom: .32rem;
}
h1 {
margin: 0;
font-size: clamp(1.25rem, 2.2vw, 2rem);
line-height: 1.12;
letter-spacing: -.025em;
}
.objective {
margin: .45rem 0 0;
max-width: 820px;
color: var(--muted);
font-size: .91rem;
line-height: 1.45;
}
.controls {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
align-items: center;
gap: .5rem;
min-width: 340px;
}
.clock-panel {
width: 100%;
text-align: right;
color: var(--muted);
font-size: .78rem;
}
.clock {
color: var(--text);
font-weight: 850;
font-variant-numeric: tabular-nums;
font-size: 1rem;
}
main {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
padding: .85rem 1.25rem 1rem;
gap: .8rem;
}
.metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: .8rem;
}
.metric-card {
position: relative;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 14px;
background: linear-gradient(145deg, rgba(24, 39, 63, .96), rgba(16, 28, 46, .96));
padding: .72rem .85rem .76rem;
box-shadow: 0 10px 28px rgba(0, 0, 0, .15);
}
.metric-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--accent);
}
.metric-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: .6rem;
margin-bottom: .6rem;
}
.scenario-name {
display: flex;
align-items: center;
gap: .55rem;
font-size: .95rem;
font-weight: 850;
}
.badge {
display: inline-grid;
place-items: center;
width: 1.55rem;
height: 1.55rem;
border-radius: 7px;
color: #07111f;
background: var(--accent);
font-weight: 900;
}
.geometry {
color: var(--muted);
font-size: .74rem;
text-align: right;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: .5rem;
}
.metric {
min-width: 0;
padding: .48rem .58rem;
border: 1px solid rgba(102, 128, 164, .22);
border-radius: 9px;
background: rgba(7, 15, 28, .34);
}
.metric .name {
display: block;
color: var(--muted);
font-size: .66rem;
font-weight: 750;
letter-spacing: .045em;
text-transform: uppercase;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.metric .value {
display: block;
margin-top: .2rem;
font-size: clamp(.94rem, 1.6vw, 1.22rem);
font-weight: 850;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.metric .sub {
display: block;
min-height: .9rem;
margin-top: .1rem;
color: var(--muted);
font-size: .65rem;
}
.stage {
position: relative;
flex: 1;
min-height: 460px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 16px;
background: #101a2b;
box-shadow: inset 0 0 60px rgba(0, 0, 0, .2), 0 15px 40px rgba(0, 0, 0, .2);
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.stage-hint {
position: absolute;
left: .8rem;
bottom: .7rem;
padding: .45rem .62rem;
border: 1px solid rgba(120, 148, 186, .28);
border-radius: 9px;
background: rgba(7, 13, 24, .72);
color: #bdcbe0;
font-size: .7rem;
pointer-events: none;
backdrop-filter: blur(6px);
}
.legend {
position: absolute;
top: .72rem;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: .75rem;
padding: .43rem .7rem;
border: 1px solid rgba(120, 148, 186, .26);
border-radius: 999px;
background: rgba(7, 13, 24, .73);
color: #c9d5e6;
font-size: .68rem;
pointer-events: none;
backdrop-filter: blur(6px);
}
.dot {
display: inline-block;
width: .52rem;
height: .52rem;
margin-right: .28rem;
border-radius: 50%;
background: var(--blue);
}
.dot.green { background: var(--green); }
.dot.gray { background: #8c9bb0; }
.notes {
display: grid;
grid-template-columns: minmax(0, 1.35fr) minmax(320px, .65fr);
gap: .8rem;
}
.note-card {
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(18, 29, 48, .88);
padding: .72rem .85rem;
}
.note-card h2 {
margin: 0 0 .42rem;
font-size: .82rem;
letter-spacing: .025em;
}
.note-card p, .note-card li {
margin: 0;
color: var(--muted);
font-size: .73rem;
line-height: 1.45;
}
.note-card ul {
margin: .2rem 0 0;
padding-left: 1.1rem;
}
details summary {
cursor: pointer;
color: var(--text);
font-size: .79rem;
font-weight: 800;
}
#diagSummary {
margin-top: .55rem;
color: #cbd8ea;
font-size: .72rem;
line-height: 1.45;
}
#diagChecks {
display: grid;
gap: .25rem;
margin-top: .5rem;
color: var(--muted);
font-size: .7rem;
}
.pass { color: var(--green); font-weight: 850; }
.fail { color: var(--red); font-weight: 850; }
.footer-note {
color: #73839a;
font-size: .66rem;
text-align: center;
padding: 0 .8rem .25rem;
}
@media (max-width: 900px) {
header { flex-direction: column; }
.controls { min-width: 0; justify-content: flex-start; }
.clock-panel { text-align: left; }
.notes { grid-template-columns: 1fr; }
.metric-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.stage { min-height: 520px; }
}
@media (max-width: 680px) {
header, main { padding-left: .7rem; padding-right: .7rem; }
.metrics { grid-template-columns: 1fr; }
.geometry { max-width: 45%; }
.legend { display: none; }
.stage { min-height: 470px; }
.controls button { flex: 1 1 auto; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div>
<div class="eyebrow">Experimento de fluxo · toy crowd 3D</div>
<h1>Porta larga ou rota alternativa?</h1>
<p class="objective">
Objetivo: com as mesmas 32 chegadas e os mesmos agentes, comparar a fila, o tempo de espera
e a conclusão da travessia quando se amplia a porta ou se desvia o fluxo.
</p>
</div>
<div class="controls">
<div class="clock-panel">
<span id="clock" class="clock">03:49,9 / 06:00,0</span>
<span id="playState"> · pausado</span>
</div>
<button id="playBtn" class="primary" type="button">▶ Continuar</button>
<button id="resetBtn" type="button">↺ Recomeçar</button>
<button id="testBtn" class="test" type="button">Testar 04:49,9</button>
<button id="speedBtn" type="button">Velocidade 4×</button>
<button id="cameraBtn" type="button">Câmera inicial</button>
</div>
</header>
<main>
<section class="metrics" aria-label="Métricas das duas modificações">
<article class="metric-card" style="--accent: var(--blue)">
<div class="metric-head">
<div class="scenario-name"><span class="badge">A</span> Porta ampliada</div>
<div class="geometry">Abertura 3,2 m · 2 faixas · percurso 15,6 m</div>
</div>
<div class="metric-grid">
<div class="metric">
<span class="name">Chegadas</span>
<strong id="aArrived" class="value">—</strong>
<span id="aArrivedSub" class="sub">de 32</span>
</div>
<div class="metric">
<span class="name">Concluídos</span>
<strong id="aDone" class="value">—</strong>
<span id="aDoneSub" class="sub">no objetivo</span>
</div>
<div class="metric">
<span class="name">Espera média</span>
<strong id="aWait" class="value">—</strong>
<span id="aWaitSub" class="sub">somente na passagem</span>
</div>
<div class="metric">
<span class="name">32/32 concluídos</span>
<strong id="aFinish" class="value">—</strong>
<span id="aFinishSub" class="sub">tempo total</span>
</div>
</div>
</article>
<article class="metric-card" style="--accent: var(--green)">
<div class="metric-head">
<div class="scenario-name"><span class="badge">B</span> Rota alternativa</div>
<div class="geometry">Desvio 1,6 m · 1 faixa · percurso 21,0 m</div>
</div>
<div class="metric-grid">
<div class="metric">
<span class="name">Chegadas</span>
<strong id="bArrived" class="value">—</strong>
<span id="bArrivedSub" class="sub">de 32</span>
</div>
<div class="metric">
<span class="name">Concluídos</span>
<strong id="bDone" class="value">—</strong>
<span id="bDoneSub" class="sub">no objetivo</span>
</div>
<div class="metric">
<span class="name">Espera média</span>
<strong id="bWait" class="value">—</strong>
<span id="bWaitSub" class="sub">somente na passagem</span>
</div>
<div class="metric">
<span class="name">32/32 concluídos</span>
<strong id="bFinish" class="value">—</strong>
<span id="bFinishSub" class="sub">tempo total</span>
</div>
</div>
</article>
</section>
<section id="stage" class="stage" aria-label="Cena tridimensional comparativa">
<canvas id="scene"></canvas>
<div class="legend">
<span><i class="dot"></i>porta / passagem direta</span>
<span><i class="dot green"></i>rota alternativa</span>
<span><i class="dot gray"></i>saída</span>
</div>
<div class="stage-hint">Arraste para orbitar · roda do mouse para zoom · duplo clique para restaurar</div>
</section>
<section class="notes">
<article class="note-card">
<h2>Regras do agente e limitações do modelo</h2>
<ul>
<li>
Cada toy é um ponto cinemático individual, com velocidade constante de 1,15–1,25 m/s.
Não há famílias, grupos, negociação, pânico, escolha de rota ou reação à visão dos outros agentes.
</li>
<li>
A fila é criada por capacidade limitada da faixa de passagem: portas de 3,2 m têm duas faixas;
a rota alternativa tem uma faixa. Não há teletransporte nem avanço através de ninguém.
</li>
<li>
“Espera” mede apenas o tempo parado junto ao gargalo, não o percurso a pé. A travessia é
reservar uma faixa e atravessá-la a 2,6 m/s no cenário A ou 2,2 m/s no B.
</li>
<li>
As chegadas são sintéticas, determinísticas e idênticas, em quatro rajadas. O resultado é
didático e comparativo; não é calibração de evacuação, não representa diferentes melodias
de preferência e não inclui acessibilidade, mancas, carrinhos ou-demandas além das 32 chegadas.
</li>
</ul>
</article>
<article class="note-card">
<details open>
<summary>Diagnóstico do estado que causava o defeito</summary>
<div id="diagSummary">Calculando teste…</div>
<div id="diagChecks"></div>
</details>
</article>
</section>
<div class="footer-note">
As duas cenas usam o mesmo 탐ulo, origem, destino, parede-base e lista de chegadas.
O mostrador de conclusão usa o tempo simulado, não um contador prefixado.
</div>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const stage = $("stage");
const canvas = $("scene");
const COLORS = {
blue: 0x67b7ff,
green: 0x55e3ad,
amber: 0xffd166,
wall: 0x45546b,
wallTop: 0x64748b,
floor: 0x26364d,
dark: 0x142034
};
const AGENT_COLORS = [
0xfb7185, 0xfbbf24, 0x34d399, 0x60a5fa, 0xc084fc, 0xf97316
];
const ARRIVAL_OFFSETS = [0, 0.8, 1.6, 2.4, 3.8, 4.6, 5.4, 6.2];
const ARRIVALS = [];
for (let group = 0; group < 4; group++) {
for (const offset of ARRIVAL_OFFSETS) {
ARRIVALS.push(75 * group + offset);
}
}
const SIM_END = 360;
const REVIEW_TIME = 289.9;
const DEFAULT_TIME = 229.9;
function formatClock(seconds, comma = true) {
const safe = Math.max(0, seconds);
const min = Math.floor(safe / 60);
const sec = safe - min * 60;
const secText = sec.toFixed(1).padStart(4, "0");
return `${String(min).padStart(2, "0")}:${comma ? secText.replace(".", ",") : secText}`;
}
function pathLength(points) {
let length = 0;
for (let i = 1; i < points.length; i++) {
length += Math.hypot(points[i].x - points[i - 1].x, points[i].z - points[i - 1].z);
}
return length;
}
function pointOnPath(points, distance) {
let remaining = Math.max(0, distance);
for (let i = 1; i < points.length; i++) {
const a = points[i - 1];
const b = points[i];
const dx = b.x - a.x;
const dz = b.z - a.z;
const segmentLength = Math.hypot(dx, dz);
if (remaining <= segmentLength || i === points.length - 1) {
const u = segmentLength > 0 ? Math.min(1, remaining / segmentLength) : 0;
return {
x: a.x + dx * u,
z: a.z + dz * u,
dx: segmentLength ? dx / segmentLength : 1,
dz: segmentLength ? dz / segmentLength : 0
};
}
remaining -= segmentLength;
}
return { x: points[0].x, z: points[0].z, dx: 1, dz: 0 };
}
function createSimulation(type) {
const isA = type === "A";
const laneCount = isA ? 2 : 1;
const crossingDuration = isA ? 2.6 : 2.2;
const lanes = Array.from({ length: laneCount }, () => ({ nextFree: 0 }));
const agents = ARRIVALS.map((arrival, id) => {
const lane = isA ? id % 2 : 0;
const laneZ = isA ? (lane === 0 ? -0.58 : 0.58) : 4.05;
const spawnZ = ((id % 5) - 2) * 0.17;
const approachPoints = isA
? [{ x: -7.8, z: spawnZ }, { x: -2.8, z: laneZ }]
: [
{ x: -7.8, z: spawnZ },
{ x: -4.0, z: spawnZ },
{ x: -2.8, z: 4.05 }
];
const exitPoints = isA
? [{ x: 2.8, z: laneZ }, { x: 7.8, z: laneZ }]
: [
{ x: 3.0, z: 4.05 },
{ x: 5.0, z: 0 },
{ x: 7.8, z: 0 }
];
return {
id,
arrival,
speed: 1.15 + (id % 4) * 0.035,
lane,
laneZ,
spawnZ,
approachPoints,
approachLength: pathLength(approachPoints),
exitPoints,
exitLength: pathLength(exitPoints),
arrived: false,
state: "future",
approachDistance: 0,
exitDistance: 0,
reachedGateAt: null,
crossStart: null,
wait: null,
doneAt: null
};
});
return {
type,
isA,
time: 0,
lanes,
crossingDuration,
agents,
queue: [],
gateStart: isA ? { x: -2.8, z: 0 } : { x: -2.8, z: 4.05 },
gateEnd: isA ? { x: 2.8, z: 0 } : { x: 3.0, z: 4.05 }
};
}
function advanceWorld(world, dt) {
world.time += dt;
for (const agent of world.agents) {
if (!agent.arrived) {
if (world.time + 1e-9 >= agent.arrival) {
agent.arrived = true;
agent.state = "approach";
} else {
continue;
}
}
if (agent.state === "approach") {
agent.approachDistance += agent.speed * dt;
if (agent.approachDistance >= agent.approachLength) {
agent.approachDistance = agent.approachLength;
agent.state = "queued";
agent.reachedGateAt = world.time;
const lane = world.lanes[agent.lane];
const start = Math.max(world.time, lane.nextFree);
agent.crossStart = start;
agent.wait = start - world.time;
lane.nextFree = start + world.crossingDuration;
world.queue.push(agent);
}
} else if (agent.state === "queued") {
if (world.time + 1e-9 >= agent.crossStart) {
agent.state = "crossing";
world.queue = world.queue.filter(item => item !== agent);
}
} else if (agent.state === "crossing") {
if (world.time - agent.crossStart >= world.crossingDuration) {
agent.state = "exit";
agent.exitDistance = 0;
}
} else if (agent.state === "exit") {
agent.exitDistance += agent.speed * dt;
if (agent.exitDistance >= agent.exitLength) {
agent.exitDistance = agent.exitLength;
agent.state = "done";
agent.doneAt = world.time;
}
}
}
}
function getStats(world) {
const arrived = world.agents.filter(a => a.arrived);
const completed = world.agents.filter(a => a.state === "done");
const queued = world.agents.filter(a => a.state === "queued");
const moving = world.agents.filter(a => a.state === "approach" || a.state === "crossing" || a.state === "exit");
const waitSamples = [];
for (const agent of world.agents) {
if (!agent.arrived || agent.reachedGateAt === null) continue;
const observed = agent.state === "queued"
? world.time - agent.reachedGateAt
: agent.wait;
if (observed !== null) waitSamples.push(Math.max(0, observed));
}
const averageWait = waitSamples.length
? waitSamples.reduce((sum, value) => sum + value, 0) / waitSamples.length
: 0;
const maxWait = waitSamples.length ? Math.max(...waitSamples) : 0;
const finishTime = completed.length === world.agents.length
? Math.max(...completed.map(a => a.doneAt))
: null;
return {
arrived: arrived.length,
completed: completed.length,
queued: queued.length,
moving: moving.length,
averageWait,
maxWait,
finishTime
};
}
// ---------- Renderização Three.js ----------
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setClearColor(0x101a2b);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x101a2b, 48, 92);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 120);
const cameraTarget = new THREE.Vector3(0, 0.45, 0);
let cameraYaw = 0;
let cameraPitch = 0.62;
let cameraZoom = 1;
const hemisphere = new THREE.HemisphereLight(0xcfe6ff, 0x26324a, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d6, 2.35);
sun.position.set(-8, 20, 13);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -30;
sun.shadow.camera.right = 30;
sun.shadow.camera.top = 25;
sun.shadow.camera.bottom = -25;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x73baff, 0.65);
rim.position.set(15, 8, -15);
scene.add(rim);
const bodyGeometry = new THREE.CylinderGeometry(0.15, 0.205, 0.49, 6);
const headGeometry = new THREE.DodecahedronGeometry(0.16, 0);
const footGeometry = new THREE.BoxGeometry(0.12, 0.10, 0.19);
const noseGeometry = new THREE.BoxGeometry(0.075, 0.07, 0.075);
const markerGeometry = new THREE.CylinderGeometry(0.095, 0.095, 0.035, 8);
const bodyMaterials = AGENT_COLORS.map(color => new THREE.MeshStandardMaterial({
color, roughness: 0.78, flatShading: true
}));
const headMaterials = [0xf4c7a0, 0xc98c63, 0x8d5b3e].map(color => new THREE.MeshStandardMaterial({
color, roughness: 0.9, flatShading: true
}));
const footMaterial = new THREE.MeshStandardMaterial({ color: 0x182235, roughness: 1 });
const noseMaterial = new THREE.MeshStandardMaterial({ color: 0xf8fafc, roughness: .8 });
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? .86,
metalness: options.metalness ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1,
flatShading: options.flatShading ?? true
});
}
function addBox(parent, width, height, depth, x, y, z, material, castShadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeTextSprite(lines, accent = "#67b7ff", width = 512, height = 128) {
const c = document.createElement("canvas");
c.width = width;
c.height = height;
const ctx = c.getContext("2d");
ctx.fillStyle = "rgba(10, 19, 33, .88)";
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = accent;
ctx.fillRect(0, 0, 10, height);
ctx.strokeStyle = "rgba(171, 195, 225, .35)";
ctx.strokeRect(1, 1, width - 2, height - 2);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#f3f7ff";
const lineHeight = height / (lines.length + 1);
lines.forEach((line, index) => {
ctx.font = index === 0 ? "800 31px system-ui" : "600 22px system-ui";
ctx.fillText(line, width / 2, lineHeight * (index + 1));
});
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
function makeGoalBoard() {
const c = document.createElement("canvas");
c.width = 256;
c.height = 128;
const ctx = c.getContext("2d");
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.8, .9, 1);
sprite.renderOrder = 20;
function draw(count) {
ctx.fillStyle = "rgba(10, 19, 33, .9)";
ctx.fillRect(0, 0, 256, 128);
ctx.fillStyle = "#55e3ad";
ctx.fillRect(0, 0, 256, 10);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#8fa3bd";
ctx.font = "700 19px system-ui";
ctx.fillText("SAÍDA", 128, 35);
ctx.fillStyle = "#f4f8ff";
ctx.font = "900 47px system-ui";
ctx.fillText(String(count), 128, 78);
ctx.fillStyle = "#8fa3bd";
ctx.font = "600 15px system-ui";
ctx.fillText("concluídos", 128, 110);
texture.needsUpdate = true;
}
draw(0);
return { sprite, draw };
}
function addGrid(parent) {
const positions = [];
for (let x = -8; x <= 8; x += 1) {
positions.push(x, .012, -4.9, x, .012, 4.9);
}
for (let z = -4; z <= 4; z += 1) {
positions.push(-8.4, .012, z, 8.4, .012, z);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({
color: 0x71829b,
transparent: true,
opacity: .13
});
parent.add(new THREE.LineSegments(geometry, material));
}
function addPathDashes(parent, points, color) {
const length = pathLength(points);
const material = standardMaterial(color, { transparent: true, opacity: .74 });
for (let d = .25; d < length; d += .72) {
const p = pointOnPath(points, d);
const dash = addBox(parent, .34, .025, .075, p.x, .035, p.z, material, false);
dash.rotation.y = -Math.atan2(p.dz, p.dx);
}
}
function addMeasurement(parent, width, centerZ, accent) {
const positions = [
.55, .055, centerZ - width / 2,
.55, .055, centerZ + width / 2,
.40, .055, centerZ - width / 2,
.70, .055, centerZ - width / 2,
.40, .055, centerZ + width / 2,
.70, .055, centerZ + width / 2
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({ color: accent });
parent.add(new THREE.LineSegments(geometry, material));
}
function buildWorldVisual(world, centerX) {
const group = new THREE.Group();
group.position.x = centerX;
scene.add(group);
const floorMaterial = standardMaterial(COLORS.floor, { roughness: .96 });
const floor = addBox(group, 17, .34, 10, 0, -.19, 0, floorMaterial, false);
floor.receiveShadow = true;
const borderMaterial = standardMaterial(0x53637b);
addBox(group, 17.15, .13, .10, 0, -.02, -5.02, borderMaterial, false);
addBox(group, 17.15, .13, .10, 0, -.02, 5.02, borderMaterial, false);
addBox(group, .10, .13, 10.15, -8.52, -.02, 0, borderMaterial, false);
addBox(group, .10, .13, 10.15, 8.52, -.02, 0, borderMaterial, false);
addGrid(group);
const startMaterial = standardMaterial(world.isA ? 0x245b85 : 0x286454, {
transparent: true, opacity: .56, roughness: 1
});
const goalMaterial = standardMaterial(0x23634c, {
transparent: true, opacity: .62, roughness: 1
});
addBox(group, 2.3, .035, 4.2, -6.7, .005, 0, startMaterial, false);
addBox(group, 2.4, .035, 4.2, 6.9, .005, 0, goalMaterial, false);
const wallMaterial = standardMaterial(COLORS.wall);
const wallTopMaterial = standardMaterial(COLORS.wallTop);
const opening = world.isA ? 1.6 : .75;
const wallMin = -3.25;
const wallMax = 3.25;
const lowerDepth = -opening - wallMin;
const upperDepth = wallMax - opening;
const lowerZ = wallMin + lowerDepth / 2;
const upperZ = opening + upperDepth / 2;
addBox(group, .48, 1.16, lowerDepth, 0, .58, lowerZ, wallMaterial);
addBox(group, .54, .09, lowerDepth, 0, 1.20, lowerZ, wallTopMaterial);
addBox(group, .48, 1.16, upperDepth, 0, .58, upperZ, wallMaterial);
addBox(group, .54, .09, upperDepth, 0, 1.20, upperZ, wallTopMaterial);
const accent = world.isA ? COLORS.blue : COLORS.green;
const accentMaterial = standardMaterial(accent);
addBox(group, .24, 1.48, .16, 0, .74, -opening, accentMaterial);
addBox(group, .24, 1.48, .16, 0, .74, opening, accentMaterial);
addBox(group, .26, .15, opening * 2 + .25, 0, 1.49, 0, accentMaterial);
const pathPoints = world.isA
? [{ x: -7.8, z: 0 }, { x: 7.8, z: 0 }]
: [
{ x: -7.8, z: 0 },
{ x: -4, z: 0 },
{ x: -2.8, z: 4.05 },
{ x: 3, z: 4.05 },
{ x: 5, z: 0 },
{ x: 7.8, z: 0 }
];
addPathDashes(group, pathPoints, accent);
if (!world.isA) {
const railMaterial = standardMaterial(0x3f826d);
addBox(group, 5.8, .62, .12, .1, .31, 3.25, railMaterial);
addBox(group, 5.8, .62, .12, .1, .31, 4.85, railMaterial);
const stripMaterial = standardMaterial(0x246650, { transparent: true, opacity: .55 });
addBox(group, 5.8, .028, 1.45, .1, .022, 4.05, stripMaterial, false);
}
// Arco da saída.
const goalArchMaterial = standardMaterial(0x58d7a7);
addBox(group, .20, 1.45, .16, 7.75, .72, -1.22, goalArchMaterial);
addBox(group, .20, 1.45, .16, 7.75, .72, 1.22, goalArchMaterial);
addBox(group, .22, .15, 2.58, 7.75, 1.43, 0, goalArchMaterial);
const title = world.isA
? ["A · PORTA AMPLIADA", "abertura de 3,2 m"]
: ["B · ROTA ALTERNATIVA", "desvio superior de 1,6 m"];
const titleSprite = makeTextSprite(title, world.isA ? "#67b7ff" : "#55e3ad");
titleSprite.position.set(0, 3.25, -4.55);
titleSprite.scale.set(5.8, 1.45, 1);
group.add(titleSprite);
const doorLabel = makeTextSprite(
world.isA ? ["3,2 m", "2 faixas"] : ["1,5 m", "porta padrão"],
world.isA ? "#67b7ff" : "#9eacc0",
256, 128
);
doorLabel.position.set(1.15, 2.00, world.isA ? 0 : -.05);
doorLabel.scale.set(1.75, .88, 1);
group.add(doorLabel);
if (!world.isA) {
const routeLabel = makeTextSprite(["ROTA ALTERNATIVA", "1 faixa · 21,0 m"], "#55e3ad", 384, 128);
routeLabel.position.set(.2, 1.72, 4.48);
routeLabel.scale.set(3.45, 1.05, 1);
group.add(routeLabel);
}
addMeasurement(group, opening * 2, 0, accent);
const goalBoard = makeGoalBoard();
goalBoard.sprite.position.set(7.55, 2.35, -1.55);
group.add(goalBoard.sprite);
const agentVisuals = world.agents.map(agent => {
const visual = new THREE.Group();
const body = new THREE.Mesh(bodyGeometry, bodyMaterials[agent.id % bodyMaterials.length]);
body.position.y = .53;
body.castShadow = true;
visual.add(body);
const head = new THREE.Mesh(headGeometry, headMaterials[agent.id % headMaterials.length]);
head.position.y = .94;
head.castShadow = true;
visual.add(head);
const leftFoot = new THREE.Mesh(footGeometry, footMaterial);
leftFoot.position.set(-.09, .10, .02);
const rightFoot = new THREE.Mesh(footGeometry, footMaterial);
rightFoot.position.set(.09, .10, .02);
visual.add(leftFoot, rightFoot);
const nose = new THREE.Mesh(noseGeometry, noseMaterial);
nose.position.set(0, .91, .17);
visual.add(nose);
const marker = new THREE.Mesh(markerGeometry, bodyMaterials[agent.id % bodyMaterials.length]);
marker.position.set(6.25 + (agent.id % 8) * .27, .07, -.85 + Math.floor(agent.id / 8) * .42);
marker.castShadow = true;
marker.visible = false;
group.add(marker);
group.add(visual);
return { visual, marker };
});
return { group, goalBoard, agentVisuals };
}
let worldA = null;
let worldB = null;
let visualA = null;
let visualB = null;
let playing = false;
let speed = 4;
let accumulator = 0;
function advanceBoth(dt) {
advanceWorld(worldA, dt);
advanceWorld(worldB, dt);
}
function advancePairTo(target) {
while (worldA.time < target - 1e-8) {
const dt = Math.min(.05, target - worldA.time);
advanceBoth(dt);
}
}
function buildPair(target = 0) {
if (visualA) scene.remove(visualA.group);
if (visualB) scene.remove(visualB.group);
worldA = createSimulation("A");
worldB = createSimulation("B");
advancePairTo(target);
visualA = buildWorldVisual(worldA, -10.35);
visualB = buildWorldVisual(worldB, 10.35);
accumulator = 0;
updateUI();
}
function updateAgentVisuals(world, visual) {
for (const agent of world.agents) {
const item = visual.agentVisuals[agent.id];
if (!agent.arrived) {
item.visual.visible = false;
item.marker.visible = false;
continue;
}
if (agent.state === "done") {
item.visual.visible = false;
item.marker.visible = true;
continue;
}
item.visual.visible = true;
item.marker.visible = false;
let x = 0;
let z = 0;
let dx = 1;
let dz = 0;
if (agent.state === "approach") {
const p = pointOnPath(agent.approachPoints, agent.approachDistance);
x = p.x; z = p.z; dx = p.dx; dz = p.dz;
} else if (agent.state === "queued") {
const sameLaneQueue = world.queue.filter(itemAgent => itemAgent.lane === agent.lane);
const queueIndex = sameLaneQueue.indexOf(agent);
if (world.isA) {
x = world.gateStart.x - .46 * (queueIndex + 1);
z = agent.laneZ;
dx = 1; dz = 0;
} else {
const behind = { x: -1.2, z: -4.05 };
const length = Math.hypot(behind.x, behind.z);
x = world.gateStart.x + (behind.x / length) * .48 * (queueIndex + 1);
z = world.gateStart.z + (behind.z / length) * .48 * (queueIndex + 1);
dx = -behind.x / length;
dz = -behind.z / length;
}
} else if (agent.state === "crossing") {
const u = THREE.MathUtils.clamp(
(world.time - agent.crossStart) / world.crossingDuration,
0,
1
);
const startZ = world.isA ? agent.laneZ : world.gateStart.z;
const endZ = world.isA ? agent.laneZ : world.gateEnd.z;
x = THREE.MathUtils.lerp(world.gateStart.x, world.gateEnd.x, u);
z = THREE.MathUtils.lerp(startZ, endZ, u);
dx = world.gateEnd.x - world.gateStart.x;
dz = endZ - startZ;
const length = Math.hypot(dx, dz) || 1;
dx /= length; dz /= length;
} else if (agent.state === "exit") {
const p = pointOnPath(agent.exitPoints, agent.exitDistance);
x = p.x; z = p.z; dx = p.dx; dz = p.dz;
}
item.visual.position.set(x, .02, z);
item.visual.rotation.y = Math.atan2(dx, dz);
}
}
function updateUI() {
const statsA = getStats(worldA);
const statsB = getStats(worldB);
$("clock").textContent = `${formatClock(worldA.time)} / ${formatClock(SIM_END)}`;
$("playState").textContent = playing ? " · em reprodução" : " · pausado";
$("playBtn").textContent = playing ? "⏸ Pausar" : "▶ Continuar";
function fill(prefix, stats) {
$(`${prefix}Arrived`).textContent = `${stats.arrived}/32`;
$(`${prefix}ArrivedSub`).textContent = stats.arrived === 32
? "demanda completa"
: `${32 - stats.arrived} ainda por chegar`;
$(`${prefix}Done`).textContent = String(stats.completed);
$(`${prefix}DoneSub`).textContent = stats.queued
? `${stats.queued} na fila · ${stats.moving} em rota`
: `${stats.moving} em rota`;
$(`${prefix}Wait`).textContent = `${stats.averageWait.toFixed(1)} s`;
$(`${prefix}WaitSub`).textContent = `máx. ${stats.maxWait.toFixed(1)} s`;
$(`${prefix}Finish`).textContent = stats.finishTime === null ? "—" : formatClock(stats.finishTime);
$(`${prefix}FinishSub`).textContent = stats.finishTime === null
? "ainda não concluído"
: "tempo simulado real";
}
fill("a", statsA);
fill("b", statsB);
visualA.goalBoard.draw(statsA.completed);
visualB.goalBoard.draw(statsB.completed);
}
// ---------- Diagnóstico com novos estados simulados ----------
function runDiagnostics() {
const a = createSimulation("A");
const b = createSimulation("B");
const target = REVIEW_TIME;
while (a.time < target - 1e-8) {
const dt = Math.min(.05, target - a.time);
advanceWorld(a, dt);
advanceWorld(b, dt);
}
const statsA = getStats(a);
const statsB = getStats(b);
const sameArrivals = a.agents.every((agent, index) => agent.arrival === b.agents[index].arrival);
const validTimes = [...a.agents, ...b.agents].every(agent =>
agent.doneAt === null || agent.doneAt >= agent.arrival
);
const directOpeningClear = Math.abs(0) < 1.6;
const alternateClear = 4.05 > 3.25;
const checks = [
[sameArrivals, "As duas séries contêm exatamente as mesmas 32 chegadas."],
[statsA.arrived === 32 && statsB.arrived === 32, "Em 04:49,9, os dois cenários receberam 32/32 agentes."],
[statsA.completed > 0 && statsB.completed > 0, `Há conclusões nos dois: A = ${statsA.completed}, B = ${statsB.completed}.`],
[statsA.completed === 32 && statsB.completed === 32, "O bloqueio anterior de zero conclusões não é reproduzido."],
[validTimes, "Todo tempo de conclusão é posterior à chegada correspondente."],
[directOpeningClear, "A rota A cruza o plano da parede dentro da abertura de 3,2 m."],
[alternateClear, "A rota B passa 0,80 m acima do topo da parede-base."]
];
$("diagSummary").textContent =
`No estado 04:49,9, A concluiu ${statsA.completed}/32 e B concluiu ${statsB.completed}/32. ` +
`Espera média: A = ${statsA.averageWait.toFixed(1)} s; B = ${statsB.averageWait.toFixed(1)} s. ` +
`O contador vem da simulação, e não de um valor fixo.`;
$("diagChecks").innerHTML = checks.map(([ok, text]) =>
`<div><span class="${ok ? "pass" : "fail"}">${ok ? "✓" : "✕"}</span> ${text}</div>`
).join("");
}
// ---------- Câmera própria, sem addons ----------
function updateCamera() {
const halfFov = THREE.MathUtils.degToRad(camera.fov * .5);
const distanceForWidth = 21 / (Math.tan(halfFov) * Math.max(.5, camera.aspect));
const distance = Math.max(31, distanceForWidth) * cameraZoom;
const horizontal = Math.cos(cameraPitch) * distance;
camera.position.set(
Math.sin(cameraYaw) * horizontal,
Math.sin(cameraPitch) * distance,
Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = 0;
cameraPitch = .62;
cameraZoom = 1;
}
let dragging = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener("pointerdown", event => {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
cameraYaw -= (event.clientX - lastX) * .006;
cameraPitch = THREE.MathUtils.clamp(cameraPitch + (event.clientY - lastY) * .004, .30, 1.18);
lastX = event.clientX;
lastY = event.clientY;
});
const endDrag = () => { dragging = false; };
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(cameraZoom * Math.exp(event.deltaY * .001), .68, 1.55);
}, { passive: false });
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
if ("ResizeObserver" in window) new ResizeObserver(resize).observe(stage);
$("playBtn").addEventListener("click", () => {
if (worldA.time >= SIM_END - .001) buildPair(0);
playing = !playing;
accumulator = 0;
updateUI();
});
$("resetBtn").addEventListener("click", () => {
buildPair(0);
playing = true;
updateUI();
});
$("testBtn").addEventListener("click", () => {
buildPair(REVIEW_TIME);
playing = false;
updateUI();
});
$("speedBtn").addEventListener("click", () => {
speed = speed === 1 ? 4 : speed === 4 ? 8 : 1;
$("speedBtn").textContent = `Velocidade ${speed}×`;
});
$("cameraBtn").addEventListener("click", resetCamera);
buildPair(DEFAULT_TIME);
resize();
runDiagnostics();
updateCamera();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const realDt = Math.min(.10, clock.getDelta());
if (playing) {
accumulator += realDt * speed;
while (accumulator >= .05 && worldA.time < SIM_END) {
const dt = Math.min(.05, SIM_END - worldA.time);
advanceBoth(dt);
accumulator -= dt;
}
if (worldA.time >= SIM_END - .001) {
playing = false;
accumulator = 0;
}
}
updateAgentVisuals(worldA, visualA);
updateAgentVisuals(worldB, visualB);
updateUI();
updateCamera();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```