Prompt specification
Build or customize the Three.js 3D scene "Morning delivery routing through a market fragment" 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: Morning delivery routing through a market fragment
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/morning-delivery-routing-through-a-market-fragment-x2644
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts Belém's Ver-o-Peso waterfront market. Let users schedule fictional deliveries through a small market layout. Show congestion at narrow passages and preserve access to stalls without assigning real market operating rules. Voxel style.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Build initial delivery paths only from existing, connected graph edges. Show stall access, congestion, and scheduling in the rendered market.
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 (morning-delivery-routing-through-a-market-fragment-x2644):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ver-o-Peso — Entregas Fictícias em Voxel</title>
<style>
:root {
--ink: #173d40;
--ink-2: #24585a;
--paper: #f4edda;
--paper-2: #fffaf0;
--muted: #66736d;
--cyan: #27d6c5;
--green: #43d58c;
--amber: #f0a34b;
--red: #e7634f;
--line: rgba(23, 61, 64, 0.2);
--shadow: 4px 4px 0 rgba(23, 61, 64, 0.18);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d8d6;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
}
button, select { font: inherit; }
#app {
display: grid;
grid-template-columns: 336px minmax(0, 1fr);
width: 100%;
height: 100%;
}
#panel {
position: relative;
z-index: 5;
padding: 22px 20px 18px;
overflow-y: auto;
background:
linear-gradient(rgba(23, 61, 64, 0.035) 1px, transparent 1px),
linear-gradient(90deg, rgba(23, 61, 64, 0.035) 1px, transparent 1px),
var(--paper);
background-size: 18px 18px;
border-right: 4px solid var(--ink);
box-shadow: 7px 0 0 rgba(23, 61, 64, 0.12);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--ink-2);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 10px;
height: 10px;
background: var(--cyan);
border: 2px solid var(--ink);
box-shadow: 3px 3px 0 var(--ink);
}
h1 {
margin: 0;
font-size: 30px;
line-height: 0.98;
letter-spacing: -0.06em;
text-transform: uppercase;
}
h1 span {
display: block;
margin-top: 8px;
color: var(--ink-2);
font-size: 16px;
letter-spacing: -0.03em;
}
.intro {
margin: 14px 0 15px;
color: #53645f;
font-size: 12px;
line-height: 1.55;
}
.synthetic-badge {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 17px;
padding: 7px 9px;
color: var(--paper-2);
background: var(--ink);
border: 2px solid var(--ink);
box-shadow: 3px 3px 0 var(--cyan);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
}
.synthetic-badge i {
width: 7px;
height: 7px;
background: var(--cyan);
}
.card {
margin-top: 14px;
padding: 14px;
background: rgba(255, 250, 240, 0.86);
border: 2px solid var(--ink);
box-shadow: var(--shadow);
}
.card-title {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
margin-bottom: 12px;
font-size: 12px;
font-weight: 900;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.card-title span {
color: var(--muted);
font-size: 9px;
letter-spacing: 0;
}
label {
display: block;
margin: 10px 0 5px;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.06em;
text-transform: uppercase;
}
select {
width: 100%;
height: 38px;
padding: 0 31px 0 10px;
color: var(--ink);
background-color: var(--paper-2);
background-image:
linear-gradient(45deg, transparent 50%, var(--ink) 50%),
linear-gradient(135deg, var(--ink) 50%, transparent 50%);
background-position:
calc(100% - 15px) 16px,
calc(100% - 10px) 16px;
background-size: 5px 5px, 5px 5px;
background-repeat: no-repeat;
border: 2px solid var(--ink);
border-radius: 0;
outline: none;
appearance: none;
font-size: 11px;
font-weight: 700;
}
select:focus-visible,
button:focus-visible {
outline: 3px solid var(--cyan);
outline-offset: 2px;
}
.primary-button {
width: 100%;
min-height: 46px;
margin-top: 15px;
padding: 10px 12px;
color: var(--ink);
background: var(--cyan);
border: 3px solid var(--ink);
box-shadow: 4px 4px 0 var(--ink);
cursor: pointer;
font-size: 12px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
transition: transform 100ms ease, box-shadow 100ms ease;
}
.primary-button:hover {
transform: translate(-1px, -1px);
box-shadow: 6px 6px 0 var(--ink);
}
.primary-button:active {
transform: translate(3px, 3px);
box-shadow: 1px 1px 0 var(--ink);
}
.route-card {
color: var(--paper-2);
background: var(--ink);
border-color: var(--ink);
}
.route-card .card-title {
color: var(--paper-2);
}
.route-card .card-title span {
color: var(--cyan);
}
#routeTitle {
margin: 4px 0 7px;
color: #fff7df;
font-size: 16px;
line-height: 1.25;
}
#routeMeta {
min-height: 32px;
margin: 0;
color: #bcd4cd;
font-size: 10px;
line-height: 1.55;
}
#routeState {
display: inline-block;
margin-top: 12px;
padding: 7px 8px;
color: var(--ink);
background: var(--cyan);
border: 2px solid #071f21;
box-shadow: 3px 3px 0 #071f21;
font-size: 9px;
font-weight: 900;
line-height: 1.35;
letter-spacing: 0.04em;
text-transform: uppercase;
}
#routeState[data-state="alert"] {
color: #3b1e13;
background: var(--amber);
}
#routeState[data-state="error"] {
color: #fff;
background: var(--red);
}
.network-status {
margin-top: 11px;
padding: 8px 9px;
color: #d9eee4;
background: #24585a;
border-left: 4px solid var(--green);
font-size: 9px;
font-weight: 800;
line-height: 1.45;
}
.legend {
display: grid;
gap: 8px;
font-size: 10px;
color: #465b56;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
}
.swatch {
width: 18px;
height: 10px;
border: 2px solid var(--ink);
flex: 0 0 auto;
}
.swatch.route { background: var(--cyan); }
.swatch.access { background: rgba(67, 213, 140, 0.3); border-color: var(--green); }
.swatch.crowd { background: var(--amber); }
.disclaimer {
margin: 15px 2px 0;
padding-top: 12px;
border-top: 1px dashed rgba(23, 61, 64, 0.35);
color: #66736d;
font-size: 9px;
line-height: 1.55;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #b9d8d6;
}
#viewport,
#worldLabels {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
cursor: grab;
}
#viewport canvas:active { cursor: grabbing; }
#worldLabels {
z-index: 3;
pointer-events: none;
overflow: hidden;
}
#worldLabels.off { display: none; }
.world-label {
position: absolute;
padding: 5px 7px;
color: #fff9e7;
background: rgba(23, 61, 64, 0.9);
border: 2px solid rgba(255, 255, 255, 0.18);
box-shadow: 3px 3px 0 rgba(23, 61, 64, 0.25);
font-size: 9px;
font-weight: 900;
line-height: 1;
letter-spacing: 0.04em;
white-space: nowrap;
transform: translate(-50%, -100%);
}
.world-label.stall {
padding: 4px 6px;
color: var(--ink);
background: rgba(255, 250, 240, 0.92);
border-color: var(--ink);
font-size: 8px;
}
.world-label.hot {
color: #32190f;
background: var(--amber);
border-color: #8f4925;
box-shadow: 4px 4px 0 rgba(79, 42, 25, 0.35);
}
.world-label.wide {
color: var(--ink);
background: rgba(255, 250, 240, 0.92);
border-color: var(--ink);
}
.scene-heading {
position: absolute;
z-index: 4;
top: 18px;
left: 18px;
max-width: 300px;
padding: 11px 13px;
color: var(--ink);
background: rgba(255, 250, 240, 0.9);
border: 2px solid var(--ink);
box-shadow: 4px 4px 0 rgba(23, 61, 64, 0.2);
pointer-events: none;
}
.scene-heading small {
display: block;
margin-bottom: 4px;
color: #61726c;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.scene-heading strong {
display: block;
font-size: 15px;
letter-spacing: -0.03em;
text-transform: uppercase;
}
.scene-heading em {
display: block;
margin-top: 5px;
color: #53645f;
font-size: 8px;
font-style: normal;
line-height: 1.4;
}
.toolbar {
position: absolute;
z-index: 6;
top: 18px;
right: 18px;
display: flex;
gap: 7px;
}
.tool-button {
min-height: 34px;
padding: 7px 9px;
color: var(--ink);
background: rgba(255, 250, 240, 0.92);
border: 2px solid var(--ink);
box-shadow: 3px 3px 0 rgba(23, 61, 64, 0.22);
cursor: pointer;
font-size: 9px;
font-weight: 900;
text-transform: uppercase;
}
.tool-button:hover { background: var(--cyan); }
.scene-legend {
position: absolute;
z-index: 4;
left: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
gap: 8px;
max-width: 360px;
pointer-events: none;
}
.scene-chip {
display: flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
color: var(--ink);
background: rgba(255, 250, 240, 0.9);
border: 2px solid var(--ink);
box-shadow: 3px 3px 0 rgba(23, 61, 64, 0.18);
font-size: 8px;
font-weight: 900;
text-transform: uppercase;
}
.scene-chip i {
width: 9px;
height: 9px;
border: 1px solid var(--ink);
}
.scene-chip.route i { background: var(--cyan); }
.scene-chip.access i { background: var(--green); }
.scene-chip.congestion i { background: var(--amber); }
.metrics {
position: absolute;
z-index: 4;
right: 18px;
bottom: 18px;
width: 290px;
color: var(--paper-2);
background: rgba(23, 61, 64, 0.94);
border: 2px solid #0b292b;
box-shadow: 5px 5px 0 rgba(23, 61, 64, 0.22);
pointer-events: none;
}
.metric {
display: grid;
grid-template-columns: 1fr auto;
gap: 3px 10px;
padding: 10px 11px;
border-bottom: 1px solid rgba(255, 255, 255, 0.13);
}
.metric:last-child { border-bottom: 0; }
.metric > span {
color: #b9d1cb;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric > strong {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
color: #fff8df;
font-size: 16px;
text-align: right;
}
.metric small {
color: #95b4ac;
font-size: 8px;
line-height: 1.4;
}
.meter {
grid-column: 1 / -1;
height: 5px;
margin-top: 4px;
overflow: hidden;
background: rgba(255, 255, 255, 0.12);
}
.meter i {
display: block;
width: 0;
height: 100%;
background: var(--amber);
transition: width 180ms ease, background 180ms ease;
}
#accessMetric { color: var(--green); }
#bottleneckMetric { color: var(--amber); }
.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;
}
@media (max-width: 850px) {
html, body { overflow: auto; }
#app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100%;
}
#stage {
order: 1;
height: 58vh;
min-height: 430px;
border-bottom: 4px solid var(--ink);
}
#panel {
order: 2;
overflow: visible;
border-right: 0;
box-shadow: none;
}
.scene-heading { max-width: 230px; }
.scene-heading strong { font-size: 12px; }
.toolbar { top: auto; bottom: 92px; right: 12px; }
.metrics { right: 12px; bottom: 12px; width: 250px; }
.scene-legend { left: 12px; bottom: 12px; max-width: 210px; }
.scene-chip { padding: 6px 7px; font-size: 7px; }
}
</style>
</head>
<body>
<div id="app">
<aside id="panel">
<div class="eyebrow">Belém do Pará · Laboratório urbano</div>
<h1>Ver-o-Peso <span>Entregas em maquete voxel</span></h1>
<p class="intro">
Programe uma entrega entre bancas ilustrativas, acompanhe o percurso e observe
a concentração de fluxes na passagem estreita do cais.
</p>
<div class="synthetic-badge"><i></i> CENÁRIO SINTÉTICO · NÃO OPERACIONAL</div>
<form id="deliveryForm" class="card" autocomplete="off">
<div class="card-title">Nova entrega <span>agendamento fictício</span></div>
<label for="pickup">Banca de coleta</label>
<select id="pickup" name="pickup">
<option value="A">A · Frutas — ilustrativa</option>
<option value="B" selected>B · Peixes frescos — ilustrativa</option>
<option value="C">C · Flores — ilustrativa</option>
<option value="D">D · Temperos — ilustrativa</option>
<option value="E">E · Açúcar — ilustrativa</option>
<option value="F">F · Peixes secos — ilustrativa</option>
</select>
<label for="dropoff">Banca de entrega</label>
<select id="dropoff" name="dropoff">
<option value="A">A · Frutas — ilustrativa</option>
<option value="B">B · Peixes frescos — ilustrativa</option>
<option value="C">C · Flores — ilustrativa</option>
<option value="D">D · Temperos — ilustrativa</option>
<option value="E">E · Açúcar — ilustrativa</option>
<option value="F" selected>F · Peixes secos — ilustrativa</option>
</select>
<label for="slot">Janela da maquete</label>
<select id="slot" name="slot">
<option value="08:00">08:00 · janela inventada</option>
<option value="10:30">10:30 · janela inventada</option>
<option value="14:00">14:00 · janela inventada</option>
</select>
<label for="packageType">Objeto da entrega</label>
<select id="packageType" name="packageType">
<option>Caixa sintética</option>
<option>Saco sintético</option>
<option>Cesta sintética</option>
</select>
<button class="primary-button" type="button" id="scheduleDeliveryButton">Agendar entrega fictícia →</button>
</form>
<section class="card route-card" aria-live="polite">
<div class="card-title">Rota em destaque <span id="routeDistance">— m</span></div>
<h2 id="routeTitle">Preparando rota</h2>
<p id="routeMeta">A malha está sendo validada antes do povoamento inicial.</p>
<div id="routeState" data-state="normal">Inicializando</div>
<div id="networkStatus" class="network-status">REDE EM CONSTRUÇÃO</div>
</section>
<section class="card">
<div class="card-title">Chave visual <span>layout esquemático</span></div>
<div class="legend">
<div class="legend-row"><i class="swatch route"></i> Rota da entrega fictícia</div>
<div class="legend-row"><i class="swatch access"></i> Entrada frontal preservada</div>
<div class="legend-row"><i class="swatch crowd"></i> Gargula e concentração simulada</div>
</div>
</section>
<p class="disclaimer">
<strong>Aviso:</strong> bancas, horários, larguras úteis, filas, sentidos e regras de
acesso são parâmetros inventados para esta maquete. A cena não representa horários,
normas ou instruções de operação do Ver-o-Peso real.
</p>
</aside>
<main id="stage" aria-label="Maquete tridimensional do mercado Ver-o-Peso">
<div id="viewport"></div>
<div id="worldLabels"></div>
<div class="scene-heading">
<small>Maquete 01 · cais e circulation</small>
<strong>Ver-o-Peso em blocos</strong>
<em>06 bancas ilustrativas · malha e|accessos sintéticos</em>
</div>
<div class="toolbar" aria-label="Controles da câmera">
<button id="resetView" class="tool-button" type="button">↺ Vista</button>
<button id="topView" class="tool-button" type="button">▦ Topo</button>
<button id="toggleLabels" class="tool-button" type="button">Rótulos ON</button>
</div>
<div class="scene-legend">
<div class="scene-chip route"><i></i> rota</div>
<div class="scene-chip access"><i></i> acesso</div>
<div class="scene-chip congestion"><i></i> G2</div>
</div>
<section class="metrics" aria-label="Métricas calculadas da cena">
<div class="metric">
<span>Gargula G2</span>
<strong id="bottleneckMetric">—</strong>
<small id="bottleneckSub">Largura e ocupação calculadas</small>
<div class="meter"><i id="congestionBar"></i></div>
</div>
<div class="metric">
<span>Acessos fronts</span>
<strong id="accessMetric">—</strong>
<small id="accessSub">Baias sem obstrução permanente</small>
</div>
<div class="metric">
<span>Malha de caminhos</span>
<strong id="graphMetric">—</strong>
<small>Somente arestas realmente conectadas</small>
</div>
</section>
<div id="statusLive" class="sr-only" aria-live="polite"></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 viewport = $("viewport");
const labelsLayer = $("worldLabels");
const STALLS = [
{
id: "A", name: "Frutas", sign: "A / FRUTAS", x: -14, z: 8,
pickX: -12.6, pickZ: 11.9, color: 0x579b68, wall: 0x947c5b
},
{
id: "B", name: "Peixes frescos", sign: "B / PEIXES", x: -3, z: 8,
pickX: -1.6, pickZ: 11.9, color: 0x3e8fa7, wall: 0x6f8790
},
{
id: "C", name: "Flores", sign: "C / FLORES", x: 7, z: 8,
pickX: 5.4, pickZ: 11.9, color: 0xc96678, wall: 0x9b756d
},
{
id: "D", name: "Temperos", sign: "D / TEMPEROS", x: -14, z: -2,
pickX: -12.6, pickZ: 1.9, color: 0xd0803f, wall: 0x927051
},
{
id: "E", name: "Açúcar", sign: "E / AÇÚCAR", x: -3, z: -2,
pickX: -1.6, pickZ: 1.9, color: 0xb89a55, wall: 0x8e785c
},
{
id: "F", name: "Peixes secos", sign: "F / SECOS", x: 7, z: -2,
pickX: 5.4, pickZ: 1.9, color: 0x3e8b83, wall: 0x71847d
}
];
const STALL_FOOTPRINT = 8.2;
const HALF_FOOTPRINT = STALL_FOOTPRINT / 2;
const ACCESS_WIDTH = 1.55;
const ACCESS_DEPTH = 1.25;
const SYNTHETIC_CAPACITY = 3;
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.02;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute("aria-label", "Cena 3D interativa do mercado");
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d8d6);
scene.fog = new THREE.Fog(0xb9d8d6, 76, 145);
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 200);
const cameraRig = {
yaw: 0.22,
pitch: 0.62,
distance: 58,
target: new THREE.Vector3(0, 1.2, 1.2),
userAdjusted: false
};
const hemi = new THREE.HemisphereLight(0xeaf7eb, 0x69604f, 1.65);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffedc6, 2.5);
sun.position.set(-24, 42, 30);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -42;
sun.shadow.camera.right = 42;
sun.shadow.camera.top = 38;
sun.shadow.camera.bottom = -38;
sun.shadow.camera.near = 2;
sun.shadow.camera.far = 100;
sun.shadow.bias = -0.00035;
scene.add(sun);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
const worldLabels = [];
const accessZones = [];
const boats = [];
const waterData = [];
function getMaterial(color, options = {}) {
const roughness = options.roughness ?? 0.86;
const metalness = options.metalness ?? 0;
const opacity = options.opacity ?? 1;
const transparent = options.transparent ?? opacity < 1;
const key = `${color}|${roughness}|${metalness}|${opacity}|${transparent}|${options.emissive ?? 0}|${options.emissiveIntensity ?? 0}`;
if (!materialCache.has(key)) {
const material = new THREE.MeshStandardMaterial({
color,
roughness,
metalness,
transparent,
opacity,
depthWrite: transparent ? false : true,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
materialCache.set(key, material);
}
return materialCache.get(key);
}
function box(parent, width, height, depth, color, x = 0, y = 0, z = 0, options = {}) {
const material = options.material || getMaterial(color, options);
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow !== false;
mesh.receiveShadow = options.receiveShadow !== false;
parent.add(mesh);
return mesh;
}
function seededRandom(seed) {
let value = seed >>> 0;
return () => {
value = (value * 1664525 + 1013904223) >>> 0;
return value / 4294967296;
};
}
function makeSignSprite(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0,0,0,.28)";
ctx.fillRect(10, 12, 492, 104);
ctx.fillStyle = options.background || "#173d40";
ctx.fillRect(0, 0, 492, 104);
ctx.strokeStyle = options.border || "#fff4cf";
ctx.lineWidth = 8;
ctx.strokeRect(5, 5, 482, 94);
let fontSize = 39;
ctx.font = `800 ${fontSize}px ui-monospace, monospace`;
while (ctx.measureText(text).width > 448 && fontSize > 19) {
fontSize -= 2;
ctx.font = `800 ${fontSize}px ui-monospace, monospace`;
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = options.foreground || "#fff4cf";
ctx.fillText(text, 246, 53);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(4, renderer.capabilities.getMaxAnisotropy());
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: options.depthTest ?? false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
const width = options.width || 4.2;
sprite.scale.set(width, width * 0.25, 1);
sprite.renderOrder = 8;
return sprite;
}
function addWorldLabel(text, position, className = "") {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
labelsLayer.appendChild(element);
const label = { element, position: position.clone() };
worldLabels.push(label);
return label;
}
function addCrate(parent, x, z, color = 0x9b7044) {
const group = new THREE.Group();
group.position.set(x, 0, z);
parent.add(group);
box(group, 0.92, 0.48, 0.72, color, 0, 0.48, 0);
box(group, 0.98, 0.08, 0.77, 0x684a31, 0, 0.74, 0);
box(group, 0.08, 0.52, 0.76, 0x684a31, -0.27, 0.48, 0);
box(group, 0.08, 0.52, 0.76, 0x684a31, 0.27, 0.48, 0);
return group;
}
function buildStall(stall, index) {
const group = new THREE.Group();
group.position.set(stall.x, 0, stall.z);
scene.add(group);
stall.group = group;
const lightRoof = new THREE.Color(stall.color)
.lerp(new THREE.Color(0xfff0cf), 0.58)
.getHex();
box(group, STALL_FOOTPRINT, 0.24, 6.2, 0x786a53, 0, 0.18, 0);
box(group, 8.0, 2.55, 0.28, stall.wall, 0, 1.5, -2.93);
box(group, 0.22, 2.25, 5.55, stall.wall, -3.99, 1.34, -0.18);
box(group, 0.22, 2.25, 5.55, stall.wall, 3.99, 1.34, -0.18);
for (const x of [-3.78, 3.78]) {
for (const z of [-2.65, 2.65]) {
box(group, 0.22, 3.1, 0.22, 0x5e4935, x, 1.76, z);
}
}
// Faixa de cobertura em tiras deixa o interior e as bancas legíveis.
for (let i = 0; i < 10; i++) {
const color = i % 2 === 0 ? stall.color : lightRoof;
box(
group,
0.74,
0.22,
6.25,
color,
-4.1 + (i + 0.5) * 0.82,
3.35,
0,
{ roughness: 0.72 }
);
}
box(group, 8.25, 0.2, 0.24, 0x4e4134, 0, 3.18, 3.11);
// Contadores separados preservam uma entrada frontal real de 2 m.
box(group, 3.05, 0.92, 1.12, 0x9b744d, -2.57, 0.86, 2.28);
box(group, 3.05, 0.92, 1.12, 0x9b744d, 2.57, 0.86, 2.28);
box(group, 3.18, 0.14, 1.22, 0xd0a56d, -2.57, 1.38, 2.28);
box(group, 3.18, 0.14, 1.22, 0xd0a56d, 2.57, 1.38, 2.28);
addCrate(group, -2.65, 1.95, 0x9b7044);
addCrate(group, 2.65, 1.95, 0x9b7044);
const random = seededRandom(4100 + index * 97);
const produceColors = [stall.color, lightRoof, 0xd9a83f, 0xcb644c, 0x70a75b];
for (let i = 0; i < 16; i++) {
const side = i % 2 === 0 ? -1 : 1;
const size = 0.18 + random() * 0.2;
box(
group,
size,
size,
size,
produceColors[Math.floor(random() * produceColors.length)],
side * (2.1 + random() * 1.35),
1.55 + random() * 0.22,
1.85 + random() * 0.65,
{ roughness: 0.7 }
);
}
if (stall.id === "B" || stall.id === "F") {
for (let i = 0; i < 7; i++) {
box(
group,
0.42,
0.12,
0.17,
i % 2 ? 0xc9d9d7 : 0x78949a,
-3.25 + i * 0.36,
1.56,
2.62,
{ roughness: 0.48, metalness: 0.18 }
);
}
}
const sign = makeSignSprite(stall.sign, {
width: 3.25,
background: "#173d40",
foreground: "#fff2ce"
});
sign.position.set(0, 4.03, 0.35);
group.add(sign);
const lamp = new THREE.PointLight(0xffd38c, 0.75, 7, 2);
lamp.position.set(0, 2.8, 1.2);
group.add(lamp);
box(group, 0.34, 0.16, 0.34, 0xffe5a1, 0, 2.83, 1.2, {
emissive: 0xffa938,
emissiveIntensity: 0.9
});
const zone = {
stall: stall.id,
x: stall.x,
z: stall.z + 3.55,
width: ACCESS_WIDTH,
depth: ACCESS_DEPTH,
clear: 2.0 >= ACCESS_WIDTH
};
accessZones.push(zone);
stall.accessZone = zone;
const fillMaterial = new THREE.MeshBasicMaterial({
color: 0x43d58c,
transparent: true,
opacity: 0.22,
depthWrite: false
});
box(scene, ACCESS_WIDTH, 0.035, ACCESS_DEPTH, 0x43d58c, zone.x, 0.265, zone.z, {
material: fillMaterial,
castShadow: false
});
box(scene, ACCESS_WIDTH, 0.055, 0.08, 0x43d58c, zone.x, 0.29, zone.z - ACCESS_DEPTH / 2);
box(scene, ACCESS_WIDTH, 0.055, 0.08, 0x43d58c, zone.x, 0.29, zone.z + ACCESS_DEPTH / 2);
box(scene, 0.08, 0.055, ACCESS_DEPTH, 0x43d58c, zone.x - ACCESS_WIDTH / 2, 0.29, zone.z);
box(scene, 0.08, 0.055, ACCESS_DEPTH, 0x43d58c, zone.x + ACCESS_WIDTH / 2, 0.29, zone.z);
addWorldLabel(
`${stall.id} · ${stall.name.toUpperCase()}`,
new THREE.Vector3(stall.x, 4.85, stall.z),
"stall"
);
}
function buildWarehouse(x, z, width, height, color, label) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
box(group, width, height, 6.0, color, 0, height / 2, 0);
box(group, width + 0.5, 0.35, 6.35, 0x455c5b, 0, height + 0.18, 0);
box(group, width - 1.0, 1.8, 0.18, 0x385154, 0, 0.9, 3.05);
for (let i = 0; i < 4; i++) {
const wx = -width / 2 + 1.3 + i * (width - 2.6) / 3;
for (let j = 0; j < 2; j++) {
box(group, 1.05, 0.82, 0.12, 0xf1d99a, wx, 2.3 + j * 1.35, 3.08, {
emissive: 0x8f6330,
emissiveIntensity: 0.22
});
}
}
for (let i = 0; i < 5; i++) {
box(group, 0.22, height + 0.25, 0.22, 0x665e50, -width / 2 + i * width / 4, height / 2, 3.12);
}
const sign = makeSignSprite(label, {
width: 4.2,
background: "#365b59",
foreground: "#e9dfbd"
});
sign.position.set(0, height + 1.0, 3.2);
group.add(sign);
}
function buildPalm(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
scene.add(group);
for (let i = 0; i < 6; i++) {
box(
group,
0.42,
0.72,
0.42,
i % 2 ? 0x876541 : 0x9b744b,
i * 0.045,
0.45 + i * 0.62,
0,
{ roughness: 1 }
);
}
const crown = new THREE.Group();
crown.position.set(0.25, 4.1, 0);
group.add(crown);
box(crown, 0.65, 0.6, 0.65, 0x806139, 0, 0, 0);
for (let i = 0; i < 7; i++) {
const leaf = box(crown, 3.0, 0.18, 0.62, i % 2 ? 0x3f7953 : 0x568d5b, 1.45, 0, 0);
leaf.rotation.y = i * Math.PI * 2 / 7;
leaf.rotation.z = i % 2 ? 0.12 : -0.12;
}
}
function buildCrane(x, z) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
const yellow = 0xd9a23c;
box(group, 5.2, 0.45, 5.2, 0x5a5d50, 0, 0.22, 0);
for (const px of [-0.75, 0.75]) {
for (const pz of [-0.75, 0.75]) {
box(group, 0.34, 8.4, 0.34, yellow, px, 4.2, pz);
}
}
for (let y = 1; y < 8; y += 1.55) {
box(group, 1.75, 0.22, 0.22, yellow, 0, y, -0.75);
box(group, 1.75, 0.22, 0.22, yellow, 0, y, 0.75);
}
box(group, 0.65, 0.65, 17.5, yellow, 0, 8.25, 6.0);
box(group, 0.18, 4.6, 0.18, 0x405154, 0, 5.95, 12.7);
box(group, 1.5, 0.5, 1.3, 0x42646a, 0.65, 7.45, -0.9);
box(group, 1.25, 1.15, 1.05, 0xd9a23c, 0, 0.78, -0.1);
}
function buildBoat(x, z, color, rotation = 0) {
const group = new THREE.Group();
group.position.set(x, -0.04, z);
group.rotation.y = rotation;
scene.add(group);
box(group, 4.5, 0.8, 8.2, color, 0, 0.25, 0);
box(group, 3.5, 0.8, 7.5, 0x804d3e, 0, 0.8, 0);
box(group, 2.8, 1.7, 2.7, 0xd8d6bb, 0, 1.95, -0.6);
box(group, 2.2, 0.75, 0.12, 0x416d78, 0, 2.15, 0.82, {
emissive: 0x193f4b,
emissiveIntensity: 0.25
});
box(group, 0.22, 4.1, 0.22, 0xd4c49a, 0, 3.15, -2.0);
box(group, 2.4, 0.15, 0.15, 0xd4c49a, 0, 4.5, -2.0);
for (let i = 0; i < 4; i++) {
box(group, 0.75, 0.6, 0.75, i % 2 ? 0xd8a53f : 0x4f8c82, -1.1 + (i % 2) * 2.2, 1.55, 1.8 + Math.floor(i / 2) * 1.1);
}
boats.push(group);
}
function buildEnvironment() {
box(scene, 48, 1.2, 38, 0x766e5b, 0, -0.62, 0);
const tileCount = 12 * 9;
const tileGeometry = unitBox;
const tileMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.96 });
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
tiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const tileColors = [0xc7c0a8, 0xbeb9a2, 0xd0c8af, 0xc2bca5];
let tileIndex = 0;
for (let z = 0; z < 9; z++) {
for (let x = 0; x < 12; x++) {
dummy.position.set(-22 + x * 4, 0.04, -16 + z * 4);
dummy.scale.set(3.84, 0.10, 3.84);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
tiles.setColorAt(tileIndex, new THREE.Color(tileColors[(x + z * 2) % tileColors.length]));
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
for (let i = 0; i < 12; i++) {
box(
scene,
3.75,
0.52,
0.48,
i % 2 ? 0xe0b84c : 0x3b5050,
-22 + i * 4,
0.23,
18.55
);
}
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.38,
metalness: 0.12
});
const waterCount = 19 * 9;
const water = new THREE.InstancedMesh(unitBox, waterMaterial, waterCount);
water.receiveShadow = true;
let waterIndex = 0;
const waterPalette = [0x4c99a8, 0x438d9d, 0x5aa5af, 0x397f92, 0x68adb5];
for (let z = 0; z < 9; z++) {
for (let x = 0; x < 19; x++) {
const px = -45 + x * 5;
const pz = 21 + z * 5;
dummy.position.set(px, -0.12, pz);
dummy.scale.set(4.82, 0.22, 4.82);
dummy.updateMatrix();
water.setMatrixAt(waterIndex, dummy.matrix);
water.setColorAt(waterIndex, new THREE.Color(waterPalette[(x * 3 + z) % waterPalette.length]));
waterData.push({ x: px, z: pz, phase: (x * 0.41 + z * 0.73) % 6.28 });
waterIndex++;
}
}
water.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
water.instanceMatrix.needsUpdate = true;
water.instanceColor.needsUpdate = true;
scene.add(water);
for (let x = -22; x <= 22; x += 5.5) {
box(scene, 0.44, 0.72, 0.44, 0x3e5554, x, 0.38, 17.8);
box(scene, 0.72, 0.16, 0.72, 0x273f40, x, 0.78, 17.8);
}
buildWarehouse(-14, -14.1, 10.5, 4.4, 0x9a7659, "DEPÓSITO SINTÉTICO");
buildWarehouse(-2.5, -14.4, 11.0, 5.2, 0x846d59, "ARMAZÉM ILUSTRATIVO");
buildWarehouse(9.0, -14.1, 10.5, 4.5, 0x68766b, "CAIS MODELO");
buildCrane(18.5, 13.3);
buildPalm(-22, -5.5, 0.95);
buildPalm(22, -4.5, 0.9);
buildPalm(-21, 13.5, 0.72);
buildBoat(-14, 29, 0x244f64, 0.13);
buildBoat(15, 25, 0x7c493c, -0.2);
const containerColors = [0x376f76, 0xb35c48, 0xc39a42, 0x617d56];
for (let i = 0; i < 5; i++) {
const container = box(
scene,
4.4,
2.1,
2.3,
containerColors[i % containerColors.length],
-21.2,
1.25,
8.5 + (i % 2) * 2.7,
{ roughness: 0.75 }
);
container.rotation.y = i % 2 ? 0.03 : -0.03;
}
for (const x of [-8.5, 2]) {
box(scene, 0.18, 4.6, 0.18, 0x45605e, x, 2.45, 15.1);
box(scene, 0.8, 0.2, 0.8, 0x334b4b, x, 4.82, 15.1);
box(scene, 0.55, 0.25, 0.55, 0xffd58b, x, 4.67, 15.1, {
emissive: 0xf2a83f,
emissiveIntensity: 0.7
});
}
}
const graph = {
nodes: new Map(),
edges: [],
adjacency: new Map(),
edgeByKey: new Map()
};
const crowdAgents = [];
let delivery = null;
let deliveryCart = null;
let routeMarkers = [];
let deliveryCounter = 104;
let labelsVisible = true;
const routeVisualGroup = new THREE.Group();
scene.add(routeVisualGroup);
const routeMarkerMaterial = new THREE.MeshStandardMaterial({
color: 0x27d6c5,
roughness: 0.38,
metalness: 0.08,
emissive: 0x0b746c,
emissiveIntensity: 0.85
});
function edgeKey(a, b) {
return a < b ? `${a}|${b}` : `${b}|${a}`;
}
function addNode(id, x, z, type = "junction") {
graph.nodes.set(id, {
id,
type,
pos: new THREE.Vector3(x, 0, z)
});
graph.adjacency.set(id, new Map());
}
function addEdge(a, b) {
if (!graph.nodes.has(a) || !graph.nodes.has(b)) return;
const key = edgeKey(a, b);
if (graph.edgeByKey.has(key)) return;
const na = graph.nodes.get(a);
const nb = graph.nodes.get(b);
const edge = {
a,
b,
key,
length: Math.hypot(nb.pos.x - na.pos.x, nb.pos.z - na.pos.z),
branch: a.endsWith("_pick") || b.endsWith("_pick"),
bottleneck: false
};
graph.edges.push(edge);
graph.edgeByKey.set(key, edge);
graph.adjacency.get(a).set(b, edge);
graph.adjacency.get(b).set(a, edge);
}
function buildGraph() {
const nodes = [
["gate", 0, 14.6, "gate"],
["fw", -14, 14.6],
["fl", -8.5, 14.6],
["bf", -3, 14.6],
["fr", 2, 14.6],
["cf", 7, 14.6],
["ml", -8.5, 2.6],
["mr", 2, 2.6],
["md", -14, 2.6],
["ed", -3, 2.6],
["fd", 7, 2.6],
["bl", -8.5, -8],
["br", 2, -8],
["bd", -14, -8],
["bm", -3, -8],
["cd", 7, -8]
];
for (const [id, x, z, type] of nodes) addNode(id, x, z, type);
for (const stall of STALLS) {
addNode(`${stall.id}_pick`, stall.pickX, stall.pickZ, "pickup");
}
const edges = [
["fw", "fl"], ["fl", "bf"], ["bf", "gate"], ["gate", "fr"], ["fr", "cf"],
["fl", "ml"], ["md", "ml"], ["ml", "ed"], ["ed", "mr"], ["mr", "fd"],
["fr", "mr"], ["md", "bd"], ["ed", "bm"], ["fd", "cd"],
["ml", "bl"], ["mr", "br"],
["bd", "bl"], ["bl", "bm"], ["bm", "br"], ["br", "cd"]
];
for (const [a, b] of edges) addEdge(a, b);
addEdge("fw", "A_pick");
addEdge("bf", "B_pick");
addEdge("cf", "C_pick");
addEdge("md", "D_pick");
addEdge("ed", "E_pick");
addEdge("fd", "F_pick");
const bottleneck = graph.edgeByKey.get(edgeKey("fr", "mr"));
const widePassage = graph.edgeByKey.get(edgeKey("fl", "ml"));
bottleneck.bottleneck = true;
widePassage.widePassage = true;
}
function validateGraph() {
const invalidEdges = [];
for (const edge of graph.edges) {
if (
!graph.nodes.has(edge.a) ||
!graph.nodes.has(edge.b) ||
!graph.adjacency.get(edge.a)?.has(edge.b) ||
!graph.adjacency.get(edge.b)?.has(edge.a)
) {
invalidEdges.push(edge.key);
}
}
const visited = new Set();
const queue = ["gate"];
while (queue.length) {
const current = queue.shift();
if (visited.has(current)) continue;
visited.add(current);
for (const [neighbor] of graph.adjacency.get(current) || []) {
if (!visited.has(neighbor)) queue.push(neighbor);
}
}
const disconnected = [...graph.nodes.keys()].filter(id => !visited.has(id));
return {
ok: invalidEdges.length === 0 && disconnected.length === 0,
invalidEdges,
disconnected
};
}
function findPath(startId, endId) {
if (!graph.nodes.has(startId) || !graph.nodes.has(endId)) return [];
if (startId === endId) return [startId];
const distance = new Map();
const previous = new Map();
const remaining = new Set(graph.nodes.keys());
for (const id of remaining) distance.set(id, Infinity);
distance.set(startId, 0);
while (remaining.size) {
let current = null;
let best = Infinity;
for (const id of remaining) {
if (distance.get(id) < best) {
best = distance.get(id);
current = id;
}
}
if (current === null || !Number.isFinite(best)) break;
remaining.delete(current);
if (current === endId) break;
for (const [neighbor, edge] of graph.adjacency.get(current)) {
if (!remaining.has(neighbor)) continue;
const candidate = best + edge.length;
if (candidate < distance.get(neighbor)) {
distance.set(neighbor, candidate);
previous.set(neighbor, current);
}
}
}
if (!previous.has(endId)) return [];
const path = [endId];
while (path[0] !== startId) {
const parent = previous.get(path[0]);
if (!parent) return [];
path.unshift(parent);
}
return path;
}
function buildPathSurfaces() {
for (const edge of graph.edges) {
const a = graph.nodes.get(edge.a).pos;
const b = graph.nodes.get(edge.b).pos;
const dx = b.x - a.x;
const dz = b.z - a.z;
let width = 1.08;
let color = 0xc5b996;
if (edge.branch) {
width = 0.68;
color = 0xb5aa8c;
}
if (edge.bottleneck) {
width = 1.48;
color = 0xd59a61;
}
if (edge.widePassage) {
width = 2.05;
color = 0xc7b98e;
}
const mesh = box(
scene,
width,
0.075,
edge.length,
color,
(a.x + b.x) / 2,
0.16,
(a.z + b.z) / 2,
{ roughness: 0.98, castShadow: false }
);
mesh.rotation.y = Math.atan2(dx, dz);
edge.surface = mesh;
}
const rightGap =
(STALLS[2].x - HALF_FOOTPRINT) -
(STALLS[1].x + HALF_FOOTPRINT);
const leftGap =
(STALLS[1].x - HALF_FOOTPRINT) -
(STALLS[0].x + HALF_FOOTPRINT);
const bottleneckCenterX = (STALLS[1].x + STALLS[2].x) / 2;
box(scene, 0.1, 0.05, 6.1, 0xe58b45, bottleneckCenterX - rightGap / 2 + 0.12, 0.25, 8.0);
box(scene, 0.1, 0.05, 6.1, 0xe58b45, bottleneckCenterX + rightGap / 2 - 0.12, 0.25, 8.0);
for (const z of [5.35, 10.65]) {
box(scene, 0.14, 1.05, 0.14, 0xe58b45, bottleneckCenterX - rightGap / 2 + 0.08, 0.72, z);
box(scene, 0.14, 1.05, 0.14, 0xe58b45, bottleneckCenterX + rightGap / 2 - 0.08, 0.72, z);
}
const g2Sign = makeSignSprite("G2 · CONGESTÃO SINTÉTICA", {
width: 5.8,
background: "#a8512f",
foreground: "#fff0c9",
border: "#ffd083"
});
g2Sign.position.set(bottleneckCenterX, 4.65, 10.8);
scene.add(g2Sign);
const g1Sign = makeSignSprite("G1 · 2,8 m", {
width: 3.8,
background: "#315c5a",
foreground: "#e9f2d5",
border: "#84c8b9"
});
g1Sign.position.set(-8.5, 3.75, 8.0);
scene.add(g1Sign);
const bottleneckLabel = addWorldLabel(
"G2 · 1,8 m · CONGESTÃO",
new THREE.Vector3(bottleneckCenterX, 4.95, 8.1),
"hot"
);
addWorldLabel(
"G1 · 2,8 m",
new THREE.Vector3(-8.5, 4.0, 8.0),
"wide"
);
return { rightGap, leftGap, bottleneckCenterX, bottleneckLabel };
}
function makePerson(shirtColor, index = 0) {
const group = new THREE.Group();
const skin = [0xd49a70, 0x9b6248, 0xe1b18a, 0x704838][index % 4];
box(group, 0.58, 0.76, 0.42, shirtColor, 0, 1.03, 0);
box(group, 0.48, 0.48, 0.46, skin, 0, 1.66, 0);
box(group, 0.5, 0.16, 0.48, 0x3c3a33, 0, 1.91, -0.02);
const leftLeg = box(group, 0.21, 0.58, 0.25, 0x304b56, -0.16, 0.38, 0);
const rightLeg = box(group, 0.21, 0.58, 0.25, 0x304b56, 0.16, 0.38, 0);
box(group, 0.17, 0.58, 0.21, shirtColor, -0.39, 1.04, 0);
box(group, 0.17, 0.58, 0.21, shirtColor, 0.39, 1.04, 0);
group.userData.legs = [leftLeg, rightLeg];
return group;
}
function makeDeliveryCart() {
const group = new THREE.Group();
box(group, 0.95, 0.22, 1.12, 0x238c86, 0, 0.47, 0);
box(group, 0.69, 0.55, 0.72, 0xe8c56f, 0, 0.86, -0.05);
box(group, 0.73, 0.08, 0.76, 0xa8783f, 0, 1.16, -0.05);
box(group, 0.12, 0.82, 0.12, 0x3c5350, 0, 0.78, 0.52);
box(group, 0.76, 0.12, 0.12, 0x3c5350, 0, 1.15, 0.52);
for (const x of [-0.5, 0.5]) {
for (const z of [-0.37, 0.37]) {
box(group, 0.22, 0.25, 0.22, 0x26383a, x, 0.24, z);
}
}
box(group, 0.17, 0.17, 0.17, 0x27d6c5, 0, 1.3, -0.05, {
emissive: 0x27d6c5,
emissiveIntensity: 1.2
});
return group;
}
function spawnAgent(path, color, speed, options = {}) {
if (!path || path.length < 2) return null;
const group = makePerson(color, options.index || 0);
if (options.scale) group.scale.setScalar(options.scale);
scene.add(group);
const agent = {
group,
path: [...path],
index: 0,
progress: (options.startFraction || 0) * graph.edgeByKey.get(edgeKey(path[0], path[1])).length,
speed,
jitter: options.jitter || 0,
phase: options.phase || 0,
currentEdgeKey: null
};
crowdAgents.push(agent);
positionAgent(agent);
return agent;
}
function positionAgent(agent) {
if (!agent || agent.index >= agent.path.length - 1) return;
const a = graph.nodes.get(agent.path[agent.index]);
const b = graph.nodes.get(agent.path[agent.index + 1]);
const edge = graph.edgeByKey.get(edgeKey(a.id, b.id));
if (!edge) return;
const t = Math.min(1, agent.progress / edge.length);
const position = a.pos.clone().lerp(b.pos, t);
const dx = b.pos.x - a.pos.x;
const dz = b.pos.z - a.pos.z;
const length = Math.hypot(dx, dz) || 1;
position.x += (-dz / length) * agent.jitter;
position.z += (dx / length) * agent.jitter;
position.y = 0.24;
agent.group.position.copy(position);
agent.group.rotation.y = Math.atan2(dx, dz);
agent.currentEdgeKey = edge.key;
}
function populateInitialCrowd() {
const shirtColors = [
0xe2704e, 0x3d8da1, 0xe5b44d, 0x5b9b70, 0x785f91,
0xc85f72, 0x3e7776, 0xd9d2b5, 0x4d6675
];
// O povoamento inicial usa apenas pares cuja conexão direta foi verificada.
const directPairs = graph.edges.filter(edge =>
!edge.branch &&
!edge.bottleneck &&
edge.length > 3 &&
graph.adjacency.get(edge.a)?.has(edge.b) &&
graph.adjacency.get(edge.b)?.has(edge.a)
);
let index = 0;
for (let i = 0; i < directPairs.length; i += 3) {
const edge = directPairs[i];
spawnAgent(
[edge.a, edge.b],
shirtColors[index % shirtColors.length],
1.05 + (index % 3) * 0.16,
{
index,
phase: index * 0.73,
startFraction: 0.1 + ((index * 0.17) % 0.7)
}
);
index++;
}
// Cada banca recebe um fluxo que usa uma rota calculada pela malha.
STALLS.forEach((stall, stallIndex) => {
const path = findPath(`${stall.id}_pick`, "gate");
if (path.length > 1) {
spawnAgent(path, shirtColors[(index + stallIndex) % shirtColors.length], 0.92, {
index: index++,
phase: stallIndex * 1.1,
startFraction: 0.05 + stallIndex * 0.018
});
}
});
// Fila sintética na passagem G2, ocupa a faixa realmente estreita.
const bottleneck = graph.edgeByKey.get(edgeKey("fr", "mr"));
for (let i = 0; i < 8; i++) {
spawnAgent(
[bottleneck.a, bottleneck.b],
shirtColors[(index + i) % shirtColors.length],
0.34 + (i % 3) * 0.06,
{
index: index++,
phase: i * 0.81,
startFraction: 0.30 + i * 0.064,
jitter: (i % 2 ? 1 : -1) * (0.12 + (i % 3) * 0.045)
}
);
}
}
function updateAgent(agent, dt, time) {
if (!agent || agent.index >= agent.path.length - 1) return;
const a = graph.nodes.get(agent.path[agent.index]);
const b = graph.nodes.get(agent.path[agent.index + 1]);
const edge = graph.edgeByKey.get(edgeKey(a.id, b.id));
if (!edge) return;
let movement = agent.speed * dt;
if (edge.bottleneck) movement *= 0.2;
if (agent.progress + movement >= edge.length) {
agent.index++;
agent.progress = 0;
if (agent.index >= agent.path.length - 1) {
agent.path.reverse();
agent.index = 0;
}
} else {
agent.progress += movement;
}
positionAgent(agent);
const stride = Math.sin(time * 7.5 + agent.phase) * 0.36;
if (agent.group.userData.legs) {
agent.group.userData.legs[0].rotation.x = stride;
agent.group.userData.legs[1].rotation.x = -stride;
}
}
function updateAgents(dt, time) {
for (const agent of crowdAgents) updateAgent(agent, dt, time);
}
function clearRouteVisuals() {
for (const child of [...routeVisualGroup.children]) {
if (child.userData.ownedGeometry) child.geometry?.dispose();
if (child.userData.ownedMaterial) child.material?.dispose();
routeVisualGroup.remove(child);
}
routeMarkers = [];
}
function buildRouteVisuals(path) {
clearRouteVisuals();
const points = path.map(id => {
const p = graph.nodes.get(id).pos;
return new THREE.Vector3(p.x, 0.26, p.z);
});
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0x27d6c5,
transparent: true,
opacity: 0.88
});
const line = new THREE.Line(geometry, material);
line.userData.ownedGeometry = true;
line.userData.ownedMaterial = true;
line.renderOrder = 4;
routeVisualGroup.add(line);
for (let i = 0; i < path.length - 1; i++) {
const a = graph.nodes.get(path[i]).pos;
const b = graph.nodes.get(path[i + 1]).pos;
const length = Math.hypot(b.x - a.x, b.z - a.z);
const steps = Math.max(1, Math.floor(length / 0.68));
for (let j = 0; j <= steps; j++) {
const t = j / steps;
const marker = box(
routeVisualGroup,
0.2,
0.13,
0.2,
0x27d6c5,
a.x + (b.x - a.x) * t,
0.29,
a.z + (b.z - a.z) * t,
{ material: routeMarkerMaterial, castShadow: false }
);
routeMarkers.push({ mesh: marker, phase: i * 0.7 + j * 0.37 });
}
}
}
function buildDeliverySegments(path) {
let cumulative = 0;
const segments = [];
for (let i = 0; i < path.length - 1; i++) {
const a = graph.nodes.get(path[i]);
const b = graph.nodes.get(path[i + 1]);
const length = Math.hypot(b.pos.x - a.pos.x, b.pos.z - a.pos.z);
const key = edgeKey(a.id, b.id);
segments.push({
from: a.id,
to: b.id,
length,
start: cumulative,
end: cumulative + length,
edgeKey: key
});
cumulative += length;
}
return { segments, total: cumulative };
}
function scheduleDelivery(options) {
const pickup = options.pickup;
const dropoff = options.dropoff;
const path = findPath(`${pickup}_pick`, `${dropoff}_pick`);
if (path.length < 2) {
$("routeTitle").textContent = `${pickup} → ${dropoff}`;
$("routeMeta").textContent = "Não existe uma rota conectada entre os pontos escolhidos.";
$("routeState").textContent = "Rota indisponível";
$("routeState").dataset.state = "error";
$("statusLive").textContent = "Não foi possível criar a rota.";
return false;
}
if (!options.initial) deliveryCounter++;
const id = `FICT-${deliveryCounter}`;
if (deliveryCart) scene.remove(deliveryCart);
deliveryCart = makeDeliveryCart();
scene.add(deliveryCart);
const routeData = buildDeliverySegments(path);
delivery = {
id,
pickup,
dropoff,
slot: options.slot,
packageType: options.packageType,
path,
segments: routeData.segments,
total: routeData.total,
distance: options.initial ? routeData.total * 0.52 : 0,
speed: 2.45,
state: "moving",
currentEdgeKey: null
};
buildRouteVisuals(path);
updateDeliveryTransform();
$("routeTitle").textContent = `${pickup} → ${dropoff} · ${id}`;
$("routeMeta").textContent =
`${options.slot} · ${options.packageType} · ${routeData.total.toFixed(1).replace(".", ",")} m de percurso`;
$("routeDistance").textContent = `${routeData.total.toFixed(1).replace(".", ",")} m`;
$("routeState").dataset.state = "normal";
$("routeState").textContent = "Rota em curso";
$("statusLive").textContent = `Entrega fictícia ${id} agendada de ${pickup} para ${dropoff}.`;
updateMetrics();
return true;
}
function updateDeliveryTransform() {
if (!delivery || !deliveryCart) return;
let segment = delivery.segments[delivery.segments.length - 1];
for (const candidate of delivery.segments) {
if (delivery.distance < candidate.end) {
segment = candidate;
break;
}
}
const a = graph.nodes.get(segment.from).pos;
const b = graph.nodes.get(segment.to).pos;
const t = segment.length > 0
? Math.min(1, Math.max(0, (delivery.distance - segment.start) / segment.length))
: 0;
deliveryCart.position.set(
a.x + (b.x - a.x) * t,
0.13,
a.z + (b.z - a.z) * t
);
deliveryCart.rotation.y = Math.atan2(b.x - a.x, b.z - a.z);
delivery.currentEdgeKey = segment.edgeKey;
}
function updateDelivery(dt) {
if (!delivery || !deliveryCart) return;
if (delivery.distance >= delivery.total) {
delivery.distance = delivery.total;
delivery.state = "delivered";
updateDeliveryTransform();
return;
}
let segment = delivery.segments[0];
for (const candidate of delivery.segments) {
if (delivery.distance < candidate.end) {
segment = candidate;
break;
}
}
const edge = graph.edgeByKey.get(segment.edgeKey);
let factor = 1;
if (edge?.bottleneck) {
factor = computeCongestion() >= SYNTHETIC_CAPACITY + 1 ? 0.17 : 0.55;
}
delivery.distance = Math.min(
delivery.total,
delivery.distance + delivery.speed * dt * factor
);
updateDeliveryTransform();
}
function computeCongestion() {
const bottleneck = graph.edgeByKey.get(edgeKey("fr", "mr"));
const centerX = (STALLS[1].x + STALLS[2].x) / 2;
const halfWidth = bottleneck ? (STALLS[2].x - HALF_FOOTPRINT - (STALLS[1].x + HALF_FOOTPRINT)) / 2 : 0.9;
let count = 0;
for (const agent of crowdAgents) {
const p = agent.group.position;
if (
Math.abs(p.x - centerX) <= halfWidth + 0.34 &&
p.z >= 4.9 &&
p.z <= 11.25
) count++;
}
if (deliveryCart && deliveryCart.visible) {
const p = deliveryCart.position;
if (
Math.abs(p.x - centerX) <= halfWidth + 0.4 &&
p.z >= 4.9 &&
p.z <= 11.25
) count++;
}
return count;
}
function computeClearAccess() {
let clearCount = 0;
for (const zone of accessZones) {
let blocked = !zone.clear;
for (const agent of crowdAgents) {
const p = agent.group.position;
if (
Math.abs(p.x - zone.x) < zone.width / 2 + 0.32 &&
Math.abs(p.z - zone.z) < zone.depth / 2 + 0.32
) {
blocked = true;
break;
}
}
if (!blocked && deliveryCart && deliveryCart.visible) {
const p = deliveryCart.position;
if (
Math.abs(p.x - zone.x) < zone.width / 2 + 0.38 &&
Math.abs(p.z - zone.z) < zone.depth / 2 + 0.38
) {
blocked = true;
}
}
if (!blocked) clearCount++;
}
return clearCount;
}
function updateMetrics() {
const count = computeCongestion();
const clearAccess = computeClearAccess();
const level = count >= 6 ? "ALTA" : count >= 4 ? "CARGA" : "FLUXO";
const rightGap =
(STALLS[2].x - HALF_FOOTPRINT) -
(STALLS[1].x + HALF_FOOTPRINT);
$("bottleneckMetric").textContent = `${count} fluxos`;
$("bottleneckSub").textContent =
`${level} · largura ${rightGap.toFixed(1).replace(".", ",")} m · limite fictício ${SYNTHETIC_CAPACITY}`;
$("congestionBar").style.width = `${Math.min(100, count / 8 * 100)}%`;
$("congestionBar").style.background = level === "ALTA" ? "#e7634f" : "#f0a34b";
$("accessMetric").textContent = `${clearAccess}/${accessZones.length}`;
$("accessSub").textContent = clearAccess === accessZones.length
? "Entradas frontais livres"
: "Obstrução temporária detectada";
$("graphMetric").textContent = `${graph.edges.length} arestas`;
$("networkStatus").textContent = graphValidation.ok
? `REDE VALIDADA · ${graph.edges.length} ligações · 0 desconexos`
: `REDE COM FALHA · ${graphValidation.disconnected.length} desconexos`;
if (bottleneckInfo?.bottleneckLabel) {
bottleneckInfo.bottleneckLabel.element.textContent =
`G2 · ${rightGap.toFixed(1).replace(".", ",")} m · ${count} FLUXOS`;
}
if (delivery) {
const edge = graph.edgeByKey.get(delivery.currentEdgeKey);
if (delivery.state === "delivered") {
$("routeState").textContent = "Entrega concluída · simulação";
$("routeState").dataset.state = "normal";
} else if (edge?.bottleneck) {
$("routeState").textContent = "Retida na G2 · fila sintética";
$("routeState").dataset.state = "alert";
} else {
$("routeState").textContent = "Em trânsito · rota sintética";
$("routeState").dataset.state = "normal";
}
}
}
function updateRoutePulse(time) {
for (const marker of routeMarkers) {
const scale = 1 + Math.sin(time * 4.2 + marker.phase) * 0.22;
marker.mesh.scale.set(0.2 * scale, 0.13 * scale, 0.2 * scale);
}
}
function updateCamera() {
const horizontal = Math.cos(cameraRig.pitch) * cameraRig.distance;
camera.position.set(
cameraRig.target.x + Math.sin(cameraRig.yaw) * horizontal,
cameraRig.target.y + Math.sin(cameraRig.pitch) * cameraRig.distance,
cameraRig.target.z + Math.cos(cameraRig.yaw) * horizontal
);
camera.lookAt(cameraRig.target);
camera.updateMatrixWorld();
}
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (!cameraRig.userAdjusted) {
const fit = Math.max(1, 1.05 / camera.aspect);
cameraRig.distance = Math.min(78, 58 * fit);
}
updateCamera();
}
function updateWorldLabels() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
for (const label of worldLabels) {
const projected = label.position.clone().project(camera);
const visible =
labelsVisible &&
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.12 &&
projected.x < 1.12 &&
projected.y > -1.12 &&
projected.y < 1.12;
label.element.style.display = visible ? "block" : "none";
if (visible) {
label.element.style.left = `${(projected.x + 1) * 0.5 * width}px`;
label.element.style.top = `${(-projected.y + 1) * 0.5 * height}px`;
}
}
}
const waterDummy = new THREE.Object3D();
function updateWater(time) {
for (let i = 0; i < waterData.length; i++) {
const item = waterData[i];
waterDummy.position.set(item.x, -0.12 + Math.sin(time * 0.8 + item.phase) * 0.075, item.z);
waterDummy.scale.set(4.82, 0.22, 4.82);
waterDummy.updateMatrix();
scene.children.find(child => child.isInstancedMesh && child.count === waterData.length)
?.setMatrixAt(i, waterDummy.matrix);
}
const waterMesh = scene.children.find(child => child.isInstancedMesh && child.count === waterData.length);
if (waterMesh) waterMesh.instanceMatrix.needsUpdate = true;
for (let i = 0; i < boats.length; i++) {
boats[i].position.y = -0.04 + Math.sin(time * 0.65 + i * 1.8) * 0.055;
boats[i].rotation.z = Math.sin(time * 0.42 + i) * 0.012;
}
}
function setupCameraControls() {
const canvas = renderer.domElement;
let drag = null;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.focus({ preventScroll: true });
canvas.setPointerCapture(event.pointerId);
drag = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
button: event.button
};
cameraRig.userAdjusted = true;
});
canvas.addEventListener("pointermove", event => {
if (!drag || drag.id !== event.pointerId) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
if (drag.button === 2) {
const right = new THREE.Vector3(Math.cos(cameraRig.yaw), 0, -Math.sin(cameraRig.yaw));
const forward = new THREE.Vector3(-Math.sin(cameraRig.yaw), 0, -Math.cos(cameraRig.yaw));
const scale = cameraRig.distance * 0.0015;
cameraRig.target.addScaledVector(right, -dx * scale);
cameraRig.target.addScaledVector(forward, dy * scale);
cameraRig.target.x = THREE.MathUtils.clamp(cameraRig.target.x, -30, 30);
cameraRig.target.z = THREE.MathUtils.clamp(cameraRig.target.z, -24, 26);
} else {
cameraRig.yaw -= dx * 0.005;
cameraRig.pitch = THREE.MathUtils.clamp(cameraRig.pitch + dy * 0.004, 0.28, 1.42);
}
});
const stopDrag = event => {
if (drag && drag.id === event.pointerId) drag = null;
};
canvas.addEventListener("pointerup", stopDrag);
canvas.addEventListener("pointercancel", stopDrag);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRig.userAdjusted = true;
cameraRig.distance = THREE.MathUtils.clamp(
cameraRig.distance * Math.exp(event.deltaY * 0.001),
26,
88
);
}, { passive: false });
canvas.addEventListener("keydown", event => {
const step = 3;
if (event.key === "ArrowLeft") cameraRig.yaw += step * 0.03;
if (event.key === "ArrowRight") cameraRig.yaw -= step * 0.03;
if (event.key === "ArrowUp") cameraRig.pitch = THREE.MathUtils.clamp(cameraRig.pitch + 0.05, 0.28, 1.42);
if (event.key === "ArrowDown") cameraRig.pitch = THREE.MathUtils.clamp(cameraRig.pitch - 0.05, 0.28, 1.42);
});
}
let graphValidation = { ok: false, disconnected: [], invalidEdges: [] };
let bottleneckInfo = null;
// Primeiro construímos e desenhamos o mercado. Só depois a rede é populada.
buildEnvironment();
STALLS.forEach(buildStall);
resizeRenderer();
updateCamera();
renderer.render(scene, camera);
buildGraph();
graphValidation = validateGraph();
bottleneckInfo = buildPathSurfaces();
populateInitialCrowd();
$("scheduleDeliveryButton").addEventListener("click", () => {
scheduleDelivery({
pickup: $("pickup").value,
dropoff: $("dropoff").value,
slot: $("slot").value,
packageType: $("packageType").value,
initial: false
});
});
$("resetView").addEventListener("click", () => {
cameraRig.yaw = 0.22;
cameraRig.pitch = 0.62;
cameraRig.target.set(0, 1.2, 1.2);
cameraRig.userAdjusted = false;
resizeRenderer();
});
$("topView").addEventListener("click", () => {
cameraRig.yaw = 0;
cameraRig.pitch = 1.4;
cameraRig.userAdjusted = true;
updateCamera();
});
$("toggleLabels").addEventListener("click", () => {
labelsVisible = !labelsVisible;
labelsLayer.classList.toggle("off", !labelsVisible);
$("toggleLabels").textContent = labelsVisible ? "Rótulos ON" : "Rótulos OFF";
});
setupCameraControls();
new ResizeObserver(resizeRenderer).observe(viewport);
scheduleDelivery({
pickup: "B",
dropoff: "F",
slot: "08:00",
packageType: "Caixa sintética",
initial: true
});
$("routeState").textContent = "Exemplo em curso · rota sintética";
updateMetrics();
let previousTime = performance.now();
let lastMetricsTime = 0;
function animate(now) {
const dt = Math.min(0.05, Math.max(0, (now - previousTime) / 1000));
previousTime = now;
const time = now / 1000;
updateCamera();
updateWater(time);
updateAgents(dt, time);
updateDelivery(dt);
updateRoutePulse(time);
renderer.render(scene, camera);
updateWorldLabels();
if (now - lastMetricsTime > 250) {
updateMetrics();
lastMetricsTime = now;
}
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```