Prompt specification
Build or customize the Three.js 3D scene "Market layout exploration sandbox" 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: Market layout exploration sandbox
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/market-layout-exploration-sandbox-x0508
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: market layout exploration sandbox. Create a configurable stall grid with fictional visitor goals; users compare path lengths and congestion markers under stated routing rules while keeping a continuous accessible circulation network.
Working Three.js Starter (market-layout-exploration-sandbox-x0508):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Marketways — Layout Exploration Sandbox</title>
<style>
:root {
--paper: #f4f0e7;
--panel: #fffdf8;
--ink: #183238;
--muted: #6d7b7c;
--line: #ded8cc;
--teal: #187d78;
--teal-soft: #d8eeea;
--orange: #e77842;
--orange-soft: #f9e2d5;
--red: #c94b3f;
--yellow: #e3ad38;
--shadow: 0 12px 35px rgba(31, 48, 47, .12);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input, select { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
button:focus-visible,
input:focus-visible,
select:focus-visible {
outline: 3px solid rgba(24, 125, 120, .22);
outline-offset: 2px;
}
.app {
height: 100dvh;
display: grid;
grid-template-rows: 62px minmax(0, 1fr);
}
.topbar {
display: flex;
align-items: center;
gap: 18px;
padding: 0 18px;
background: var(--panel);
border-bottom: 1px solid var(--line);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 11px;
min-width: 235px;
}
.brand-mark {
width: 35px;
height: 35px;
display: grid;
place-items: center;
border-radius: 11px;
color: white;
background: var(--ink);
box-shadow: inset 0 -5px 0 rgba(255,255,255,.08);
}
.brand-mark svg {
width: 22px;
height: 22px;
}
.brand strong {
display: block;
font-size: 16px;
letter-spacing: -.02em;
}
.brand small {
display: block;
color: var(--muted);
font-size: 10px;
margin-top: 2px;
text-transform: uppercase;
letter-spacing: .13em;
}
.scenario-title {
flex: 1;
min-width: 0;
}
.scenario-title strong {
display: block;
font-size: 13px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.scenario-title span {
color: var(--muted);
font-size: 11px;
}
.header-actions {
display: flex;
align-items: center;
gap: 8px;
}
.header-pill {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border-radius: 999px;
background: var(--teal-soft);
color: var(--teal);
font-size: 11px;
font-weight: 750;
white-space: nowrap;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 4px rgba(24,125,120,.12);
}
.plain-button,
.small-button,
.primary-button {
border: 1px solid var(--line);
border-radius: 9px;
background: var(--panel);
font-weight: 700;
transition: background .15s, border-color .15s, transform .15s;
}
.plain-button:hover,
.small-button:hover {
background: #f3efe7;
border-color: #cfc7b9;
}
.plain-button:active,
.small-button:active,
.primary-button:active {
transform: translateY(1px);
}
.plain-button {
padding: 8px 11px;
font-size: 11px;
}
.small-button {
padding: 7px 10px;
font-size: 11px;
}
.primary-button {
padding: 10px 12px;
border-color: var(--teal);
background: var(--teal);
color: white;
font-size: 12px;
}
.mobile-toggle { display: none; }
.workspace {
min-height: 0;
display: grid;
grid-template-columns: 300px minmax(0, 1fr) 320px;
position: relative;
}
.panel {
min-height: 0;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #cbc4b8 transparent;
background: var(--panel);
z-index: 8;
}
.left-panel {
border-right: 1px solid var(--line);
}
.right-panel {
border-left: 1px solid var(--line);
}
.panel-section {
padding: 18px;
border-bottom: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 14px;
}
.section-heading h2 {
margin: 0;
font-size: 11px;
letter-spacing: .12em;
text-transform: uppercase;
font-weight: 850;
}
.section-heading span {
color: var(--muted);
font-size: 10px;
}
.field {
margin-bottom: 13px;
}
.field:last-child { margin-bottom: 0; }
.field-label {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 6px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
}
.field-label output {
color: var(--ink);
font-variant-numeric: tabular-nums;
font-weight: 800;
}
select,
input[type="number"],
input[type="text"] {
width: 100%;
min-width: 0;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--ink);
background: #faf8f3;
padding: 8px 9px;
font-size: 12px;
}
select:hover,
input:hover { border-color: #c7bfb2; }
.two-column {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
input[type="range"] {
width: 100%;
accent-color: var(--teal);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
color: #929994;
font-size: 9px;
margin-top: 2px;
}
.network-note {
display: grid;
grid-template-columns: 30px 1fr;
gap: 10px;
padding: 11px;
border: 1px solid #cde3de;
border-radius: 10px;
background: var(--teal-soft);
}
.network-note .network-icon {
width: 30px;
height: 30px;
display: grid;
place-items: center;
border-radius: 8px;
background: var(--teal);
color: white;
font-weight: 900;
}
.network-note strong {
display: block;
font-size: 11px;
margin-bottom: 3px;
}
.network-note p {
margin: 0;
color: #54706e;
font-size: 10px;
line-height: 1.45;
}
.goal-list {
display: grid;
gap: 9px;
}
.goal-card {
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fbfaf6;
}
.goal-card-top {
display: grid;
grid-template-columns: 10px minmax(0, 1fr) 54px;
align-items: center;
gap: 7px;
margin-bottom: 8px;
}
.goal-color {
width: 9px;
height: 9px;
border-radius: 50%;
}
.goal-card input[type="text"] {
border: 0;
border-bottom: 1px dashed #d5cfc4;
border-radius: 0;
padding: 3px 1px;
background: transparent;
font-size: 11px;
font-weight: 750;
}
.goal-card input[type="number"] {
padding: 5px 6px;
text-align: center;
font-size: 11px;
}
.goal-card select {
padding: 6px 7px;
font-size: 10px;
}
.goal-bottom {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
}
.goal-bottom span {
color: var(--muted);
font-size: 9px;
}
.remove-goal {
border: 0;
background: transparent;
color: #a66c5c;
font-size: 10px;
padding: 2px;
}
.full-width { width: 100%; }
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric-card {
min-height: 79px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: #fbfaf6;
}
.metric-card.wide { grid-column: 1 / -1; }
.metric-label {
display: block;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: .09em;
font-weight: 800;
margin-bottom: 7px;
}
.metric-value {
display: block;
font-size: 23px;
line-height: 1;
letter-spacing: -.04em;
font-variant-numeric: tabular-nums;
font-weight: 850;
}
.metric-value small {
font-size: 10px;
color: var(--muted);
letter-spacing: 0;
font-weight: 700;
}
.metric-sub {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 9px;
}
.policy-list {
display: grid;
gap: 7px;
}
.policy-button {
display: grid;
grid-template-columns: 25px 1fr auto;
align-items: center;
gap: 9px;
width: 100%;
text-align: left;
border: 1px solid var(--line);
border-radius: 10px;
background: #fbfaf6;
padding: 9px;
}
.policy-button:hover { border-color: #bdb5a8; }
.policy-button.active {
border-color: var(--teal);
background: var(--teal-soft);
box-shadow: inset 0 0 0 1px rgba(24,125,120,.08);
}
.policy-icon {
width: 25px;
height: 25px;
display: grid;
place-items: center;
border-radius: 7px;
background: #ece8df;
font-size: 12px;
font-weight: 900;
}
.policy-button.active .policy-icon {
background: var(--teal);
color: white;
}
.policy-name {
font-size: 11px;
font-weight: 800;
}
.policy-detail {
display: block;
color: var(--muted);
font-size: 9px;
margin-top: 2px;
}
.policy-length {
color: var(--muted);
font-size: 10px;
font-weight: 800;
white-space: nowrap;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th {
color: var(--muted);
text-align: right;
font-size: 8px;
text-transform: uppercase;
letter-spacing: .08em;
padding: 0 4px 8px;
}
th:first-child { text-align: left; }
td {
border-top: 1px solid #e8e2d8;
padding: 9px 4px;
text-align: right;
font-variant-numeric: tabular-nums;
}
td:first-child { text-align: left; }
tbody tr {
cursor: pointer;
}
tbody tr.active {
color: var(--teal);
background: rgba(216,238,234,.45);
}
.hotspot {
display: flex;
align-items: center;
gap: 10px;
padding: 11px;
border-radius: 10px;
background: var(--orange-soft);
}
.hotspot-icon {
width: 34px;
height: 34px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 50%;
background: var(--orange);
color: white;
font-weight: 900;
}
.hotspot strong {
display: block;
font-size: 11px;
}
.hotspot span {
display: block;
margin-top: 3px;
color: #8b6254;
font-size: 9px;
line-height: 1.35;
}
.rules {
margin: 0;
padding-left: 17px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.rules li { margin-bottom: 7px; }
.rules strong { color: var(--ink); }
.viewport {
min-width: 0;
min-height: 0;
position: relative;
overflow: hidden;
background: #eae6dc;
}
#canvasHost {
position: absolute;
inset: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#canvasHost canvas:active { cursor: grabbing; }
.viewport-top {
position: absolute;
top: 14px;
left: 14px;
right: 14px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
pointer-events: none;
z-index: 4;
}
.scene-badges {
display: flex;
flex-wrap: wrap;
gap: 7px;
max-width: 360px;
}
.scene-badge {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border: 1px solid rgba(24,50,56,.12);
border-radius: 999px;
background: rgba(255,253,248,.9);
backdrop-filter: blur(8px);
box-shadow: 0 4px 15px rgba(40,50,46,.08);
color: var(--ink);
font-size: 10px;
font-weight: 800;
}
.scene-badge .badge-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--teal);
}
.view-controls {
display: flex;
gap: 5px;
pointer-events: auto;
}
.view-controls button {
border: 1px solid rgba(24,50,56,.12);
background: rgba(255,253,248,.92);
backdrop-filter: blur(8px);
border-radius: 8px;
padding: 8px 9px;
font-size: 10px;
font-weight: 800;
box-shadow: 0 4px 15px rgba(40,50,46,.08);
}
.view-controls button:hover { background: white; }
.scene-caption {
position: absolute;
left: 16px;
bottom: 58px;
pointer-events: none;
color: rgba(24,50,56,.65);
font-size: 9px;
letter-spacing: .03em;
z-index: 4;
}
.legend {
position: absolute;
left: 14px;
bottom: 14px;
display: flex;
flex-wrap: wrap;
gap: 7px 12px;
max-width: calc(100% - 28px);
padding: 9px 11px;
border: 1px solid rgba(24,50,56,.12);
border-radius: 10px;
background: rgba(255,253,248,.9);
backdrop-filter: blur(8px);
pointer-events: none;
z-index: 4;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
font-size: 9px;
font-weight: 700;
}
.legend-swatch {
width: 9px;
height: 9px;
border-radius: 50%;
}
.legend-line {
width: 15px;
height: 2px;
background: var(--teal);
}
.tooltip {
position: fixed;
z-index: 50;
max-width: 240px;
padding: 9px 11px;
border-radius: 8px;
color: white;
background: rgba(24,50,56,.94);
box-shadow: var(--shadow);
pointer-events: none;
font-size: 10px;
line-height: 1.45;
opacity: 0;
transform: translateY(4px);
transition: opacity .1s, transform .1s;
}
.tooltip.visible {
opacity: 1;
transform: translateY(0);
}
.tooltip strong {
display: block;
font-size: 11px;
margin-bottom: 2px;
}
.tooltip span { color: #bcd3d1; }
.empty-state {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: var(--muted);
font-size: 13px;
}
@media (max-width: 1120px) {
.workspace { grid-template-columns: 270px minmax(0, 1fr) 290px; }
.panel-section { padding: 15px; }
.header-pill { display: none; }
}
@media (max-width: 920px) {
.workspace { grid-template-columns: 260px minmax(0, 1fr); }
.right-panel {
display: none;
position: absolute;
top: 10px;
right: 10px;
bottom: 10px;
width: 310px;
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: var(--shadow);
}
body.show-insights .right-panel { display: block; }
.mobile-toggle { display: inline-block; }
}
@media (max-width: 680px) {
.app { grid-template-rows: 56px minmax(0, 1fr); }
.topbar { padding: 0 10px; gap: 8px; }
.brand { min-width: 0; }
.brand small, .scenario-title { display: none; }
.brand strong { font-size: 14px; }
.workspace { display: block; }
.viewport { height: 100%; }
.left-panel {
display: none;
position: absolute;
top: 10px;
left: 10px;
bottom: 10px;
width: min(300px, calc(100% - 20px));
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: var(--shadow);
}
body.show-config .left-panel { display: block; }
.view-controls button { padding: 7px; }
.scene-caption { display: none; }
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M4 8h16l-2-4H6L4 8Z" stroke="currentColor" stroke-width="1.7"/>
<path d="M5 8v11h14V8M8 19v-6h8v6" stroke="currentColor" stroke-width="1.7"/>
<path d="M9 3v3M15 3v3" stroke="currentColor" stroke-width="1.7"/>
</svg>
</div>
<div>
<strong>Marketways</strong>
<small>Layout exploration sandbox</small>
</div>
</div>
<div class="scenario-title">
<strong>Saturday Neighborhood Market</strong>
<span>Fictional visitor goals · continuous accessible circulation</span>
</div>
<div class="header-actions">
<div class="header-pill">
<span class="status-dot"></span>
Network connected
</div>
<button class="plain-button mobile-toggle" id="configToggle">Config</button>
<button class="plain-button mobile-toggle" id="metricsToggle">Metrics</button>
<button class="plain-button" id="resetScenario">Reset</button>
</div>
</header>
<main class="workspace">
<aside class="panel left-panel">
<section class="panel-section">
<div class="section-heading">
<h2>Scenario</h2>
<span>01 / Layout</span>
</div>
<div class="field">
<label class="field-label" for="presetSelect">Visitor mix</label>
<select id="presetSelect">
<option value="balanced">Balanced browsing</option>
<option value="snack">Snack crawl</option>
<option value="family">Family errands</option>
</select>
</div>
<div class="two-column">
<div class="field">
<label class="field-label" for="rowsSelect">Rows</label>
<select id="rowsSelect">
<option value="3">3</option>
<option value="4" selected>4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="field">
<label class="field-label" for="colsSelect">Columns</label>
<select id="colsSelect">
<option value="4">4</option>
<option value="5">5</option>
<option value="6" selected>6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
</div>
<div class="field">
<label class="field-label" for="aisleRange">
Clear aisle width
<output id="aisleValue">2.4 m</output>
</label>
<input id="aisleRange" type="range" min="1.2" max="4" step="0.1" value="2.4">
<div class="range-ends"><span>1.2 m minimum</span><span>4.0 m</span></div>
</div>
<div class="field">
<label class="field-label" for="depthSelect">Stall depth</label>
<select id="depthSelect">
<option value="1.6">1.6 m</option>
<option value="2" selected>2.0 m</option>
<option value="2.4">2.4 m</option>
<option value="2.8">2.8 m</option>
</select>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Visitor goals</h2>
<span id="visitorTotal">24 visitors</span>
</div>
<div id="goalList" class="goal-list"></div>
<button id="addGoal" class="small-button full-width" style="margin-top:10px">
+ Add fictional goal
</button>
</section>
<section class="panel-section">
<div class="network-note">
<div class="network-icon">↔</div>
<div>
<strong>Continuous step-free circulation</strong>
<p>
An outer loop and orthogonal aisles are generated from every grid.
Stalls never block a route, and the minimum clear aisle is 1.2 m.
</p>
</div>
</div>
</section>
</aside>
<section class="viewport" id="viewport">
<div id="canvasHost"></div>
<div class="viewport-top">
<div class="scene-badges">
<div class="scene-badge">
<span class="badge-dot"></span>
<span id="scenePolicyBadge">Shortest path policy</span>
</div>
<div class="scene-badge" id="sceneSizeBadge">6 × 4 stalls</div>
</div>
<div class="view-controls">
<button data-view="iso">Isometric</button>
<button data-view="top">Top</button>
<button data-view="reset">Fit</button>
</div>
</div>
<div class="scene-caption">
Drag to orbit · Shift/right-drag to pan · Scroll to zoom · Hover stalls and markers
</div>
<div class="legend">
<div class="legend-item"><span class="legend-line"></span> Step-free aisle graph</div>
<div class="legend-item"><span class="legend-swatch" style="background:#187d78"></span> Low use</div>
<div class="legend-item"><span class="legend-swatch" style="background:#e3ad38"></span> Shared ×2–3</div>
<div class="legend-item"><span class="legend-swatch" style="background:#c94b3f"></span> Congested</div>
<div class="legend-item"><span class="legend-swatch" style="background:#e77842"></span> Goal</div>
</div>
<div id="emptyState" class="empty-state" hidden>
WebGL could not start in this browser.
</div>
</section>
<aside class="panel right-panel">
<section class="panel-section">
<div class="section-heading">
<h2>Live comparison</h2>
<span>02 / Routing</span>
</div>
<div class="metric-grid">
<div class="metric-card">
<span class="metric-label">Average path</span>
<span class="metric-value" id="averagePath">—</span>
<span class="metric-sub">active policy</span>
</div>
<div class="metric-card">
<span class="metric-label">Step-free</span>
<span class="metric-value" id="stepFree">100<small>%</small></span>
<span class="metric-sub">of visitor paths</span>
</div>
<div class="metric-card">
<span class="metric-label">Peak segment</span>
<span class="metric-value" id="peakLoad">—</span>
<span class="metric-sub">planned shared users</span>
</div>
<div class="metric-card">
<span class="metric-label">Collision index</span>
<span class="metric-value" id="collisionIndex">—</span>
<span class="metric-sub">relative pair overlap</span>
</div>
<div class="metric-card wide">
<span class="metric-label">Circulation network</span>
<span class="metric-value" id="networkLength">—</span>
<span class="metric-sub" id="networkSummary">continuous aisle length</span>
</div>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Routing rule</h2>
<span>Click to apply</span>
</div>
<div class="policy-list" id="policyList">
<button class="policy-button active" data-policy="shortest">
<span class="policy-icon">↝</span>
<span>
<span class="policy-name">Shortest</span>
<span class="policy-detail">Geometric distance only</span>
</span>
<span class="policy-length" data-length="shortest">—</span>
</button>
<button class="policy-button" data-policy="turns">
<span class="policy-icon">↱</span>
<span>
<span class="policy-name">Fewest turns</span>
<span class="policy-detail">Distance + turn penalty</span>
</span>
<span class="policy-length" data-length="turns">—</span>
</button>
<button class="policy-button" data-policy="crowd">
<span class="policy-icon">≈</span>
<span>
<span class="policy-name">Crowd-aware</span>
<span class="policy-detail">Distance + planned load</span>
</span>
<span class="policy-length" data-length="crowd">—</span>
</button>
<button class="policy-button" data-policy="loop">
<span class="policy-icon">◯</span>
<span>
<span class="policy-name">Loop-preferred</span>
<span class="policy-detail">Keep circulation on outer loop</span>
</span>
<span class="policy-length" data-length="loop">—</span>
</button>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Policy comparison</h2>
<span>Same goal set</span>
</div>
<table>
<thead>
<tr>
<th>Rule</th>
<th>Avg m</th>
<th>Peak</th>
<th>Index</th>
</tr>
</thead>
<tbody id="comparisonBody"></tbody>
</table>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Busiest segment</h2>
<span>Active plan</span>
</div>
<div class="hotspot">
<div class="hotspot-icon" id="hotspotIcon">×2</div>
<div>
<strong id="hotspotTitle">Calculating…</strong>
<span id="hotspotDetail">Marker load represents planned travelers sharing an aisle segment.</span>
</div>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Stated rules</h2>
<span>Deterministic</span>
</div>
<ul class="rules">
<li><strong>Shortest:</strong> sum of geometric aisle lengths.</li>
<li><strong>Fewest turns:</strong> length plus 1.4 m for each turn over roughly 7°.</li>
<li><strong>Crowd-aware:</strong> length plus 1.8 m for each already-planned user on a segment.</li>
<li><strong>Loop-preferred:</strong> length plus 1.1 m on internal segments and 0.45 m per turn.</li>
<li><strong>Accessibility:</strong> every rule uses only the same level circulation graph; no stall is crossed.</li>
<li><strong>Collision index:</strong> shared segment pairs divided by all possible visitor pairs, capped at 100.</li>
</ul>
</section>
</aside>
</main>
</div>
<div id="tooltip" class="tooltip" role="status"></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 COLORS = {
ink: 0x183238,
teal: 0x187d78,
orange: 0xe77842,
red: 0xc94b3f,
yellow: 0xe3ad38,
cream: 0xfffaf0,
floor: 0xe8e2d6
};
const STALL_TYPES = [
"Produce", "Bakery", "Tea", "Spice",
"Flowers", "Dairy", "Craft", "Books",
"Coffee", "Noodles", "Preserves", "Soap"
];
const STALL_COLORS = [
0x6f9f72, 0xd58b54, 0x4e8c87, 0xbc604c,
0x8b78a5, 0x6f91b4, 0xc18d45, 0x697c8e,
0x855f4a, 0xbd765f, 0x75945b, 0x9a6e88
];
const GOAL_COLORS = [
"#e77842", "#187d78", "#7b67a5", "#c94b3f",
"#3e7d9b", "#b48a2f", "#8a6b54"
];
const POLICY_NAMES = {
shortest: "Shortest path policy",
turns: "Fewest-turns policy",
crowd: "Crowd-aware policy",
loop: "Loop-preferred policy"
};
const defaultState = {
rows: 4,
cols: 6,
aisle: 2.4,
stallDepth: 2.0,
stallWidth: 2.2,
perimeter: 1.2,
seed: 17,
policy: "shortest",
preset: "balanced",
goals: [
{ name: "Pantry sweep", target: 0, count: 8 },
{ name: "Spice run", target: 3, count: 6 },
{ name: "Tea meet-up", target: 2, count: 5 },
{ name: "Treat detour", target: 1, count: 5 }
]
};
const state = structuredClone(defaultState);
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
} catch (error) {
$("emptyState").hidden = false;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
$("canvasHost").appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e5dc);
scene.fog = new THREE.Fog(0xe9e5dc, 34, 68);
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 120);
const cameraState = {
theta: 0.72,
phi: 0.78,
radius: 28,
target: new THREE.Vector3(0, 0, 0)
};
const marketGroup = new THREE.Group();
const congestionGroup = new THREE.Group();
const visitorGroup = new THREE.Group();
const goalGroup = new THREE.Group();
scene.add(marketGroup, congestionGroup, visitorGroup, goalGroup);
const ambient = new THREE.HemisphereLight(0xfff8e9, 0x77827e, 2.1);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xfff3d8, 3.1);
sun.position.set(-13, 22, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -30;
sun.shadow.camera.right = 30;
sun.shadow.camera.top = 30;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 60;
sun.shadow.bias = -0.0007;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8dce2, 0.7);
fill.position.set(15, 10, -18);
scene.add(fill);
let graph = null;
let allPlans = null;
let activePlan = null;
let visitors = [];
let markerPulses = [];
let pickables = [];
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function stallType(index) {
return STALL_TYPES[index % STALL_TYPES.length];
}
function stallCode(r, c) {
return String.fromCharCode(65 + r) + (c + 1);
}
function seededRandom(seed) {
let a = seed >>> 0;
return () => {
a += 0x6D2B79F5;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function angleDifference(a, b) {
return Math.atan2(Math.sin(a - b), Math.cos(a - b));
}
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeTextSprite(text, background = "#fffdf8", foreground = "#183238", width = 2.2) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 5, 9, 502, 110, 22);
ctx.fillStyle = background;
ctx.fill();
ctx.strokeStyle = "rgba(24,50,56,.15)";
ctx.lineWidth = 4;
ctx.stroke();
ctx.fillStyle = foreground;
ctx.font = "800 42px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 66, 475);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width / 4, 1);
sprite.userData.isLabel = true;
return sprite;
}
function disposeGroup(group) {
while (group.children.length) {
const child = group.children[0];
group.remove(child);
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach(material => {
if (material.map) material.map.dispose();
material.dispose();
});
}
});
}
}
function buildGraph() {
const g = {
nodes: new Map(),
edges: [],
adj: new Map(),
laneX: [],
laneZ: [],
width: 0,
depth: 0
};
const { cols, rows, aisle, stallWidth, stallDepth, perimeter } = state;
g.width = cols * stallWidth + (cols - 1) * aisle + perimeter * 2;
g.depth = rows * stallDepth + (rows - 1) * aisle + perimeter * 2;
g.laneX[0] = -g.width / 2 + perimeter / 2;
g.laneX[cols] = g.width / 2 - perimeter / 2;
for (let v = 1; v < cols; v++) {
g.laneX[v] =
-g.width / 2 + perimeter +
(v - 1) * (stallWidth + aisle) +
stallWidth + aisle / 2;
}
g.laneZ[0] = -g.depth / 2 + perimeter / 2;
g.laneZ[rows] = g.depth / 2 - perimeter / 2;
for (let h = 1; h < rows; h++) {
g.laneZ[h] =
-g.depth / 2 + perimeter +
(h - 1) * (stallDepth + aisle) +
stallDepth + aisle / 2;
}
function addNode(id, x, z, extra = {}) {
g.nodes.set(id, { id, x, z, ...extra });
g.adj.set(id, []);
}
function addEdge(a, b, kind = "aisle") {
const A = g.nodes.get(a);
const B = g.nodes.get(b);
const length = Math.hypot(B.x - A.x, B.z - A.z);
const outer =
(A.h === 0 && B.h === 0) ||
(A.h === rows && B.h === rows) ||
(A.v === 0 && B.v === 0) ||
(A.v === cols && B.v === cols);
const edge = {
id: g.edges.length,
a,
b,
length,
kind,
outer,
midpoint: new THREE.Vector3((A.x + B.x) / 2, 0, (A.z + B.z) / 2)
};
g.edges.push(edge);
g.adj.get(a).push({ to: b, edge });
g.adj.get(b).push({ to: a, edge });
return edge;
}
for (let h = 0; h <= rows; h++) {
for (let v = 0; v <= cols; v++) {
addNode(
`j-${h}-${v}`,
g.laneX[v],
g.laneZ[h],
{ kind: "junction", h, v }
);
}
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const x = stallX(g, c);
const z = g.laneZ[r + 1];
addNode(
`a-${r}-${c}`,
x,
z,
{ kind: "access", r, c, h: r + 1, v: null }
);
}
}
// Horizontal aisle edges. Stall frontage points split each lane,
// allowing a goal to be reached at the exact service position.
for (let h = 0; h <= rows; h++) {
for (let c = 0; c < cols; c++) {
const left = `j-${h}-${c}`;
const right = `j-${h}-${c + 1}`;
if (h === 0) {
addEdge(left, right);
} else {
const access = `a-${h - 1}-${c}`;
addEdge(left, access);
addEdge(access, right);
}
}
}
// Vertical cross-aisles.
for (let v = 0; v <= cols; v++) {
for (let h = 0; h < rows; h++) {
addEdge(`j-${h}-${v}`, `j-${h + 1}-${v}`, "cross-aisle");
}
}
const entranceX = 0;
const entranceZ = g.depth / 2 - 0.1;
const southLaneNodes = [...g.nodes.values()]
.filter(node => node.h === rows)
.sort((a, b) => a.x - b.x);
const exact = southLaneNodes.find(
node => Math.abs(node.x - entranceX) < 0.001 && Math.abs(node.z - entranceZ) < 0.2
);
let startId;
if (exact) {
startId = exact.id;
} else {
addNode("entrance", entranceX, entranceZ, { kind: "entrance", h: rows });
startId = "entrance";
let left = null;
let right = null;
for (const node of southLaneNodes) {
if (node.x < entranceX && (!left || node.x > left.x)) left = node;
if (node.x > entranceX && (!right || node.x < right.x)) right = node;
}
if (left) addEdge("entrance", left.id, "entry");
if (right) addEdge("entrance", right.id, "entry");
}
g.startId = startId;
g.networkLength = g.edges.reduce((sum, edge) => sum + edge.length, 0);
return g;
}
function stallX(g, c) {
return -g.width / 2 + state.perimeter +
c * (state.stallWidth + state.aisle) +
state.stallWidth / 2;
}
function stallZ(g, r) {
return -g.depth / 2 + state.perimeter +
r * (state.stallDepth + state.aisle) +
state.stallDepth / 2;
}
function createWorld() {
disposeGroup(marketGroup);
pickables = [];
const g = graph;
const plaza = new THREE.Mesh(
new THREE.BoxGeometry(g.width + 5, 0.18, g.depth + 5),
new THREE.MeshStandardMaterial({ color: 0xe3ddd1, roughness: 0.98 })
);
plaza.position.y = -0.11;
plaza.receiveShadow = true;
marketGroup.add(plaza);
const deck = new THREE.Mesh(
new THREE.BoxGeometry(g.width, 0.08, g.depth),
new THREE.MeshStandardMaterial({ color: 0xf0eadf, roughness: 0.93 })
);
deck.position.y = -0.02;
deck.receiveShadow = true;
marketGroup.add(deck);
const linePositions = [];
const outerPositions = [];
for (const edge of g.edges) {
const a = g.nodes.get(edge.a);
const b = g.nodes.get(edge.b);
const target = edge.outer ? outerPositions : linePositions;
target.push(a.x, 0.045, a.z, b.x, 0.045, b.z);
}
const networkGeometry = new THREE.BufferGeometry();
networkGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(linePositions, 3)
);
const networkLines = new THREE.LineSegments(
networkGeometry,
new THREE.LineBasicMaterial({
color: COLORS.teal,
transparent: true,
opacity: 0.34,
depthWrite: false
})
);
marketGroup.add(networkLines);
if (outerPositions.length) {
const outerGeometry = new THREE.BufferGeometry();
outerGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(outerPositions, 3)
);
marketGroup.add(new THREE.LineSegments(
outerGeometry,
new THREE.LineBasicMaterial({
color: COLORS.orange,
transparent: true,
opacity: 0.7,
depthWrite: false
})
));
}
for (let r = 0; r < state.rows; r++) {
for (let c = 0; c < state.cols; c++) {
createStall(r, c);
}
}
createEntrance();
const north = makeTextSprite(
"N",
"#fffdf8",
"#183238",
0.9
);
north.position.set(-g.width / 2 - 1.4, 0.08, -g.depth / 2 + 0.8);
north.material.rotation = 0;
marketGroup.add(north);
}
function createStall(r, c) {
const index = r * state.cols + c;
const g = graph;
const width = state.stallWidth;
const depth = state.stallDepth;
const type = stallType(index);
const baseColor = STALL_COLORS[index % STALL_COLORS.length];
const group = new THREE.Group();
group.position.set(stallX(g, c), 0, stallZ(g, r));
const wood = new THREE.MeshStandardMaterial({
color: 0xb98959,
roughness: 0.88
});
const darkWood = new THREE.MeshStandardMaterial({
color: 0x74533b,
roughness: 0.9
});
const vendorColor = new THREE.MeshStandardMaterial({
color: baseColor,
roughness: 0.82
});
const cream = new THREE.MeshStandardMaterial({
color: 0xfff4dd,
roughness: 0.88
});
const counter = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.9, 0.58, depth * 0.34),
wood
);
counter.position.set(0, 0.29, depth * 0.18);
counter.castShadow = true;
counter.receiveShadow = true;
group.add(counter);
const back = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.91, 1.35, 0.09),
darkWood
);
back.position.set(0, 0.68, -depth * 0.4);
back.castShadow = true;
group.add(back);
const stripeCount = 6;
const stripeWidth = width * 0.93 / stripeCount;
for (let s = 0; s < stripeCount; s++) {
const stripe = new THREE.Mesh(
new THREE.BoxGeometry(stripeWidth * 0.96, 0.11, depth * 0.53),
s % 2 === 0 ? vendorColor : cream
);
stripe.position.set(
-width * 0.465 + stripeWidth * (s + 0.5),
1.48,
-depth * 0.04
);
stripe.castShadow = true;
group.add(stripe);
}
const postGeometry = new THREE.CylinderGeometry(0.045, 0.055, 1.55, 6);
for (const x of [-width * 0.43, width * 0.43]) {
const post = new THREE.Mesh(postGeometry, darkWood);
post.position.set(x, 0.77, -depth * 0.24);
post.castShadow = true;
group.add(post);
}
const produceGeometry = new THREE.IcosahedronGeometry(0.16, 0);
const produceColors = [baseColor, 0xe6ad42, 0xc96545, 0x8cad59];
for (let p = 0; p < 5; p++) {
const produce = new THREE.Mesh(
produceGeometry,
new THREE.MeshStandardMaterial({
color: produceColors[p % produceColors.length],
roughness: 0.9
})
);
produce.position.set(
-width * 0.3 + p * width * 0.15,
0.73,
depth * 0.18 + (p % 2) * 0.07
);
produce.rotation.set(p * 0.6, p * 0.9, 0);
produce.castShadow = true;
group.add(produce);
}
const sign = makeTextSprite(
`${stallCode(r, c)} ${type.toUpperCase()}`,
"#fffdf8",
"#183238",
Math.min(width * 0.88, 2.35)
);
sign.position.set(0, 1.93, -depth * 0.08);
group.add(sign);
group.traverse(object => {
if (object.isMesh) {
object.userData = {
hoverType: "stall",
index,
r,
c,
code: stallCode(r, c),
title: type,
detail: `Stall ${stallCode(r, c)} · ${state.stallWidth.toFixed(1)} × ${state.stallDepth.toFixed(1)} m footprint`
};
pickables.push(object);
}
});
marketGroup.add(group);
}
function createEntrance() {
const group = new THREE.Group();
const z = graph.depth / 2 + 0.15;
const material = new THREE.MeshStandardMaterial({
color: COLORS.teal,
roughness: 0.72
});
for (const x of [-0.72, 0.72]) {
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.065, 0.08, 1.8, 6),
material
);
post.position.set(x, 0.9, z);
post.castShadow = true;
group.add(post);
}
const bar = new THREE.Mesh(
new THREE.BoxGeometry(1.65, 0.14, 0.14),
material
);
bar.position.set(0, 1.8, z);
bar.castShadow = true;
group.add(bar);
const sign = makeTextSprite("MARKET ENTRY", "#fffdf8", "#183238", 2.2);
sign.position.set(0, 2.18, z);
group.add(sign);
marketGroup.add(group);
}
function rebuildSpecs() {
const random = seededRandom(state.seed);
const specs = [];
state.goals.forEach((goal, goalIndex) => {
for (let i = 0; i < goal.count; i++) {
specs.push({ goalIndex, uid: specs.length });
}
});
for (let i = specs.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[specs[i], specs[j]] = [specs[j], specs[i]];
}
state.visitorSpecs = specs;
}
function dijkstra(targetId, policy, loads) {
const distances = new Map();
const previous = new Map();
const directions = new Map();
const queue = [];
distances.set(graph.startId, 0);
queue.push({ id: graph.startId, cost: 0 });
while (queue.length) {
queue.sort((a, b) => a.cost - b.cost);
const current = queue.shift();
if (current.cost !== distances.get(current.id)) continue;
if (current.id === targetId) break;
const incomingDirection = directions.get(current.id);
for (const { to, edge } of graph.adj.get(current.id)) {
if (distances.has(to) && distances.get(to) <= current.cost + edge.length) {
// Costs below are applied before the dominance check.
}
const A = graph.nodes.get(current.id);
const B = graph.nodes.get(to);
const direction = Math.atan2(B.x - A.x, B.z - A.z);
const turn =
incomingDirection !== undefined &&
Math.abs(angleDifference(direction, incomingDirection)) > 0.12;
let penalty = 0;
if (policy === "turns") {
if (turn) penalty += 1.4;
} else if (policy === "crowd") {
penalty += (loads.get(edge.id) || 0) * 1.8;
} else if (policy === "loop") {
if (!edge.outer) penalty += 1.1;
if (turn) penalty += 0.45;
}
const cost = current.cost + edge.length + penalty;
if (!distances.has(to) || cost < distances.get(to) - 0.00001) {
distances.set(to, cost);
previous.set(to, { from: current.id, edge });
directions.set(to, direction);
queue.push({ id: to, cost });
}
}
}
if (!distances.has(targetId)) return null;
const nodeIds = [];
const edgeIds = [];
let current = targetId;
while (current !== graph.startId) {
nodeIds.unshift(current);
const step = previous.get(current);
if (!step) break;
edgeIds.unshift(step.edge.id);
current = step.from;
}
nodeIds.unshift(graph.startId);
return {
nodeIds,
edgeIds,
geometricLength: edgeIds.reduce(
(sum, id) => sum + graph.edges[id].length,
0
)
};
}
function computePlan(policy) {
const loads = new Map(graph.edges.map(edge => [edge.id, 0]));
const routes = [];
for (const spec of state.visitorSpecs) {
const goal = state.goals[spec.goalIndex];
const r = Math.floor(goal.target / state.cols);
const c = goal.target % state.cols;
const targetId = `a-${r}-${c}`;
const route = dijkstra(targetId, policy, loads);
if (!route) continue;
route.goalIndex = spec.goalIndex;
route.uid = spec.uid;
routes.push(route);
for (const edgeId of route.edgeIds) {
loads.set(edgeId, (loads.get(edgeId) || 0) + 1);
}
}
const visitorCount = routes.length;
const peak = Math.max(0, ...loads.values());
let sharedPairs = 0;
for (const load of loads.values()) {
sharedPairs += load * (load - 1) / 2;
}
const possiblePairs = visitorCount > 1
? visitorCount * (visitorCount - 1) / 2
: 1;
const averageLength = visitorCount
? routes.reduce((sum, route) => sum + route.geometricLength, 0) / visitorCount
: 0;
const index = Math.min(100, Math.round((sharedPairs / possiblePairs) * 100));
return {
policy,
routes,
loads,
peak,
sharedPairs,
index,
averageLength
};
}
function computeAllPlans() {
rebuildSpecs();
allPlans = {};
for (const policy of ["shortest", "turns", "crowd", "loop"]) {
allPlans[policy] = computePlan(policy);
}
activePlan = allPlans[state.policy];
}
function makePath(nodeIds) {
const points = nodeIds.map(id => graph.nodes.get(id));
const cumulative = [0];
for (let i = 1; i < points.length; i++) {
cumulative.push(
cumulative[i - 1] +
Math.hypot(
points[i].x - points[i - 1].x,
points[i].z - points[i - 1].z
)
);
}
return { points, cumulative, length: cumulative[cumulative.length - 1] };
}
function pointAlongPath(path, distance) {
const d = THREE.MathUtils.clamp(distance, 0, path.length);
for (let i = 1; i < path.points.length; i++) {
const a = path.points[i - 1];
const b = path.points[i];
const segmentLength = path.cumulative[i] - path.cumulative[i - 1];
if (d <= path.cumulative[i] || i === path.points.length - 1) {
const t = segmentLength
? (d - path.cumulative[i - 1]) / segmentLength
: 0;
return {
x: THREE.MathUtils.lerp(a.x, b.x, t),
z: THREE.MathUtils.lerp(a.z, b.z, t),
dx: b.x - a.x,
dz: b.z - a.z
};
}
}
return path.points[0];
}
function renderActive() {
disposeGroup(visitorGroup);
disposeGroup(congestionGroup);
disposeGroup(goalGroup);
visitors = [];
markerPulses = [];
pickables = pickables.filter(item => item.userData.hoverType !== "congestion");
renderGoalPins();
renderCongestionMarkers();
renderVisitors();
}
function renderGoalPins() {
state.goals.forEach((goal, index) => {
const r = Math.floor(goal.target / state.cols);
const c = goal.target % state.cols;
const node = graph.nodes.get(`a-${r}-${c}`);
if (!node) return;
const group = new THREE.Group();
group.position.set(node.x, 0, node.z);
const color = GOAL_COLORS[index % GOAL_COLORS.length];
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.045, 1.3, 6),
new THREE.MeshStandardMaterial({ color })
);
pole.position.y = 0.65;
group.add(pole);
const pin = new THREE.Mesh(
new THREE.OctahedronGeometry(0.22, 0),
new THREE.MeshStandardMaterial({ color, roughness: 0.65 })
);
pin.position.y = 1.45;
pin.castShadow = true;
group.add(pin);
const label = makeTextSprite(
`${goal.name || "Goal"} · ${goal.count}`,
color,
"#ffffff",
Math.max(1.7, Math.min(3.2, 0.26 * goal.name.length + 0.8))
);
label.position.y = 2.03;
group.add(label);
goalGroup.add(group);
});
}
function renderCongestionMarkers() {
const entries = [...activePlan.loads.entries()]
.filter(([, load]) => load > 0)
.sort((a, b) => b[1] - a[1]);
for (const [edgeId, load] of entries) {
const edge = graph.edges[edgeId];
const ratio = activePlan.peak ? load / activePlan.peak : 0;
let color = COLORS.teal;
if (load >= 3 && ratio >= 0.65) color = COLORS.red;
else if (load >= 2) color = COLORS.yellow;
const group = new THREE.Group();
group.position.set(edge.midpoint.x, 0.03, edge.midpoint.z);
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.22, 0.34, 6),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.88,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.userData = {
hoverType: "congestion",
title: `Congestion marker ×${load}`,
detail: describeEdge(edge)
};
pickables.push(ring);
group.add(ring);
const height = Math.min(1.35, 0.35 + load * 0.12);
const column = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.075, height, 6),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.75,
depthWrite: false
})
);
column.position.y = height / 2;
group.add(column);
if (load >= 2) {
const label = makeTextSprite(`×${load}`, "#fffdf8", `#${color.toString(16).padStart(6, "0")}`, 0.72);
label.position.y = height + 0.32;
group.add(label);
}
markerPulses.push({ ring, phase: edgeId * 0.7 });
congestionGroup.add(group);
}
}
function renderVisitors() {
const random = seededRandom(state.seed + 99);
activePlan.routes.forEach((route, index) => {
const goal = state.goals[route.goalIndex];
const color = GOAL_COLORS[route.goalIndex % GOAL_COLORS.length];
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.11, 0.15, 0.53, 5),
new THREE.MeshStandardMaterial({ color, roughness: 0.75 })
);
body.position.y = 0.43;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.13, 0),
new THREE.MeshStandardMaterial({ color: 0xe8b38f, roughness: 0.9 })
);
head.position.y = 0.84;
head.castShadow = true;
group.add(head);
const bag = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.22, 0.11),
new THREE.MeshStandardMaterial({ color: 0x354b4c, roughness: 0.88 })
);
bag.position.set(0, 0.5, -0.12);
group.add(bag);
const halo = new THREE.Mesh(
new THREE.CircleGeometry(0.18, 12),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.35,
depthWrite: false,
side: THREE.DoubleSide
})
);
halo.rotation.x = -Math.PI / 2;
halo.position.y = 0.025;
group.add(halo);
const outbound = makePath(route.nodeIds);
const returnPath = makePath([...route.nodeIds].reverse());
const full = {
points: [...outbound.points, ...returnPath.points.slice(1)],
cumulative: [],
length: outbound.length + returnPath.length
};
let cumulative = 0;
full.cumulative.push(0);
for (let i = 1; i < full.points.length; i++) {
cumulative += Math.hypot(
full.points[i].x - full.points[i - 1].x,
full.points[i].z - full.points[i - 1].z
);
full.cumulative.push(cumulative);
}
const visitor = {
group,
path: full,
distance: random() * full.length,
direction: 1,
speed: 0.85 + random() * 0.4,
offset: (random() - 0.5) * 0.24,
dwell: 0,
goalName: goal.name,
phase: random() * Math.PI * 2
};
visitors.push(visitor);
visitorGroup.add(group);
});
}
function describeEdge(edge) {
const a = graph.nodes.get(edge.a);
const b = graph.nodes.get(edge.b);
if (edge.kind === "entry") return "Entrance feeder segment";
if (a.h !== undefined && b.h !== undefined && a.h === b.h) {
return `Horizontal aisle ${a.h + 1}`;
}
if (a.v !== undefined && b.v !== undefined && a.v === b.v) {
return `Cross-aisle ${a.v + 1}`;
}
return "Circulation segment";
}
function renderGoalRows() {
const list = $("goalList");
list.innerHTML = "";
state.goals.forEach((goal, index) => {
const card = document.createElement("div");
card.className = "goal-card";
const color = GOAL_COLORS[index % GOAL_COLORS.length];
card.innerHTML = `
<div class="goal-card-top">
<span class="goal-color" style="background:${color}"></span>
<input
type="text"
data-field="name"
data-index="${index}"
value="${escapeAttribute(goal.name)}"
aria-label="Goal name ${index + 1}"
>
<input
type="number"
min="1"
max="20"
data-field="count"
data-index="${index}"
value="${goal.count}"
aria-label="Number of visitors for goal ${index + 1}"
>
</div>
<div class="goal-bottom">
<select data-field="target" data-index="${index}" aria-label="Target stall for goal ${index + 1}">
${targetOptions(goal.target)}
</select>
${state.goals.length > 1 ? `<button class="remove-goal" data-remove="${index}">Remove</button>` : ""}
</div>
`;
list.appendChild(card);
});
const total = state.goals.reduce((sum, goal) => sum + goal.count, 0);
$("visitorTotal").textContent = `${total} visitor${total === 1 ? "" : "s"}`;
}
function targetOptions(selected) {
let html = "";
for (let r = 0; r < state.rows; r++) {
for (let c = 0; c < state.cols; c++) {
const index = r * state.cols + c;
html += `
<option value="${index}" ${index === selected ? "selected" : ""}>
${stallCode(r, c)} · ${stallType(index)}
</option>
`;
}
}
return html;
}
function escapeAttribute(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll('"', """)
.replaceAll("<", "<")
.replaceAll(">", ">");
}
function renderAnalytics() {
const total = state.goals.reduce((sum, goal) => sum + goal.count, 0);
$("averagePath").innerHTML = `${activePlan.averageLength.toFixed(1)}<small> m</small>`;
$("stepFree").innerHTML = `${total ? 100 : 0}<small>%</small>`;
$("peakLoad").innerHTML = `${activePlan.peak}<small> users</small>`;
$("collisionIndex").innerHTML = `${activePlan.index}<small>%</small>`;
$("networkLength").innerHTML = `${graph.networkLength.toFixed(1)}<small> m</small>`;
$("networkSummary").textContent =
`${state.rows} × ${state.cols} stalls · ${state.aisle.toFixed(1)} m clear aisles`;
$("scenePolicyBadge").textContent = POLICY_NAMES[state.policy];
$("sceneSizeBadge").textContent = `${state.cols} × ${state.rows} stalls`;
document.querySelectorAll(".policy-button").forEach(button => {
button.classList.toggle("active", button.dataset.policy === state.policy);
const plan = allPlans[button.dataset.policy];
const length = button.querySelector("[data-length]");
if (length) length.textContent = `${plan.averageLength.toFixed(1)} m`;
});
const rows = ["shortest", "turns", "crowd", "loop"].map(policy => {
const plan = allPlans[policy];
return `
<tr data-policy="${policy}" class="${policy === state.policy ? "active" : ""}">
<td>${policyLabel(policy)}</td>
<td>${plan.averageLength.toFixed(1)}</td>
<td>${plan.peak}</td>
<td>${plan.index}%</td>
</tr>
`;
}).join("");
$("comparisonBody").innerHTML = rows;
const entries = [...activePlan.loads.entries()]
.filter(([, load]) => load > 0)
.sort((a, b) => b[1] - a[1]);
if (entries.length) {
const [edgeId, load] = entries[0];
const edge = graph.edges[edgeId];
$("hotspotIcon").textContent = `×${load}`;
$("hotspotTitle").textContent = describeEdge(edge);
$("hotspotDetail").textContent =
`${load} planned travelers share this segment under ${POLICY_NAMES[state.policy].toLowerCase()}.`;
} else {
$("hotspotIcon").textContent = "—";
$("hotspotTitle").textContent = "No visitors";
$("hotspotDetail").textContent = "Add visitors to generate a routing plan.";
}
}
function policyLabel(policy) {
return {
shortest: "Shortest",
turns: "Fewest turns",
crowd: "Crowd-aware",
loop: "Loop-preferred"
}[policy];
}
function rebuildAll({ fit = false } = {}) {
graph = buildGraph();
createWorld();
computeAllPlans();
renderGoalRows();
renderActive();
renderAnalytics();
if (fit) fitCamera();
}
function fitCamera() {
const maxDimension = Math.max(graph.width, graph.depth);
cameraState.radius = maxDimension * 1.28 + 3;
cameraState.theta = 0.72;
cameraState.phi = 0.78;
cameraState.target.set(0, 0, 0);
updateCamera();
}
function updateCamera() {
const offset = new THREE.Vector3().setFromSphericalCoords(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.copy(cameraState.target).add(offset);
camera.lookAt(cameraState.target);
camera.zoom = 20 / cameraState.radius;
camera.updateProjectionMatrix();
}
function resize() {
const host = $("canvasHost");
const width = host.clientWidth;
const height = host.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
const aspect = width / height;
camera.left = -10 * aspect;
camera.right = 10 * aspect;
camera.top = 10;
camera.bottom = -10;
updateCamera();
}
// UI events
$("presetSelect").addEventListener("change", event => {
state.preset = event.target.value;
const counts = {
balanced: [8, 6, 5, 5],
snack: [3, 8, 4, 6],
family: [10, 10, 8, 8]
}[state.preset];
state.goals.forEach((goal, index) => {
goal.count = counts[index] ?? 4;
});
rebuildAll();
});
$("rowsSelect").addEventListener("change", event => {
state.rows = Number(event.target.value);
const total = state.rows * state.cols;
state.goals.forEach(goal => goal.target = Math.min(goal.target, total - 1));
rebuildAll({ fit: true });
});
$("colsSelect").addEventListener("change", event => {
state.cols = Number(event.target.value);
const total = state.rows * state.cols;
state.goals.forEach(goal => goal.target = Math.min(goal.target, total - 1));
rebuildAll({ fit: true });
});
$("aisleRange").addEventListener("input", event => {
state.aisle = Number(event.target.value);
$("aisleValue").textContent = `${state.aisle.toFixed(1)} m`;
rebuildAll({ fit: true });
});
$("depthSelect").addEventListener("change", event => {
state.stallDepth = Number(event.target.value);
rebuildAll({ fit: true });
});
$("goalList").addEventListener("change", event => {
const field = event.target.dataset.field;
const index = Number(event.target.dataset.index);
if (field === undefined || Number.isNaN(index)) return;
if (field === "count") {
state.goals[index].count = THREE.MathUtils.clamp(
Math.round(Number(event.target.value) || 1),
1,
20
);
} else if (field === "target") {
state.goals[index].target = Number(event.target.value);
} else if (field === "name") {
state.goals[index].name = event.target.value.trim() || `Goal ${index + 1}`;
}
rebuildAll();
});
$("goalList").addEventListener("click", event => {
const button = event.target.closest("[data-remove]");
if (!button) return;
state.goals.splice(Number(button.dataset.remove), 1);
rebuildAll();
});
$("addGoal").addEventListener("click", () => {
if (state.goals.length >= 6) return;
const total = state.rows * state.cols;
state.goals.push({
name: `New objective ${state.goals.length + 1}`,
target: state.seed % total,
count: 3
});
rebuildAll();
});
$("policyList").addEventListener("click", event => {
const button = event.target.closest("[data-policy]");
if (!button) return;
state.policy = button.dataset.policy;
activePlan = allPlans[state.policy];
renderActive();
renderAnalytics();
});
$("comparisonBody").addEventListener("click", event => {
const row = event.target.closest("[data-policy]");
if (!row) return;
state.policy = row.dataset.policy;
activePlan = allPlans[state.policy];
renderActive();
renderAnalytics();
});
$("resetScenario").addEventListener("click", () => {
Object.assign(state, structuredClone(defaultState));
$("presetSelect").value = state.preset;
$("rowsSelect").value = state.rows;
$("colsSelect").value = state.cols;
$("aisleRange").value = state.aisle;
$("aisleValue").textContent = `${state.aisle.toFixed(1)} m`;
$("depthSelect").value = state.stallDepth;
rebuildAll({ fit: true });
});
$("configToggle").addEventListener("click", () => {
document.body.classList.toggle("show-config");
document.body.classList.remove("show-insights");
});
$("metricsToggle").addEventListener("click", () => {
document.body.classList.toggle("show-insights");
document.body.classList.remove("show-config");
});
document.querySelectorAll("[data-view]").forEach(button => {
button.addEventListener("click", () => {
const view = button.dataset.view;
if (view === "iso") {
cameraState.theta = 0.72;
cameraState.phi = 0.78;
cameraState.target.set(0, 0, 0);
} else if (view === "top") {
cameraState.theta = 0;
cameraState.phi = 0.12;
cameraState.target.set(0, 0, 0);
} else {
fitCamera();
}
updateCamera();
});
});
// Direct orbit, pan and zoom controls; no Three.js addons are used.
let pointerDown = false;
let pointerMoved = false;
let pointerButton = 0;
let lastX = 0;
let lastY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
pointerMoved = false;
pointerButton = event.button;
lastX = event.clientX;
lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (pointerDown) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 2) pointerMoved = true;
const pan = pointerButton === 2 || pointerButton === 1 || event.shiftKey;
if (pan) {
const scale = cameraState.radius / $("canvasHost").clientHeight;
cameraState.target.x -= dx * scale;
cameraState.target.z += dy * scale;
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.12,
1.35
);
}
$("tooltip").classList.remove("visible");
} else {
updateTooltip(event);
}
});
renderer.domElement.addEventListener("pointerup", event => {
pointerDown = false;
renderer.domElement.releasePointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) $("tooltip").classList.remove("visible");
});
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
8,
90
);
updateCamera();
}, { passive: false });
function updateTooltip(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
const hit = intersections.find(item => item.object.userData.hoverType);
if (!hit) {
$("tooltip").classList.remove("visible");
return;
}
const data = hit.object.userData;
$("tooltip").innerHTML = `<strong>${escapeAttribute(data.title)}</strong><span>${escapeAttribute(data.detail)}</span>`;
$("tooltip").style.left = `${Math.min(event.clientX + 13, window.innerWidth - 250)}px`;
$("tooltip").style.top = `${Math.min(event.clientY + 13, window.innerHeight - 90)}px`;
$("tooltip").classList.add("visible");
}
new ResizeObserver(resize).observe($("canvasHost"));
// Initialize.
$("aisleValue").textContent = `${state.aisle.toFixed(1)} m`;
rebuildAll({ fit: true });
resize();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const time = clock.elapsedTime;
for (const visitor of visitors) {
if (visitor.dwell > 0) {
visitor.dwell -= dt;
} else {
visitor.distance += visitor.speed * visitor.direction * dt;
if (visitor.direction > 0 && visitor.distance >= visitor.path.length) {
visitor.distance = visitor.path.length;
visitor.direction = -1;
visitor.dwell = 1.1;
} else if (visitor.direction < 0 && visitor.distance <= 0) {
visitor.distance = 0;
visitor.direction = 1;
visitor.dwell = 0.35;
}
}
const point = pointAlongPath(visitor.path, visitor.distance);
const length = Math.hypot(point.dx, point.dz) || 1;
const px = -point.dz / length;
const pz = point.dx / length;
visitor.group.position.set(
point.x + px * visitor.offset,
Math.sin(time * 7 + visitor.phase) * 0.012,
point.z + pz * visitor.offset
);
visitor.group.rotation.y = Math.atan2(point.dx, point.dz);
}
for (const marker of markerPulses) {
const scale = 1 + Math.sin(time * 3.1 + marker.phase) * 0.08;
marker.ring.scale.setScalar(scale);
}
goalGroup.children.forEach((group, index) => {
group.position.y = Math.sin(time * 2 + index) * 0.025;
});
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```