Prompt specification
Build or customize the Three.js 3D scene "Bakery Absence and Cross-Training" 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: Bakery Absence and Cross-Training
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/bakery-absence-and-cross-training-x3148
Scene Description Prompt:
Bakery absence and cross-training. Create a small bakery with mixing, shaping, and baking stations. Remove one specialist, then enable a trained substitute and compare queue recovery under identical order arrivals. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (bakery-absence-and-cross-training-x3148):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crumb Coverage Lab — Bakery Cross-Training</title>
<style>
:root {
--bg: #eee8dd;
--panel: #fffdf8;
--ink: #26312d;
--muted: #747c76;
--line: #ddd5c7;
--teal: #248b7f;
--red: #df6256;
--purple: #6d5bd0;
--orange: #d9822b;
--soft: #f5f0e7;
--shadow: 0 10px 30px rgba(65, 54, 38, 0.08);
}
* { box-sizing: border-box; }
body {
margin: 0;
color: var(--ink);
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
overflow: hidden;
}
button, select, input { font: inherit; }
button { cursor: pointer; }
.app {
height: 100vh;
display: grid;
grid-template-rows: 66px minmax(0, 1fr);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 22px;
background: rgba(255, 253, 248, 0.94);
border-bottom: 1px solid var(--line);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
width: 36px;
height: 36px;
border-radius: 12px 12px 15px 15px;
background: var(--orange);
position: relative;
box-shadow: inset 0 -5px rgba(104, 55, 18, 0.12);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
width: 4px;
height: 11px;
top: 7px;
background: #fff3db;
border-radius: 4px;
}
.brand-mark::before { left: 11px; transform: rotate(-18deg); }
.brand-mark::after { right: 10px; transform: rotate(18deg); }
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: -0.02em;
}
.brand p {
margin: 2px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.header-meta {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 12px;
}
.seed-pill {
padding: 7px 10px;
background: var(--soft);
border: 1px solid var(--line);
border-radius: 99px;
font-variant-numeric: tabular-nums;
}
.layout {
min-height: 0;
display: grid;
grid-template-columns: 276px minmax(500px, 1fr) 292px;
gap: 12px;
padding: 12px;
}
.panel {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 16px;
box-shadow: var(--shadow);
}
.sidebar,
.insights {
overflow: auto;
scrollbar-width: thin;
}
.sidebar { padding: 18px; }
.insights { padding: 18px; }
.eyebrow {
margin: 0 0 6px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h2 {
margin: 0;
font-size: 20px;
letter-spacing: -0.035em;
}
.intro {
margin: 9px 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.section {
padding: 15px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type { border-top: 0; }
.field-label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
select {
width: 100%;
padding: 9px 10px;
color: var(--ink);
background: var(--soft);
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
}
.scenario-tabs {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
margin-top: 8px;
}
.scenario-tabs button {
padding: 9px 4px;
color: var(--muted);
background: transparent;
border: 1px solid var(--line);
border-radius: 9px;
font-size: 10px;
font-weight: 750;
}
.scenario-tabs button.active {
color: #fff;
background: var(--ink);
border-color: var(--ink);
}
.button-row {
display: grid;
gap: 8px;
margin-top: 10px;
}
.button-row.two {
grid-template-columns: 1fr 1fr;
}
.btn {
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--ink);
background: var(--soft);
font-weight: 750;
font-size: 12px;
transition: transform 0.12s ease, opacity 0.12s ease, background 0.12s ease;
}
.btn:hover:not(:disabled) { transform: translateY(-1px); }
.btn:active:not(:disabled) { transform: translateY(0); }
.btn:disabled { opacity: 0.42; cursor: not-allowed; }
.btn.primary {
color: white;
background: var(--orange);
border-color: var(--orange);
}
.btn.danger {
color: #a43c33;
background: #fff0ed;
border-color: #efc2bc;
}
.btn.substitute {
color: #5142ad;
background: #f0edff;
border-color: #d8d0ff;
}
.schedule {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 11px;
}
.schedule-card {
padding: 10px;
background: var(--soft);
border: 1px solid var(--line);
border-radius: 10px;
}
.schedule-card span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.schedule-card strong {
display: block;
margin-top: 4px;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.status-box {
margin-top: 12px;
padding: 12px;
color: #5c5143;
background: #fff5e4;
border: 1px solid #f0d8ad;
border-radius: 11px;
font-size: 11px;
line-height: 1.45;
}
.status-box strong {
display: block;
margin-bottom: 3px;
color: #8b561e;
}
.note {
margin: 7px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.workspace {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: minmax(350px, 1fr) 285px;
gap: 12px;
}
.scene-panel {
position: relative;
min-height: 0;
overflow: hidden;
background: #e9e0d2;
border: 1px solid var(--line);
border-radius: 16px;
box-shadow: var(--shadow);
}
#scene {
position: absolute;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-top {
position: absolute;
top: 14px;
left: 14px;
right: 14px;
display: flex;
align-items: flex-start;
justify-content: space-between;
pointer-events: none;
gap: 12px;
}
.scene-title {
padding: 9px 11px;
background: rgba(255, 253, 248, 0.89);
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 10px;
box-shadow: 0 6px 18px rgba(61, 49, 35, 0.08);
backdrop-filter: blur(8px);
}
.scene-title b {
display: block;
font-size: 12px;
}
.scene-title span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.scene-chip {
padding: 9px 11px;
color: #fff;
background: rgba(38, 49, 45, 0.88);
border-radius: 10px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.04em;
backdrop-filter: blur(8px);
}
.scene-bottom {
position: absolute;
left: 14px;
right: 14px;
bottom: 13px;
display: flex;
align-items: flex-end;
justify-content: space-between;
pointer-events: none;
}
.camera-hint {
padding: 7px 9px;
color: #5e625e;
background: rgba(255, 253, 248, 0.78);
border-radius: 8px;
font-size: 9px;
backdrop-filter: blur(6px);
}
#cameraReset {
pointer-events: auto;
padding: 7px 10px;
color: var(--ink);
background: rgba(255, 253, 248, 0.9);
border: 1px solid rgba(210, 201, 187, 0.8);
border-radius: 8px;
font-size: 10px;
font-weight: 700;
}
.timeline-panel {
position: absolute;
left: 14px;
right: 14px;
bottom: 47px;
padding: 10px 12px;
background: rgba(255, 253, 248, 0.9);
border: 1px solid rgba(255, 255, 255, 0.78);
border-radius: 11px;
box-shadow: 0 8px 24px rgba(61, 49, 35, 0.08);
backdrop-filter: blur(10px);
}
.timeline-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 5px;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
#clock {
color: var(--orange);
font-variant-numeric: tabular-nums;
}
.timeline-wrap {
position: relative;
height: 20px;
}
#timeline {
position: absolute;
inset: 4px 0 auto;
width: 100%;
height: 5px;
margin: 0;
accent-color: var(--orange);
cursor: pointer;
}
.event-marker {
position: absolute;
top: 0;
width: 2px;
height: 17px;
transform: translateX(-1px);
pointer-events: none;
}
.event-marker.absence { background: var(--red); }
.event-marker.cover { background: var(--purple); }
.chart-panel {
min-height: 0;
padding: 14px 16px 10px;
overflow: hidden;
}
.chart-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.chart-head h3 {
margin: 0;
font-size: 14px;
letter-spacing: -0.02em;
}
.chart-head p {
margin: 3px 0 0;
color: var(--muted);
font-size: 10px;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 11px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 14px;
height: 3px;
display: inline-block;
border-radius: 3px;
}
#chart {
width: 100%;
height: calc(100% - 34px);
display: block;
overflow: visible;
}
.chart-wrap {
position: relative;
height: calc(100% - 36px);
min-height: 190px;
}
.chart-tip {
position: absolute;
z-index: 3;
min-width: 140px;
padding: 8px 10px;
color: white;
background: rgba(38, 49, 45, 0.94);
border-radius: 8px;
pointer-events: none;
font-size: 9px;
line-height: 1.55;
box-shadow: 0 7px 20px rgba(0, 0, 0, 0.16);
opacity: 0;
transition: opacity 0.08s;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
.metric {
min-height: 94px;
padding: 12px;
background: var(--soft);
border: 1px solid var(--line);
border-radius: 12px;
}
.metric.red { background: #fff2ef; border-color: #f0c9c3; }
.metric.purple { background: #f2efff; border-color: #dcd5ff; }
.metric.teal { background: #eaf7f3; border-color: #c8e6dd; }
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin: 7px 0 2px;
font-size: 25px;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric small {
color: var(--muted);
font-size: 9px;
line-height: 1.35;
}
.insight {
margin-top: 13px;
padding: 13px;
background: #f7f3eb;
border: 1px solid var(--line);
border-radius: 12px;
}
.insight b {
display: block;
margin-bottom: 5px;
font-size: 11px;
}
.insight p {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.arrival-summary {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 13px;
padding-top: 13px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
}
.arrival-summary b {
color: var(--ink);
font-variant-numeric: tabular-nums;
}
.loading {
position: absolute;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
color: var(--muted);
background: #e9e0d2;
font-size: 12px;
font-weight: 700;
}
@media (max-width: 1120px) {
body { overflow: auto; }
.app { height: auto; min-height: 100vh; }
.layout {
grid-template-columns: 250px minmax(500px, 1fr);
}
.insights {
grid-column: 1 / -1;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.insights > .eyebrow,
.insights > h2,
.insights > .metric-grid,
.insights > .insight,
.insights > .arrival-summary { margin: 0; }
.insights > .metric-grid { grid-column: 1 / -1; grid-template-columns: repeat(4, 1fr); }
.insights > .insight { grid-column: 1 / 3; }
.insights > .arrival-summary { grid-column: 3 / 5; }
}
@media (max-width: 790px) {
header { padding: 0 14px; }
.header-meta > span:first-child { display: none; }
.layout {
display: flex;
flex-direction: column;
padding: 8px;
}
.workspace {
order: -1;
grid-template-rows: 470px 300px;
}
.sidebar, .insights { overflow: visible; }
.insights {
display: block;
}
.insights > .metric-grid { grid-template-columns: 1fr 1fr; }
.insights > .insight,
.insights > .arrival-summary { margin-top: 10px; }
.chart-head { display: block; }
.legend { justify-content: flex-start; margin-top: 7px; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>Crumb Coverage Lab</h1>
<p>Bakery workforce simulation</p>
</div>
</div>
<div class="header-meta">
<span>Deterministic workload</span>
<div class="seed-pill">SEED 042 · <span id="headerOrderCount">—</span> ORDERS</div>
</div>
</header>
<main class="layout">
<aside class="panel sidebar">
<p class="eyebrow">Experiment 01</p>
<h2>Absence & cross-training</h2>
<p class="intro">
Compare a fully staffed bakery with the same bakery after one specialist leaves.
A trained substitute can then cover the station.
</p>
<section class="section">
<label class="field-label" for="stationSelect">Specialist to remove</label>
<select id="stationSelect">
<option value="0">Mixing specialist</option>
<option value="1" selected>Shaping specialist</option>
<option value="2">Baking specialist</option>
</select>
<label class="field-label" style="margin-top:13px">3D scenario view</label>
<div class="scenario-tabs" id="scenarioTabs">
<button data-scenario="baseline">Baseline</button>
<button data-scenario="nocover">No cover</button>
<button data-scenario="cross" class="active">Cross-trained</button>
</div>
</section>
<section class="section">
<div class="button-row two">
<button id="removeBtn" class="btn danger">Remove specialist</button>
<button id="coverBtn" class="btn substitute">Enable substitute</button>
</div>
<div class="schedule">
<div class="schedule-card">
<span>Absence begins</span>
<strong id="absenceTime">18.0 s</strong>
</div>
<div class="schedule-card">
<span>Cover begins</span>
<strong id="coverTime">34.0 s</strong>
</div>
</div>
<div class="button-row">
<button id="runBtn" class="btn primary">▶ Run comparison</button>
<div class="button-row two">
<button id="resetBtn" class="btn">Reset</button>
<select id="speedSelect" aria-label="Playback speed">
<option value="1">1× speed</option>
<option value="2">2× speed</option>
<option value="4" selected>4× speed</option>
<option value="8">8× speed</option>
</select>
</div>
</div>
<div class="status-box" id="statusBox">
<strong id="statusTitle">Full coverage</strong>
<span id="statusText">All three specialists are on station.</span>
</div>
<p class="note">
The scripted run removes the selected specialist at 18 seconds and enables the
substitute at 34 seconds. Manual intervention buttons override those times.
</p>
</section>
<section class="section">
<p class="eyebrow">Method</p>
<p class="note">
All three scenarios consume the same seeded arrival schedule. Queue load includes
waiting orders plus an order currently held at the station.
</p>
</section>
</aside>
<section class="workspace">
<div class="scene-panel" id="scenePanel">
<div id="scene"></div>
<div class="scene-top">
<div class="scene-title">
<b>Small Batch Bakery</b>
<span>Mixing → Shaping → Baking</span>
</div>
<div class="scene-chip" id="sceneChip">CROSS-TRAINED SCENARIO</div>
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<span>Shift timeline</span>
<span id="clock">00.0 / 90.0 s</span>
</div>
<div class="timeline-wrap">
<input id="timeline" type="range" min="0" max="90" step="0.1" value="0" />
<div id="absenceMarker" class="event-marker absence" title="Specialist removed"></div>
<div id="coverMarker" class="event-marker cover" title="Substitute enabled"></div>
</div>
</div>
<div class="scene-bottom">
<div class="camera-hint">Drag to orbit · Shift-drag to pan · Wheel to zoom</div>
<button id="cameraReset">Reset camera</button>
</div>
<div class="loading" id="loading">Preparing the bakery…</div>
</div>
<div class="panel chart-panel">
<div class="chart-head">
<div>
<h3>Queue recovery under identical arrivals</h3>
<p id="chartSubtitle">Selected station: shaping</p>
</div>
<div class="legend">
<span><i style="background:#248b7f"></i>Full staffing</span>
<span><i style="background:#df6256"></i>No coverage</span>
<span><i style="background:#6d5bd0"></i>Cross-trained</span>
</div>
</div>
<div class="chart-wrap" id="chartWrap">
<svg id="chart" viewBox="0 0 720 220" preserveAspectRatio="none"></svg>
<div class="chart-tip" id="chartTip"></div>
</div>
</div>
</section>
<aside class="panel insights">
<p class="eyebrow">Recovery readout</p>
<h2>Coverage outcomes</h2>
<div class="metric-grid">
<div class="metric red">
<span>No-cover peak</span>
<strong id="peakNoCover">—</strong>
<small>orders in station load</small>
</div>
<div class="metric purple">
<span>Cross-trained peak</span>
<strong id="peakCross">—</strong>
<small>orders in station load</small>
</div>
<div class="metric teal">
<span>Recovery to parity</span>
<strong id="recoveryValue">—</strong>
<small>seconds after substitute starts</small>
</div>
<div class="metric">
<span>Orders completed</span>
<strong id="completedValue">—</strong>
<small>cross-trained / full staffing</small>
</div>
</div>
<div class="insight">
<b id="insightTitle">Cross-training limits the backlog</b>
<p id="insightText">
Run the comparison to calculate avoided queue time and recovery time.
</p>
</div>
<div class="arrival-summary">
<span>Shared arrival schedule</span>
<b id="arrivalSummary">—</b>
</div>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------------
// Configuration and deterministic workload
// ---------------------------------------------------------------------------
const CONFIG = {
duration: 90,
seed: 42,
dt: 0.1,
defaultRemoval: 18,
defaultCover: 34,
substituteSpeed: 0.92,
stationNames: ["Mixing", "Shaping", "Baking"]
};
const state = {
time: 0,
running: false,
speed: 4,
target: 1,
scenario: "cross",
removalAt: CONFIG.defaultRemoval,
coverAt: CONFIG.defaultCover
};
const stationDefs = [
{ name: "Mixing", x: -4.45, color: 0x2f9b8f, orderColor: 0xe4b866 },
{ name: "Shaping", x: 0, color: 0xd9822b, orderColor: 0xf0c77c },
{ name: "Baking", x: 4.45, color: 0x557aad, orderColor: 0xc98b53 }
];
function mulberry32(seed) {
return function () {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
function generateOrders(seed) {
const random = mulberry32(seed);
const orders = [];
let time = 0.15;
while (time < CONFIG.duration) {
time += -Math.log(1 - random()) * 2.15;
if (time >= CONFIG.duration) break;
orders.push({
at: time,
serviceTimes: [
2.4 + random() * 1.2,
1.8 + random() * 1.0,
3.2 + random() * 1.4
]
});
}
return orders;
}
const orders = generateOrders(CONFIG.seed);
function cloneOrders() {
return orders.map(order => ({
at: order.at,
serviceTimes: [...order.serviceTimes],
waited: 0
}));
}
// ---------------------------------------------------------------------------
// Discrete-event style workload simulation
// ---------------------------------------------------------------------------
function simulateScenario(kind) {
const localOrders = cloneOrders();
const stations = stationDefs.map(() => ({
queue: [],
active: null,
remaining: 0,
waits: []
}));
const snapshots = [];
let arrivalIndex = 0;
let completed = 0;
const totalTicks = Math.round(CONFIG.duration / CONFIG.dt);
for (let tick = 0; tick <= totalTicks; tick++) {
const time = tick * CONFIG.dt;
while (
arrivalIndex < localOrders.length &&
localOrders[arrivalIndex].at <= time + 1e-8
) {
const order = localOrders[arrivalIndex++];
order.readyAt = order.at;
stations[0].queue.push(order);
}
// Work downstream first so completed orders can enter the next queue.
for (let index = 2; index >= 0; index--) {
const station = stations[index];
let available = true;
let speed = 1;
if (index === state.target) {
if (kind === "nocover") {
available = time < state.removalAt;
} else if (kind === "cross") {
available = time < state.removalAt || time >= state.coverAt;
if (time >= state.coverAt) speed = CONFIG.substituteSpeed;
}
}
if (!station.active && available && station.queue.length) {
const order = station.queue.shift();
const wait = Math.max(0, time - order.readyAt);
order.waited += wait;
station.waits.push(wait);
station.active = order;
station.remaining = order.serviceTimes[index];
}
if (station.active && available) {
station.remaining -= CONFIG.dt * speed;
if (station.remaining <= 0) {
const order = station.active;
station.active = null;
if (index < 2) {
order.readyAt = time;
stations[index + 1].queue.push(order);
} else {
completed++;
}
}
}
}
if (tick % 5 === 0) {
snapshots.push({
t: time,
completed,
loads: stations.map(s => s.queue.length + (s.active ? 1 : 0)),
queueCounts: stations.map(s => s.queue.length),
active: stations.map(s => !!s.active)
});
}
}
return {
kind,
snapshots,
completed,
stationWaits: stations.map(s => s.waits)
};
}
function loadArea(result, stationIndex, fromTime = 0) {
let area = 0;
for (const snapshot of result.snapshots) {
if (snapshot.t >= fromTime) {
area += snapshot.loads[stationIndex] * 0.5;
}
}
return area;
}
function peakLoad(result, stationIndex) {
return Math.max(...result.snapshots.map(s => s.loads[stationIndex]));
}
function findRecovery(baseline, cross, stationIndex) {
if (!Number.isFinite(state.coverAt)) return null;
for (let i = 0; i < cross.snapshots.length; i++) {
const snapshot = cross.snapshots[i];
if (snapshot.t < state.coverAt) continue;
const window = cross.snapshots.slice(i, i + 8);
const baselineWindow = baseline.snapshots.slice(i, i + 8);
const recovered = window.length === 8 &&
window.every((sample, j) =>
sample.loads[stationIndex] <= baselineWindow[j].loads[stationIndex] + 1
);
if (recovered) return snapshot.t - state.coverAt;
}
return null;
}
let results = {};
function recomputeResults() {
results.baseline = simulateScenario("baseline");
results.nocover = simulateScenario("nocover");
results.cross = simulateScenario("cross");
renderChart();
updateMetrics();
updateTimelineMarkers();
}
// ---------------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------------
const sceneContainer = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e0d2);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
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;
sceneContainer.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xfff8e8, 0x9e8d73, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d8, 3.2);
sun.position.set(-6, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
scene.add(sun);
const rim = new THREE.DirectionalLight(0xbad7ff, 0.8);
rim.position.set(8, 7, -8);
scene.add(rim);
const material = (color, roughness = 0.82, metalness = 0) =>
new THREE.MeshStandardMaterial({ color, roughness, metalness });
const materials = {
floor: material(0xd9c7aa),
wall: material(0xf0e6d5),
trim: material(0x9f7653),
counter: material(0xb9805b),
top: material(0xf2dfbd),
dark: material(0x3a403d),
steel: material(0x8e9894, 0.55, 0.25),
bowl: material(0x557d80, 0.6, 0.08),
dough: material(0xf0d19a),
bread: material(0xc98746),
paper: material(0xf6e6bf),
purple: material(0x6d5bd0),
red: material(0xdf6256)
};
function box(parent, w, h, d, mat, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function cylinder(parent, top, bottom, height, segments, mat, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(top, bottom, height, segments),
mat
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function sphere(parent, radius, mat, x = 0, y = 0, z = 0, detail = 0) {
const geometry = detail
? new THREE.SphereGeometry(radius, 12, 8)
: new THREE.DodecahedronGeometry(radius, 0);
const mesh = new THREE.Mesh(geometry, mat);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function createTextSprite(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
}));
sprite.userData.canvas = canvas;
sprite.userData.ctx = ctx;
sprite.userData.texture = texture;
sprite.userData.bg = options.bg || "#26312d";
sprite.userData.fg = options.fg || "#ffffff";
sprite.renderOrder = 20;
updateTextSprite(sprite, text);
return sprite;
}
function updateTextSprite(sprite, text, bg = sprite.userData.bg, fg = sprite.userData.fg) {
const canvas = sprite.userData.canvas;
const ctx = sprite.userData.ctx;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = bg;
ctx.beginPath();
ctx.roundRect(4, 8, 504, 108, 24);
ctx.fill();
ctx.fillStyle = fg;
ctx.font = "800 42px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
sprite.userData.texture.needsUpdate = true;
}
// Room
box(scene, 15.3, 0.28, 9.0, materials.floor, 0, -0.14, 0);
box(scene, 15.3, 3.7, 0.22, materials.wall, 0, 1.85, -4.45);
box(scene, 0.22, 3.7, 8.8, materials.wall, -7.55, 1.85, -0.1);
box(scene, 15.4, 0.18, 0.22, materials.trim, 0, 3.55, -4.45);
box(scene, 0.22, 0.18, 8.9, materials.trim, -7.55, 3.55, -0.1);
const tileGrid = new THREE.GridHelper(15, 15, 0xb8a58c, 0xc9b79c);
tileGrid.position.y = 0.012;
tileGrid.scale.z = 0.59;
tileGrid.material.transparent = true;
tileGrid.material.opacity = 0.38;
scene.add(tileGrid);
// Back-wall bakery sign and shelving
const sign = createTextSprite("CRUMB • SMALL BATCH", {
bg: "#ffffff",
fg: "#5f4937"
});
sign.scale.set(3.9, 0.98, 1);
sign.position.set(0, 3.03, -4.28);
scene.add(sign);
box(scene, 5.6, 0.16, 0.75, materials.trim, 0, 1.72, -4.08);
for (let i = 0; i < 9; i++) {
const loaf = sphere(
scene,
0.22,
i % 2 ? materials.bread : materials.dough,
-2.15 + i * 0.54,
1.98,
-4.03
);
loaf.scale.set(1.35, 0.72, 0.9);
}
// Decorative flour sacks
const sackMat = material(0xc8b391);
const sack1 = box(scene, 0.8, 1.0, 0.7, sackMat, -6.6, 0.5, -3.5);
sack1.rotation.y = 0.15;
const sack2 = box(scene, 0.68, 0.82, 0.62, sackMat, -5.75, 0.41, -3.65);
sack2.rotation.y = -0.1;
// Station data
const stationVisuals = [];
function makeOrderMarker(color) {
const group = new THREE.Group();
box(group, 0.32, 0.36, 0.24, material(color), 0, 0.18, 0);
const top = new THREE.Mesh(
new THREE.ConeGeometry(0.23, 0.2, 4),
material(0xf4d694)
);
top.position.y = 0.47;
top.rotation.y = Math.PI / 4;
top.castShadow = true;
group.add(top);
return group;
}
function makeWorker(apronColor, skinColor = 0xd5a078) {
const group = new THREE.Group();
const apron = material(apronColor);
const skin = material(skinColor);
const pants = material(0x4b5350);
box(group, 0.19, 0.58, 0.22, pants, -0.17, 0.3, 0);
box(group, 0.19, 0.58, 0.22, pants, 0.17, 0.3, 0);
cylinder(group, 0.32, 0.38, 0.72, 8, apron, 0, 0.92, 0);
box(group, 0.43, 0.52, 0.08, material(0xf5ead6), 0, 0.87, 0.31);
sphere(group, 0.29, skin, 0, 1.55, 0);
cylinder(group, 0.36, 0.34, 0.12, 10, material(0xfff8e9), 0, 1.79, 0);
cylinder(group, 0.27, 0.31, 0.34, 10, material(0xfff8e9), 0, 1.97, 0);
const arms = [];
for (const side of [-1, 1]) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.39, 1.19, 0);
const arm = box(pivot, 0.17, 0.58, 0.18, apron, 0, -0.23, 0);
arm.rotation.z = side * 0.1;
group.add(pivot);
arms.push(pivot);
}
group.userData.arms = arms;
return group;
}
function buildMixStation(station) {
const group = new THREE.Group();
box(group, 3.25, 1.25, 2.05, materials.counter, 0, 0.63, -0.25);
box(group, 3.45, 0.18, 2.2, materials.top, 0, 1.34, -0.25);
// Mixer
box(group, 0.64, 0.16, 0.58, materials.steel, -0.85, 1.49, -0.35);
box(group, 0.20, 0.85, 0.24, materials.steel, -1.04, 1.91, -0.48);
box(group, 0.95, 0.16, 0.25, materials.steel, -0.65, 2.25, -0.34);
cylinder(group, 0.50, 0.36, 0.42, 12, materials.bowl, -0.55, 1.72, -0.20);
const dough = sphere(group, 0.30, materials.dough, -0.55, 1.86, -0.20);
// Ingredient bins
for (let i = 0; i < 3; i++) {
cylinder(group, 0.18, 0.18, 0.28, 8, material([0xe8c06b, 0xf4eee2, 0xc88955][i]),
0.55 + i * 0.45, 1.58, -0.55);
}
station.activeTask = dough;
station.activeTask.scale.set(1, 0.7, 1);
return group;
}
function buildShapeStation(station) {
const group = new THREE.Group();
box(group, 3.25, 1.25, 2.05, materials.counter, 0, 0.63, -0.25);
box(group, 3.45, 0.18, 2.2, materials.top, 0, 1.34, -0.25);
box(group, 1.65, 0.10, 1.08, material(0xd9b782), 0, 1.49, -0.22);
const dough = sphere(group, 0.36, materials.dough, -0.15, 1.68, -0.2);
dough.scale.set(1.35, 0.55, 0.9);
const roller = cylinder(group, 0.13, 0.13, 1.15, 10, materials.trim, 0.48, 1.66, -0.15);
roller.rotation.z = Math.PI / 2;
for (let i = 0; i < 3; i++) {
sphere(group, 0.18, materials.bread, 0.72 + i * 0.37, 1.67, 0.28);
}
station.activeTask = dough;
return group;
}
function buildBakeStation(station) {
const group = new THREE.Group();
box(group, 3.25, 1.25, 2.05, materials.counter, 0, 0.63, -0.25);
box(group, 3.45, 0.18, 2.2, materials.top, 0, 1.34, -0.25);
// Low-poly oven
box(group, 2.25, 1.75, 1.52, material(0x66706d), 0, 2.18, -0.42);
box(group, 1.55, 1.00, 0.12, materials.dark, 0, 1.99, 0.38);
const ovenGlow = new THREE.Mesh(
new THREE.PlaneGeometry(1.42, 0.87),
new THREE.MeshBasicMaterial({ color: 0xd77932 })
);
ovenGlow.position.set(0, 1.98, 0.455);
group.add(ovenGlow);
box(group, 1.72, 0.12, 0.18, materials.steel, 0, 1.42, 0.48);
for (let i = 0; i < 3; i++) {
cylinder(group, 0.10, 0.10, 0.16, 8, materials.steel,
-0.67 + i * 0.67, 2.95, 0.08);
}
const loaf = sphere(group, 0.42, materials.bread, 0, 1.95, 0.45);
loaf.scale.set(1.35, 0.7, 0.65);
station.activeTask = loaf;
return group;
}
stationDefs.forEach((station, index) => {
const group = new THREE.Group();
group.position.set(station.x, 0, 0);
scene.add(group);
let stationGroup;
if (index === 0) stationGroup = buildMixStation(station);
else if (index === 1) stationGroup = buildShapeStation(station);
else stationGroup = buildBakeStation(station);
group.add(stationGroup);
const label = createTextSprite(station.name.toUpperCase(), {
bg: "#fffdf8",
fg: "#39433f"
});
label.scale.set(2.35, 0.59, 1);
label.position.set(station.x, 3.38, -1.25);
scene.add(label);
const badge = createTextSprite("0 WAITING", {
bg: "#ffffff",
fg: "#6c766f"
});
badge.scale.set(1.55, 0.39, 1);
badge.position.set(station.x, 2.42, 1.25);
scene.add(badge);
const worker = makeWorker(station.color);
worker.position.set(station.x, 0, -2.05);
scene.add(worker);
const substitute = makeWorker(0x6d5bd0, 0xc98f67);
substitute.position.set(station.x, 0, -2.05);
substitute.visible = false;
scene.add(substitute);
const queue = [];
for (let i = 0; i < 15; i++) {
const marker = makeOrderMarker(station.orderColor);
marker.visible = false;
scene.add(marker);
queue.push(marker);
}
stationVisuals.push({
group,
stationGroup,
label,
badge,
worker,
substitute,
queue,
activeTask: station.activeTask,
lastBadge: -1
});
});
// Status markers above the affected station
const absentBadge = createTextSprite("SPECIALIST OUT", {
bg: "#df6256",
fg: "#ffffff"
});
absentBadge.scale.set(2.5, 0.63, 1);
absentBadge.position.set(stationDefs[state.target].x, 3.85, -0.5);
scene.add(absentBadge);
const substituteBadge = createTextSprite("TRAINED SUBSTITUTE", {
bg: "#6d5bd0",
fg: "#ffffff"
});
substituteBadge.scale.set(2.9, 0.73, 1);
substituteBadge.position.set(stationDefs[state.target].x, 3.85, -0.5);
scene.add(substituteBadge);
// ---------------------------------------------------------------------------
// Direct camera controls: orbit, pan, and zoom
// ---------------------------------------------------------------------------
const cameraState = {
yaw: 0.64,
pitch: 0.66,
radius: 17.7,
target: new THREE.Vector3(0, 0.82, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(yaw) * Math.cos(pitch),
target.y + radius * Math.sin(pitch),
target.z + radius * Math.cos(yaw) * Math.cos(pitch)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.yaw = 0.64;
cameraState.pitch = 0.66;
cameraState.radius = 17.7;
cameraState.target.set(0, 0.82, 0);
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
if (event.shiftKey || event.buttons === 2) {
cameraState.target.x -= dx * cameraState.radius * 0.0012;
cameraState.target.z += dy * cameraState.radius * 0.0012;
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -6, 6);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -4, 4);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.36,
1.20
);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
renderer.domElement.releasePointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
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),
10,
27
);
updateCamera();
}, { passive: false });
function resizeRenderer() {
const width = sceneContainer.clientWidth;
const height = sceneContainer.clientHeight;
camera.aspect = width / Math.max(1, height);
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
new ResizeObserver(resizeRenderer).observe(sceneContainer);
resizeRenderer();
resetCamera();
// ---------------------------------------------------------------------------
// Scene animation
// ---------------------------------------------------------------------------
function snapshotAt(result, time) {
const index = Math.min(
result.snapshots.length - 1,
Math.max(0, Math.round(time / 0.5))
);
return result.snapshots[index];
}
function isTargetAvailable(kind, time) {
if (kind === "baseline") return true;
if (kind === "nocover") return time < state.removalAt;
return time < state.removalAt || time >= state.coverAt;
}
function updateScene() {
const result = results[state.scenario] || results.cross;
const snapshot = snapshotAt(result, state.time);
const targetAvailable = isTargetAvailable(state.scenario, state.time);
stationVisuals.forEach((visual, index) => {
const load = snapshot.loads[index];
const busy = snapshot.active[index];
visual.queue.forEach((marker, itemIndex) => {
marker.visible = itemIndex < load;
if (!marker.visible) return;
const column = itemIndex % 5;
const row = Math.floor(itemIndex / 5);
const x = stationDefs[index].x + (column - 2) * 0.46;
const z = 1.67 + row * 0.48;
marker.position.set(x, 0.02, z);
marker.rotation.y = itemIndex * 0.31;
});
if (load !== visual.lastBadge) {
updateTextSprite(
visual.badge,
`${load} ${load === 1 ? "ORDER" : "ORDERS"}`,
"#ffffff",
load > 5 ? "#b54b41" : "#6c766f"
);
visual.lastBadge = load;
}
if (index === state.target) {
visual.worker.visible =
state.scenario === "baseline" || state.time < state.removalAt;
visual.substitute.visible =
state.scenario === "cross" &&
Number.isFinite(state.coverAt) &&
state.time >= state.coverAt;
} else {
visual.worker.visible = true;
visual.substitute.visible = false;
}
const activeWorker = visual.worker.visible
? visual.worker
: visual.substitute.visible
? visual.substitute
: null;
if (activeWorker) {
const working = busy && (
index !== state.target || targetAvailable
);
const motion = working
? Math.sin(state.time * 8.5 + index) * 0.43
: 0;
activeWorker.userData.arms[0].rotation.x = working ? -0.48 + motion : -0.08;
activeWorker.userData.arms[1].rotation.x = working ? -0.48 - motion : -0.08;
activeWorker.position.y = working
? Math.abs(Math.sin(state.time * 5 + index)) * 0.035
: 0;
}
if (visual.activeTask) {
visual.activeTask.visible = busy;
visual.activeTask.rotation.y = busy
? Math.sin(state.time * 3 + index) * 0.18
: 0;
}
});
const affectedX = stationDefs[state.target].x;
absentBadge.position.x = affectedX;
substituteBadge.position.x = affectedX;
const absent = state.scenario !== "baseline" &&
state.time >= state.removalAt &&
!(state.scenario === "cross" && state.time >= state.coverAt);
const substituteOn = state.scenario === "cross" &&
Number.isFinite(state.coverAt) &&
state.time >= state.coverAt;
absentBadge.visible = absent;
substituteBadge.visible = substituteOn;
}
// ---------------------------------------------------------------------------
// Chart
// ---------------------------------------------------------------------------
const chart = document.getElementById("chart");
const chartTip = document.getElementById("chartTip");
const CHART = {
width: 720,
height: 220,
left: 42,
right: 16,
top: 15,
bottom: 31
};
let chartData = null;
function chartX(time) {
return CHART.left +
(time / CONFIG.duration) * (CHART.width - CHART.left - CHART.right);
}
function chartY(value, maxY) {
return CHART.top +
(1 - value / maxY) * (CHART.height - CHART.top - CHART.bottom);
}
function pathFor(result, stationIndex, maxY) {
return result.snapshots.map((snapshot, index) => {
const command = index === 0 ? "M" : "L";
return `${command}${chartX(snapshot.t).toFixed(2)},${chartY(snapshot.loads[stationIndex], maxY).toFixed(2)}`;
}).join(" ");
}
function renderChart() {
const noCover = results.nocover;
const cross = results.cross;
const baseline = results.baseline;
let maxY = 1;
for (const result of [noCover, cross, baseline]) {
maxY = Math.max(maxY, ...result.snapshots.map(s => s.loads[state.target]));
}
maxY = Math.ceil(maxY / 5) * 5;
chartData = { maxY };
chart.setAttribute("viewBox", `0 0 ${CHART.width} ${CHART.height}`);
const fragments = [];
for (let i = 0; i <= 5; i++) {
const value = maxY * i / 5;
const y = chartY(value, maxY);
fragments.push(`
<line x1="${CHART.left}" y1="${y}" x2="${CHART.width - CHART.right}"
y2="${y}" stroke="#ded7cb" stroke-width="1"/>
<text x="${CHART.left - 9}" y="${y + 3}" text-anchor="end"
fill="#858b85" font-size="9">${value}</text>
`);
}
for (let i = 0; i <= 6; i++) {
const time = CONFIG.duration * i / 6;
const x = chartX(time);
fragments.push(`
<text x="${x}" y="${CHART.height - 10}" text-anchor="middle"
fill="#858b85" font-size="9">${Math.round(time)}s</text>
`);
}
// Identical arrival ticks
for (const order of orders) {
const x = chartX(order.at);
fragments.push(`
<line x1="${x}" y1="${CHART.height - CHART.bottom + 2}"
x2="${x}" y2="${CHART.height - CHART.bottom + 7}"
stroke="#aa9f8e" stroke-width="1" opacity="0.65"/>
`);
}
fragments.push(`
<line id="absenceLine" x1="${chartX(state.removalAt)}" y1="${CHART.top}"
x2="${chartX(state.removalAt)}" y2="${CHART.height - CHART.bottom}"
stroke="#df6256" stroke-width="1.2" stroke-dasharray="4 4" opacity="0.7"/>
`);
if (Number.isFinite(state.coverAt)) {
fragments.push(`
<line id="coverLine" x1="${chartX(state.coverAt)}" y1="${CHART.top}"
x2="${chartX(state.coverAt)}" y2="${CHART.height - CHART.bottom}"
stroke="#6d5bd0" stroke-width="1.2" stroke-dasharray="4 4" opacity="0.8"/>
`);
}
const series = [
{ result: baseline, color: "#248b7f", id: "baselinePath" },
{ result: noCover, color: "#df6256", id: "nocoverPath" },
{ result: cross, color: "#6d5bd0", id: "crossPath" }
];
for (const item of series) {
fragments.push(`
<path id="${item.id}" d="${pathFor(item.result, state.target, maxY)}"
fill="none" stroke="${item.color}" stroke-width="2.5"
stroke-linejoin="round" stroke-linecap="round"/>
`);
}
fragments.push(`
<line id="chartCursor" x1="${chartX(state.time)}" y1="${CHART.top}"
x2="${chartX(state.time)}" y2="${CHART.height - CHART.bottom}"
stroke="#26312d" stroke-width="1" opacity="0.65"/>
<circle id="chartDotBaseline" r="3.5" fill="#248b7f"
cx="${chartX(state.time)}" cy="${chartY(snapshotAt(baseline, state.time).loads[state.target], maxY)}"/>
<circle id="chartDotNoCover" r="3.5" fill="#df6256"
cx="${chartX(state.time)}" cy="${chartY(snapshotAt(noCover, state.time).loads[state.target], maxY)}"/>
<circle id="chartDotCross" r="3.5" fill="#6d5bd0"
cx="${chartX(state.time)}" cy="${chartY(snapshotAt(cross, state.time).loads[state.target], maxY)}"/>
`);
chart.innerHTML = fragments.join("");
document.getElementById("chartSubtitle").textContent =
`Selected station: ${stationDefs[state.target].name.toLowerCase()} · identical seeded arrivals`;
}
function updateChartCursor() {
if (!chartData) return;
const x = chartX(state.time);
const cursor = document.getElementById("chartCursor");
if (cursor) {
cursor.setAttribute("x1", x);
cursor.setAttribute("x2", x);
}
const definitions = [
["chartDotBaseline", results.baseline],
["chartDotNoCover", results.nocover],
["chartDotCross", results.cross]
];
for (const [id, result] of definitions) {
const dot = document.getElementById(id);
if (!dot) continue;
const snapshot = snapshotAt(result, state.time);
dot.setAttribute("cx", x);
dot.setAttribute("cy", chartY(snapshot.loads[state.target], chartData.maxY));
}
}
chart.addEventListener("pointermove", event => {
if (!chartData) return;
const rect = chart.getBoundingClientRect();
const viewX = (event.clientX - rect.left) / rect.width * CHART.width;
const time = THREE.MathUtils.clamp(
(viewX - CHART.left) / (CHART.width - CHART.left - CHART.right) * CONFIG.duration,
0,
CONFIG.duration
);
const baseline = snapshotAt(results.baseline, time).loads[state.target];
const noCover = snapshotAt(results.nocover, time).loads[state.target];
const cross = snapshotAt(results.cross, time).loads[state.target];
chartTip.innerHTML = `
<b>${time.toFixed(1)} seconds</b><br>
<span style="color:#8ed3c9">●</span> Baseline: ${baseline}<br>
<span style="color:#ffaaa2">●</span> No cover: ${noCover}<br>
<span style="color:#b8adff">●</span> Cross-trained: ${cross}
`;
chartTip.style.left =
`${Math.min(Math.max(event.clientX - rect.left + 12, 8), rect.width - 165)}px`;
chartTip.style.top = "12px";
chartTip.style.opacity = "1";
});
chart.addEventListener("pointerleave", () => {
chartTip.style.opacity = "0";
});
// ---------------------------------------------------------------------------
// Metrics and UI
// ---------------------------------------------------------------------------
function updateMetrics() {
const noCover = results.nocover;
const cross = results.cross;
const baseline = results.baseline;
const noCoverPeak = peakLoad(noCover, state.target);
const crossPeak = peakLoad(cross, state.target);
const recovery = findRecovery(baseline, cross, state.target);
const noCoverArea = loadArea(noCover, state.target, state.removalAt);
const crossArea = loadArea(cross, state.target, state.removalAt);
const avoidedQueueMinutes = Math.max(0, (noCoverArea - crossArea) * 0.5 / 60);
const reduction = noCoverArea > 0
? Math.max(0, (1 - crossArea / noCoverArea) * 100)
: 0;
document.getElementById("peakNoCover").textContent = noCoverPeak;
document.getElementById("peakCross").textContent = crossPeak;
document.getElementById("recoveryValue").textContent =
recovery === null ? "—" : `${recovery.toFixed(1)}s`;
document.getElementById("completedValue").textContent =
`${cross.completed} / ${baseline.completed}`;
document.getElementById("insightTitle").textContent =
recovery === null
? "Cross-training improves, but parity is not reached"
: "Cross-training restores queue parity";
document.getElementById("insightText").textContent =
`${crossArea < noCoverArea
? `The substitute avoids ${avoidedQueueMinutes.toFixed(1)} queue-minutes`
: "The substitute limits additional waiting"
} and reduces post-absence queue load by ${reduction.toFixed(0)}%. ` +
(recovery === null
? "Parity is not reached within this 90-second shift."
: `The station returns to baseline tolerance ${recovery.toFixed(1)} seconds after cover begins.`);
document.getElementById("arrivalSummary").textContent =
`${orders.length} orders · seed ${CONFIG.seed}`;
document.getElementById("headerOrderCount").textContent = orders.length;
}
function updateTimelineMarkers() {
document.getElementById("absenceMarker").style.left =
`${state.removalAt / CONFIG.duration * 100}%`;
const coverMarker = document.getElementById("coverMarker");
coverMarker.style.left = Number.isFinite(state.coverAt)
? `${state.coverAt / CONFIG.duration * 100}%`
: "-10px";
document.getElementById("absenceTime").textContent =
`${state.removalAt.toFixed(1)} s`;
document.getElementById("coverTime").textContent =
Number.isFinite(state.coverAt)
? `${state.coverAt.toFixed(1)} s`
: "Waiting";
}
function updateStatus() {
const title = document.getElementById("statusTitle");
const text = document.getElementById("statusText");
const chip = document.getElementById("sceneChip");
if (state.scenario === "baseline") {
title.textContent = "Full coverage baseline";
text.textContent = "All three specialists are on station throughout the shift.";
chip.textContent = "FULL-STAFFING BASELINE";
} else if (state.scenario === "nocover") {
if (state.time < state.removalAt) {
title.textContent = "Specialist on station";
text.textContent = "The selected station is fully staffed for now.";
} else {
title.textContent = "No coverage";
text.textContent = "The absent specialist leaves the station workload uncovered.";
}
chip.textContent = "NO-COVERAGE SCENARIO";
} else {
if (state.time < state.removalAt) {
title.textContent = "Full coverage";
text.textContent = "All three specialists are on station.";
} else if (state.time < state.coverAt) {
title.textContent = "Coverage gap";
text.textContent = "The specialist is absent and the trained substitute is en route.";
} else {
title.textContent = "Substitute active";
text.textContent = `The trained substitute is working at ${Math.round(CONFIG.substituteSpeed * 100)}% pace.`;
}
chip.textContent = "CROSS-TRAINED SCENARIO";
}
document.getElementById("clock").textContent =
`${state.time.toFixed(1).padStart(4, "0")} / ${CONFIG.duration.toFixed(1)} s`;
const timeline = document.getElementById("timeline");
if (document.activeElement !== timeline) timeline.value = state.time;
document.getElementById("removeBtn").disabled = state.time >= state.removalAt;
document.getElementById("coverBtn").disabled =
state.time < state.removalAt || state.time >= state.coverAt;
}
document.getElementById("stationSelect").addEventListener("change", event => {
state.target = Number(event.target.value);
absentBadge.position.x = stationDefs[state.target].x;
substituteBadge.position.x = stationDefs[state.target].x;
recomputeResults();
});
document.getElementById("scenarioTabs").addEventListener("click", event => {
const button = event.target.closest("button[data-scenario]");
if (!button) return;
state.scenario = button.dataset.scenario;
document.querySelectorAll("#scenarioTabs button").forEach(tab => {
tab.classList.toggle("active", tab === button);
});
});
document.getElementById("runBtn").addEventListener("click", () => {
if (state.time >= CONFIG.duration) state.time = 0;
state.running = !state.running;
document.getElementById("runBtn").textContent =
state.running ? "Ⅱ Pause" : "▶ Run comparison";
});
document.getElementById("resetBtn").addEventListener("click", () => {
state.time = 0;
state.running = false;
state.removalAt = CONFIG.defaultRemoval;
state.coverAt = CONFIG.defaultCover;
state.scenario = "cross";
document.getElementById("runBtn").textContent = "▶ Run comparison";
document.querySelectorAll("#scenarioTabs button").forEach(tab => {
tab.classList.toggle("active", tab.dataset.scenario === "cross");
});
recomputeResults();
});
document.getElementById("removeBtn").addEventListener("click", () => {
state.removalAt = Math.min(state.time, CONFIG.duration - 0.1);
state.coverAt = Infinity;
recomputeResults();
});
document.getElementById("coverBtn").addEventListener("click", () => {
state.coverAt = Math.min(state.time, CONFIG.duration - 0.1);
recomputeResults();
});
document.getElementById("speedSelect").addEventListener("change", event => {
state.speed = Number(event.target.value);
});
document.getElementById("timeline").addEventListener("input", event => {
state.time = Number(event.target.value);
});
document.getElementById("cameraReset").addEventListener("click", resetCamera);
// ---------------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------------
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state.running) {
state.time = Math.min(CONFIG.duration, state.time + delta * state.speed);
if (state.time >= CONFIG.duration) {
state.running = false;
document.getElementById("runBtn").textContent = "▶ Run again";
}
}
updateStatus();
updateScene();
updateChartCursor();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
recomputeResults();
document.getElementById("loading").style.display = "none";
requestAnimationFrame(animate);
</script>
</body>
</html>
```