Prompt specification
Build or customize the Three.js 3D scene "Bakery production timing 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: Bakery production timing sandbox
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/bakery-production-timing-sandbox-x0488
Scene Description Prompt:
Make a voxel Three.js scene in a self-contained HTML file using cdnjs: bakery production timing sandbox. Create a small shop with configurable fictional batch intervals and demand pulses; users observe stockouts and surplus trays through explicit counts rather than hidden economic assumptions.
Working Three.js Starter (bakery-production-timing-sandbox-x0488):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bake Timing Lab — Voxel Production Sandbox</title>
<style>
:root {
--ink: #382e28;
--muted: #776b61;
--paper: #faf6ee;
--paper-solid: #fffaf1;
--line: rgba(76, 61, 48, 0.15);
--terracotta: #b85f43;
--terracotta-dark: #88432f;
--sage: #6f866d;
--gold: #d99a48;
--red: #c54d3d;
--blue: #4f7f89;
--shadow: 0 18px 48px rgba(57, 43, 31, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #ded4c5;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 10;
top: 20px;
left: 20px;
right: 400px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.brand,
.camera-controls,
.status-card {
border: 1px solid rgba(255, 255, 255, 0.52);
background: rgba(255, 250, 241, 0.82);
box-shadow: 0 10px 28px rgba(61, 45, 32, 0.1);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
padding: 12px 16px 12px 12px;
border-radius: 17px;
}
.logo {
position: relative;
width: 42px;
height: 42px;
flex: 0 0 auto;
border-radius: 12px;
background: var(--terracotta);
box-shadow: inset 0 -7px 0 rgba(91, 40, 25, 0.12);
}
.logo::before,
.logo::after {
content: "";
position: absolute;
background: #f5d899;
border-radius: 3px;
}
.logo::before {
width: 9px;
height: 9px;
left: 10px;
top: 9px;
box-shadow: 14px 0 0 #f5d899;
}
.logo::after {
width: 23px;
height: 9px;
left: 10px;
bottom: 9px;
}
.eyebrow {
margin: 0 0 3px;
color: var(--terracotta-dark);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 18px;
line-height: 1.1;
letter-spacing: -0.025em;
}
.brand p:last-child {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
}
.top-right {
display: flex;
align-items: stretch;
gap: 8px;
}
.status-card {
display: flex;
align-items: center;
gap: 10px;
min-width: 132px;
padding: 0 14px;
border-radius: 14px;
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--sage);
box-shadow: 0 0 0 5px rgba(111, 134, 109, 0.13);
}
.status-dot.paused {
background: var(--gold);
box-shadow: 0 0 0 5px rgba(217, 154, 72, 0.13);
}
.status-copy {
display: flex;
flex-direction: column;
gap: 2px;
}
#runStatus {
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
}
#clock {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 14px;
font-weight: 700;
}
.camera-controls {
display: flex;
align-items: center;
padding: 5px;
border-radius: 14px;
pointer-events: auto;
}
.camera-controls button {
width: 33px;
height: 33px;
padding: 0;
border: 0;
border-radius: 9px;
background: transparent;
cursor: pointer;
font-size: 16px;
font-weight: 700;
}
.camera-controls button:hover {
background: rgba(184, 95, 67, 0.1);
}
.camera-controls .wide {
width: auto;
padding: 0 10px;
font-size: 11px;
}
#panel {
position: fixed;
z-index: 20;
top: 16px;
right: 16px;
bottom: 16px;
width: 366px;
overflow-y: auto;
padding: 19px;
border: 1px solid rgba(255, 255, 255, 0.62);
border-radius: 22px;
background: rgba(255, 250, 241, 0.95);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(104, 80, 60, 0.25) transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel-heading h2 {
margin: 0;
font-size: 20px;
letter-spacing: -0.035em;
}
.panel-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.pending-badge {
flex: 0 0 auto;
padding: 5px 8px;
border-radius: 999px;
color: var(--sage);
background: rgba(111, 134, 109, 0.12);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.pending-badge.pending {
color: #93611f;
background: rgba(217, 154, 72, 0.17);
}
.section {
padding: 15px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type {
border-top: 0;
padding-top: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 11px;
}
.section-title h3 {
margin: 0;
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.section-title span {
color: var(--muted);
font-size: 10px;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 12px;
}
.preset {
padding: 8px 5px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.45);
cursor: pointer;
font-size: 10px;
font-weight: 750;
}
.preset:hover {
border-color: rgba(184, 95, 67, 0.35);
background: rgba(184, 95, 67, 0.07);
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.field label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.number-wrap {
position: relative;
}
.number-wrap input {
width: 100%;
height: 39px;
padding: 0 38px 0 11px;
border: 1px solid var(--line);
border-radius: 10px;
outline: none;
color: var(--ink);
background: rgba(255, 255, 255, 0.7);
font-weight: 750;
font-variant-numeric: tabular-nums;
}
.number-wrap input:focus {
border-color: rgba(184, 95, 67, 0.55);
box-shadow: 0 0 0 3px rgba(184, 95, 67, 0.09);
}
.number-wrap output {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
color: #9a8b7d;
font-size: 9px;
pointer-events: none;
}
.rule-note {
margin: 12px 0 0;
padding: 10px 11px;
border-left: 3px solid var(--gold);
border-radius: 0 9px 9px 0;
color: #6b5d50;
background: rgba(217, 154, 72, 0.08);
font-size: 10px;
line-height: 1.48;
}
.rule-note strong {
color: var(--ink);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
margin-top: 12px;
}
.control-button {
min-height: 37px;
padding: 7px 8px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.65);
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.control-button:hover {
background: white;
}
.control-button.primary {
border-color: var(--terracotta);
color: white;
background: var(--terracotta);
}
.control-button.primary:hover {
background: var(--terracotta-dark);
}
.playback-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
color: var(--muted);
font-size: 10px;
}
select {
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 8px;
outline: none;
color: var(--ink);
background: white;
font-size: 10px;
}
.next-events {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.event-chip {
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.52);
}
.event-chip .label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.event-chip strong {
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.event-chip.production strong {
color: var(--terracotta);
}
.event-chip.demand strong {
color: var(--blue);
}
.chart-wrap {
position: relative;
width: 100%;
height: 120px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.45);
}
#inventoryChart {
display: block;
width: 100%;
height: 100%;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 11px;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend-swatch {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--sage);
}
.legend-swatch.red {
background: var(--red);
}
.legend-swatch.gold {
background: var(--gold);
}
.equation {
margin-top: 10px;
padding: 9px 10px;
border-radius: 9px;
color: #685b50;
background: rgba(83, 67, 53, 0.055);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
line-height: 1.55;
}
.event-log {
display: flex;
flex-direction: column;
gap: 7px;
max-height: 188px;
overflow-y: auto;
scrollbar-width: thin;
}
.log-entry {
display: grid;
grid-template-columns: 8px 43px 1fr;
align-items: start;
gap: 7px;
padding: 8px 9px;
border: 1px solid rgba(76, 61, 48, 0.08);
border-radius: 9px;
background: rgba(255, 255, 255, 0.42);
}
.log-dot {
width: 7px;
height: 7px;
margin-top: 3px;
border-radius: 2px;
background: var(--sage);
}
.log-entry.production .log-dot {
background: var(--terracotta);
}
.log-entry.demand .log-dot {
background: var(--blue);
}
.log-entry.stockout .log-dot {
background: var(--red);
}
.log-time {
color: #958679;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.log-text {
color: #5f5349;
font-size: 9px;
line-height: 1.42;
}
.log-text strong {
color: var(--ink);
}
#hud {
position: fixed;
z-index: 8;
left: 20px;
right: 400px;
bottom: 20px;
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
gap: 8px;
pointer-events: none;
}
.metric {
min-width: 0;
padding: 11px 12px 10px;
border: 1px solid rgba(255, 255, 255, 0.48);
border-radius: 14px;
background: rgba(255, 250, 241, 0.86);
box-shadow: 0 8px 22px rgba(59, 44, 32, 0.09);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.metric-label {
display: block;
overflow: hidden;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.055em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.metric-value {
display: block;
font-size: clamp(20px, 2.1vw, 28px);
font-weight: 850;
line-height: 1;
letter-spacing: -0.045em;
font-variant-numeric: tabular-nums;
}
.metric-note {
display: block;
overflow: hidden;
margin-top: 5px;
color: #918477;
font-size: 8px;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric.alert {
border-color: rgba(197, 77, 61, 0.3);
background: rgba(255, 244, 237, 0.92);
}
.metric.alert .metric-value {
color: var(--red);
}
.metric.surplus .metric-value {
color: #a66b24;
}
.scene-label {
position: fixed;
z-index: 6;
left: 50%;
top: 50%;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 9px;
color: var(--ink);
background: rgba(255, 250, 241, 0.88);
box-shadow: 0 7px 18px rgba(50, 37, 28, 0.13);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
font-weight: 800;
pointer-events: none;
transform: translate(-50%, -50%);
white-space: nowrap;
}
.scene-label.empty {
color: var(--red);
border-color: rgba(197, 77, 61, 0.35);
}
#toast {
position: fixed;
z-index: 30;
left: calc((100% - 380px) / 2);
bottom: 118px;
min-width: 240px;
max-width: 420px;
padding: 10px 14px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 12px;
color: var(--ink);
background: rgba(255, 250, 241, 0.94);
box-shadow: var(--shadow);
font-size: 11px;
line-height: 1.4;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 8px);
transition: opacity 160ms ease, transform 160ms ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#toast strong {
display: block;
margin-bottom: 2px;
font-size: 12px;
}
#toast.production {
border-left: 4px solid var(--terracotta);
}
#toast.demand {
border-left: 4px solid var(--blue);
}
#toast.stockout {
border-left: 4px solid var(--red);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
color: var(--ink);
background: #ded4c5;
font-size: 13px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#loading.hidden {
display: none;
}
@media (max-width: 1150px) {
.topbar,
#hud {
right: 390px;
}
#hud {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.metric-value {
font-size: 21px;
}
#toast {
left: calc((100% - 380px) / 2);
bottom: 170px;
}
}
@media (max-width: 850px) {
.topbar {
right: 14px;
left: 14px;
top: 14px;
}
.brand p:last-child,
.camera-controls .wide {
display: none;
}
#panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 43vh;
padding: 15px;
border-radius: 18px;
}
#hud {
top: 84px;
right: 14px;
bottom: auto;
left: 14px;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.metric {
padding: 8px 9px;
}
.metric-note {
display: none;
}
.metric-value {
font-size: 18px;
}
#toast {
top: 210px;
bottom: auto;
left: 50%;
}
}
@media (max-width: 520px) {
.brand {
padding: 9px;
}
.brand h1 {
font-size: 14px;
}
.brand .eyebrow {
font-size: 8px;
}
.logo {
width: 35px;
height: 35px;
}
.status-card {
min-width: 106px;
padding: 0 9px;
}
.camera-controls {
display: none;
}
#hud {
gap: 5px;
}
.metric-label {
font-size: 7px;
}
.metric-value {
font-size: 16px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel bakery production sandbox"></canvas>
<div id="loading">Building voxel bakery…</div>
<header class="topbar">
<div class="brand">
<div class="logo" aria-hidden="true"></div>
<div>
<p class="eyebrow">Production timing sandbox</p>
<h1>Bake Timing Lab</h1>
<p>Count trays, pulses, shortages, and surplus.</p>
</div>
</div>
<div class="top-right">
<div class="status-card">
<span id="statusDot" class="status-dot"></span>
<div class="status-copy">
<span id="runStatus">RUNNING</span>
<span id="clock">00:00</span>
</div>
</div>
<div class="camera-controls" aria-label="Camera controls">
<button id="camOut" type="button" title="Zoom out" aria-label="Zoom out">−</button>
<button id="camIn" type="button" title="Zoom in" aria-label="Zoom in">+</button>
<button id="camReset" class="wide" type="button" title="Reset camera">Reset view</button>
</div>
</div>
</header>
<aside id="panel" aria-label="Simulation controls">
<div class="panel-heading">
<div>
<p class="eyebrow">Fictional count model</p>
<h2>Configure the rhythm</h2>
<p>Events occur at fixed simulated-time intervals.</p>
</div>
<span id="pendingBadge" class="pending-badge">Applied</span>
</div>
<form id="scenarioForm">
<section class="section">
<div class="section-title">
<h3>Quick scenarios</h3>
<span>Loads and restarts</span>
</div>
<div class="presets">
<button class="preset" type="button" data-preset="balanced">Balanced</button>
<button class="preset" type="button" data-preset="stockout">Stockout</button>
<button class="preset" type="button" data-preset="surplus">Surplus</button>
</div>
<div class="field-grid">
<div class="field">
<label for="productionInterval">Batch interval</label>
<div class="number-wrap">
<input
id="productionInterval"
name="productionInterval"
type="number"
min="2"
max="60"
step="1"
value="7"
required
/>
<output data-output="productionInterval">sec</output>
</div>
</div>
<div class="field">
<label for="batchSize">Trays per batch</label>
<div class="number-wrap">
<input
id="batchSize"
name="batchSize"
type="number"
min="1"
max="20"
step="1"
value="4"
required
/>
<output data-output="batchSize">trays</output>
</div>
</div>
<div class="field">
<label for="demandInterval">Demand pulse interval</label>
<div class="number-wrap">
<input
id="demandInterval"
name="demandInterval"
type="number"
min="2"
max="60"
step="1"
value="10"
required
/>
<output data-output="demandInterval">sec</output>
</div>
</div>
<div class="field">
<label for="pulseSize">Trays requested per pulse</label>
<div class="number-wrap">
<input
id="pulseSize"
name="pulseSize"
type="number"
min="1"
max="30"
step="1"
value="6"
required
/>
<output data-output="pulseSize">trays</output>
</div>
</div>
<div class="field">
<label for="capacity">Display capacity</label>
<div class="number-wrap">
<input
id="capacity"
name="capacity"
type="number"
min="12"
max="48"
step="1"
value="30"
required
/>
<output data-output="capacity">trays</output>
</div>
</div>
<div class="field">
<label for="playbackSpeed">Playback speed</label>
<select id="playbackSpeed" name="playbackSpeed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="2">2×</option>
<option value="5">5×</option>
</select>
</div>
</div>
<p class="rule-note">
<strong>Counting rules:</strong>
A pulse asks for N trays. Available trays are handed out first; the
remainder is counted as a stockout tray. A batch adds N trays. If the
display is full, extra trays are explicitly counted as discarded.
<strong>No prices, revenue, costs, or spoilage rules are modeled.</strong>
</p>
<div class="button-row">
<button class="control-button primary" type="submit">Apply & restart</button>
<button id="pauseButton" class="control-button" type="button">Pause</button>
<button id="resetButton" class="control-button" type="button">Reset</button>
</div>
</section>
<section class="section">
<div class="section-title">
<h3>Next events</h3>
<span>Simulated time</span>
</div>
<div class="next-events">
<div class="event-chip production">
<span class="label">Next batch</span>
<strong id="nextProduction">7 sec</strong>
</div>
<div class="event-chip demand">
<span class="label">Next pulse</span>
<strong id="nextDemand">10 sec</strong>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h3>Display inventory</h3>
<span id="shelfCaption">0 / 30 trays</span>
</div>
<div class="chart-wrap">
<canvas id="inventoryChart" aria-label="Inventory history chart"></canvas>
</div>
<div class="chart-legend">
<span class="legend-item"><i class="legend-swatch"></i>On display</span>
<span class="legend-item"><i class="legend-swatch red"></i>Stockout pulse</span>
<span class="legend-item"><i class="legend-swatch gold"></i>Discarded</span>
</div>
<div id="accountingEquation" class="equation"></div>
</section>
<section class="section">
<div class="section-title">
<h3>Event ledger</h3>
<span>Explicit counts only</span>
</div>
<div id="eventLog" class="event-log" aria-live="polite"></div>
</section>
</form>
</aside>
<section id="hud" aria-label="Simulation counts">
<div class="metric">
<span class="metric-label">On display</span>
<strong id="metricStock" class="metric-value">0</strong>
<span class="metric-note">Current shelf stock</span>
</div>
<div class="metric">
<span class="metric-label">Made</span>
<strong id="metricMade" class="metric-value">0</strong>
<span class="metric-note">All batch trays</span>
</div>
<div class="metric">
<span class="metric-label">Handed out</span>
<strong id="metricFulfilled" class="metric-value">0</strong>
<span class="metric-note">Trays requested and supplied</span>
</div>
<div class="metric">
<span class="metric-label">Requested</span>
<strong id="metricRequested" class="metric-value">0</strong>
<span class="metric-note">Total pulse demand</span>
</div>
<div class="metric" id="metricStockoutCard">
<span class="metric-label">Stockout trays</span>
<strong id="metricStockout" class="metric-value">0</strong>
<span class="metric-note">Requested − handed out</span>
</div>
<div class="metric surplus" id="metricSurplusCard">
<span class="metric-label">Surplus trays</span>
<strong id="metricSurplus" class="metric-value">0</strong>
<span class="metric-note">Made − handed out</span>
</div>
</section>
<div id="stockSceneLabel" class="scene-label">SHELF 0 / 30</div>
<div id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM references
// -------------------------------------------------------------------------
const $ = (selector) => document.querySelector(selector);
const canvas = $("#scene");
const panel = $("#panel");
const form = $("#scenarioForm");
const eventLog = $("#eventLog");
const chartCanvas = $("#inventoryChart");
const chartContext = chartCanvas.getContext("2d");
const stockSceneLabel = $("#stockSceneLabel");
const toast = $("#toast");
const numberInputs = [
$("#productionInterval"),
$("#batchSize"),
$("#demandInterval"),
$("#pulseSize"),
$("#capacity")
];
let config = {
productionInterval: 7,
batchSize: 4,
demandInterval: 10,
pulseSize: 6,
capacity: 30
};
let running = true;
let playbackSpeed = 1;
let chartDirty = true;
let uiDirty = true;
let toastTimer = 0;
let sim = createEmptySimulation();
function createEmptySimulation() {
return {
time: 0,
nextProduction: 7,
nextDemand: 10,
nextSample: 0.5,
stock: 0,
made: 0,
fulfilled: 0,
requested: 0,
discarded: 0,
stockoutPulses: 0,
fulfilledPulses: 0,
history: [],
chartEvents: []
};
}
// -------------------------------------------------------------------------
// Renderer, camera, lighting
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xded4c5);
scene.fog = new THREE.Fog(0xded4c5, 22, 38);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
yaw: 0.72,
pitch: 0.62,
radius: 14.5,
target: new THREE.Vector3(0.25, 1.45, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
const horizontal = radius * Math.cos(pitch);
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xfff6df, 0x84776b, 2.3);
scene.add(hemisphere);
const ambient = new THREE.AmbientLight(0xfff1d4, 0.55);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.2);
sun.position.set(7, 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 = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fillLight = new THREE.DirectionalLight(0xb9d5db, 0.85);
fillLight.position.set(-7, 6, 1);
scene.add(fillLight);
// -------------------------------------------------------------------------
// Materials and voxel construction helpers
// -------------------------------------------------------------------------
const materials = {
backWall: new THREE.MeshStandardMaterial({
color: 0xd9cbb8,
roughness: 0.92
}),
sideWall: new THREE.MeshStandardMaterial({
color: 0xc3cfbd,
roughness: 0.92
}),
trim: new THREE.MeshStandardMaterial({
color: 0xf4ecdd,
roughness: 0.8
}),
dark: new THREE.MeshStandardMaterial({
color: 0x40342d,
roughness: 0.8
}),
wood: new THREE.MeshStandardMaterial({
color: 0x9b6747,
roughness: 0.85
}),
woodDark: new THREE.MeshStandardMaterial({
color: 0x70452f,
roughness: 0.9
}),
terracotta: new THREE.MeshStandardMaterial({
color: 0xb85f43,
roughness: 0.8
}),
terracottaDark: new THREE.MeshStandardMaterial({
color: 0x87432f,
roughness: 0.86
}),
cream: new THREE.MeshStandardMaterial({
color: 0xf4ead4,
roughness: 0.86
}),
metal: new THREE.MeshStandardMaterial({
color: 0x87918c,
metalness: 0.38,
roughness: 0.55
}),
gold: new THREE.MeshStandardMaterial({
color: 0xd99a48,
roughness: 0.74
}),
pastry: new THREE.MeshStandardMaterial({
color: 0xe8b866,
roughness: 0.88
}),
pastryLight: new THREE.MeshStandardMaterial({
color: 0xf4d294,
roughness: 0.88
}),
tray: new THREE.MeshStandardMaterial({
color: 0x8c5638,
roughness: 0.88
}),
discarded: new THREE.MeshStandardMaterial({
color: 0xc7793c,
roughness: 0.9
}),
blue: new THREE.MeshStandardMaterial({
color: 0x517e88,
roughness: 0.85
}),
blueLight: new THREE.MeshStandardMaterial({
color: 0x86aeb2,
roughness: 0.84
}),
green: new THREE.MeshStandardMaterial({
color: 0x667e5f,
roughness: 0.9
}),
greenLight: new THREE.MeshStandardMaterial({
color: 0x89a276,
roughness: 0.9
}),
skin: new THREE.MeshStandardMaterial({
color: 0xc8926e,
roughness: 0.9
}),
white: new THREE.MeshStandardMaterial({
color: 0xfffaf0,
roughness: 0.82
})
};
const serviceLightMaterial = new THREE.MeshStandardMaterial({
color: 0x73966f,
emissive: 0x315b32,
emissiveIntensity: 0.4,
roughness: 0.4
});
const ovenLightMaterial = new THREE.MeshStandardMaterial({
color: 0xd98b3d,
emissive: 0xff7b28,
emissiveIntensity: 0.35,
roughness: 0.45
});
function box(width, height, depth, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function signTexture(title, subtitle, background = "#f4ead4", foreground = "#40342d") {
const signCanvas = document.createElement("canvas");
signCanvas.width = 1024;
signCanvas.height = 256;
const context = signCanvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, 1024, 256);
context.strokeStyle = foreground;
context.lineWidth = 18;
context.strokeRect(18, 18, 988, 220);
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = foreground;
context.font = "900 92px monospace";
context.fillText(title, 512, 100);
context.font = "700 30px monospace";
context.fillText(subtitle, 512, 180);
const texture = new THREE.CanvasTexture(signCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
function addSign(width, height, title, subtitle, x, y, z, background, foreground) {
const material = new THREE.MeshBasicMaterial({
map: signTexture(title, subtitle, background, foreground),
side: THREE.DoubleSide
});
const sign = new THREE.Mesh(new THREE.PlaneGeometry(width, height), material);
sign.position.set(x, y, z);
scene.add(sign);
return sign;
}
// -------------------------------------------------------------------------
// Build the bakery
// -------------------------------------------------------------------------
const shop = new THREE.Group();
scene.add(shop);
// Floor slab and individual voxel tiles.
box(12.4, 0.42, 10.4, materials.woodDark, 0, -0.22, 0, shop);
const tileGeometry = new THREE.BoxGeometry(0.96, 0.055, 0.96);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95
});
const tileMesh = new THREE.InstancedMesh(tileGeometry, tileMaterial, 120);
tileMesh.receiveShadow = true;
const transform = new THREE.Object3D();
const tileColors = [
new THREE.Color(0xeee3d0),
new THREE.Color(0xe8dcc8),
new THREE.Color(0xf3e9d8)
];
let tileIndex = 0;
for (let z = 0; z < 10; z++) {
for (let x = 0; x < 12; x++) {
transform.position.set(x - 5.5, 0.015, z - 4.5);
transform.updateMatrix();
tileMesh.setMatrixAt(tileIndex, transform.matrix);
tileMesh.setColorAt(
tileIndex,
tileColors[(x + z * 2) % tileColors.length]
);
tileIndex++;
}
}
tileMesh.instanceMatrix.needsUpdate = true;
tileMesh.instanceColor.needsUpdate = true;
shop.add(tileMesh);
// Cutaway walls.
box(12.2, 4.7, 0.3, materials.backWall, 0, 2.35, -5.0, shop);
box(0.3, 3.7, 10.0, materials.sideWall, -6.0, 1.85, 0, shop);
box(12.2, 0.16, 0.38, materials.trim, 0, 4.72, -4.96, shop);
box(0.38, 0.16, 10.0, materials.trim, -5.96, 3.72, 0, shop);
// Lower wall wainscoting.
box(12.0, 0.72, 0.08, materials.terracottaDark, 0, 0.42, -4.82, shop);
box(0.08, 0.72, 9.8, materials.wood, -5.82, 0.42, 0, shop);
// Window on the side wall.
box(0.08, 2.25, 2.8, materials.blueLight, -5.80, 2.35, -1.65, shop);
box(0.12, 0.14, 3.05, materials.trim, -5.72, 3.53, -1.65, shop);
box(0.12, 0.14, 3.05, materials.trim, -5.72, 1.17, -1.65, shop);
box(0.12, 2.45, 0.14, materials.trim, -5.72, 2.35, -3.13, shop);
box(0.12, 2.45, 0.14, materials.trim, -5.72, 2.35, -0.17, shop);
box(0.12, 2.35, 0.08, materials.trim, -5.68, 2.35, -1.65, shop);
// Shop sign and clock.
addSign(
5.9,
1.25,
"BAKE / TIME",
"PRODUCTION TIMING SANDBOX",
1.45,
3.86,
-4.81,
"#f4ead4",
"#40342d"
);
box(1.28, 1.28, 0.13, materials.woodDark, -2.55, 3.75, -4.75, shop);
box(1.08, 1.08, 0.10, materials.cream, -2.55, 3.75, -4.66, shop);
box(0.08, 0.35, 0.05, materials.dark, -2.55, 3.87, -4.57, shop);
box(0.27, 0.07, 0.05, materials.dark, -2.47, 3.72, -4.57, shop);
box(0.08, 0.08, 0.08, materials.terracotta, -2.55, 3.75, -4.52, shop);
// Counter.
box(5.25, 1.28, 1.9, materials.terracotta, 1.45, 0.78, 0.0, shop);
box(5.55, 0.18, 2.12, materials.wood, 1.45, 1.50, 0.0, shop);
box(4.85, 0.65, 0.09, materials.cream, 1.45, 0.85, 0.985, shop);
for (let i = 0; i < 7; i++) {
box(0.08, 0.55, 0.05, materials.woodDark, -0.65 + i * 0.7, 0.85, 1.045, shop);
}
addSign(
2.5,
0.5,
"FRESH TRAYS",
"COUNT / TIMING",
1.45,
0.84,
1.075,
"#f4ead4",
"#87432f"
);
// Display frame with four shelves.
const shelfYs = [1.62, 2.01, 2.40, 2.79];
for (const shelfY of shelfYs) {
box(4.7, 0.07, 0.72, materials.cream, 1.42, shelfY, -0.25, shop);
box(4.72, 0.08, 0.09, materials.wood, 1.42, shelfY - 0.01, 0.13, shop);
}
box(0.10, 1.55, 0.70, materials.woodDark, -0.96, 2.18, -0.25, shop);
box(0.10, 1.55, 0.70, materials.woodDark, 3.80, 2.18, -0.25, shop);
// Register.
box(0.72, 0.22, 0.62, materials.dark, 4.04, 1.70, 0.54, shop);
box(0.48, 0.42, 0.10, materials.metal, 4.04, 1.98, 0.62, shop);
box(0.38, 0.28, 0.05, materials.blue, 4.04, 1.98, 0.69, shop);
// Small service indicator.
box(0.15, 0.15, 0.15, serviceLightMaterial, 3.61, 1.77, 0.58, shop);
// Oven.
const oven = new THREE.Group();
oven.position.set(-4.05, 0, -3.55);
shop.add(oven);
box(2.2, 2.25, 1.65, materials.terracottaDark, 0, 1.22, 0, oven);
box(2.35, 0.18, 1.78, materials.metal, 0, 2.42, 0, oven);
box(1.58, 1.05, 0.12, materials.dark, 0, 1.13, 0.87, oven);
box(1.35, 0.82, 0.07, ovenLightMaterial, 0, 1.13, 0.95, oven);
box(1.45, 0.12, 0.16, materials.metal, 0, 1.82, 0.93, oven);
box(0.26, 0.26, 0.15, materials.dark, 0.78, 2.18, 0.86, oven);
box(0.16, 0.16, 0.16, ovenLightMaterial, -0.78, 2.18, 0.86, oven);
// Prep table.
box(2.45, 0.16, 1.15, materials.wood, -3.65, 1.38, 0.15, shop);
for (const x of [-4.55, -2.75]) {
for (const z of [-0.18, 0.48]) {
box(0.16, 1.3, 0.16, materials.woodDark, x, 0.67, z, shop);
}
}
box(0.62, 0.12, 0.42, materials.cream, -4.18, 1.52, 0.03, shop);
box(0.48, 0.12, 0.38, materials.cream, -3.33, 1.52, 0.10, shop);
const doughGeometry = new THREE.BoxGeometry(0.16, 0.16, 0.16);
const doughMesh = new THREE.InstancedMesh(
doughGeometry,
materials.pastryLight,
6
);
for (let i = 0; i < 6; i++) {
transform.position.set(-4.18, 1.66, -0.05 + (i % 3) * 0.1);
transform.updateMatrix();
doughMesh.setMatrixAt(i, transform.matrix);
}
doughMesh.instanceMatrix.needsUpdate = true;
doughMesh.castShadow = true;
shop.add(doughMesh);
// Discard bin.
box(0.95, 0.78, 0.90, materials.dark, -2.05, 0.48, 1.72, shop);
box(1.05, 0.12, 1.0, materials.metal, -2.05, 0.91, 1.72, shop);
box(0.66, 0.12, 0.05, materials.metal, -2.05, 0.56, 2.19, shop);
// Customer waiting area.
box(2.4, 0.025, 1.7, materials.terracottaDark, 3.45, 0.05, 3.15, shop);
box(2.15, 0.03, 1.45, materials.gold, 3.45, 0.07, 3.15, shop);
// Plant.
box(0.58, 0.62, 0.58, materials.terracotta, 5.12, 0.38, -4.25, shop);
box(0.12, 0.8, 0.12, materials.woodDark, 5.12, 1.05, -4.25, shop);
box(0.58, 0.35, 0.25, materials.green, 5.12, 1.50, -4.25, shop);
box(0.28, 0.55, 0.30, materials.greenLight, 4.88, 1.40, -4.14, shop);
box(0.32, 0.46, 0.30, materials.greenLight, 5.35, 1.42, -4.37, shop);
// Voxel worker.
const worker = new THREE.Group();
worker.position.set(1.48, 0, -1.80);
shop.add(worker);
box(0.66, 0.72, 0.43, materials.white, 0, 1.42, 0, worker);
box(0.48, 0.48, 0.48, materials.skin, 0, 2.03, 0, worker);
box(0.54, 0.25, 0.50, materials.white, 0, 2.37, 0, worker);
box(0.66, 0.16, 0.54, materials.white, 0, 2.54, 0, worker);
box(0.43, 0.20, 0.10, materials.terracotta, 0, 1.68, 0.25, worker);
box(0.09, 0.09, 0.04, materials.dark, -0.11, 2.06, 0.25, worker);
box(0.09, 0.09, 0.04, materials.dark, 0.11, 2.06, 0.25, worker);
box(0.17, 0.62, 0.19, materials.dark, -0.18, 0.52, 0, worker);
box(0.17, 0.62, 0.19, materials.dark, 0.18, 0.52, 0, worker);
const workerArmLeft = new THREE.Group();
workerArmLeft.position.set(-0.42, 1.68, 0);
worker.add(workerArmLeft);
box(0.18, 0.55, 0.18, materials.white, 0, -0.25, 0, workerArmLeft);
box(0.19, 0.18, 0.19, materials.skin, 0, -0.57, 0, workerArmLeft);
const workerArmRight = new THREE.Group();
workerArmRight.position.set(0.42, 1.68, 0);
worker.add(workerArmRight);
box(0.18, 0.55, 0.18, materials.white, 0, -0.25, 0, workerArmRight);
box(0.19, 0.18, 0.19, materials.skin, 0, -0.57, 0, workerArmRight);
// -------------------------------------------------------------------------
// Dynamic instanced trays
// -------------------------------------------------------------------------
const trayGeometry = new THREE.BoxGeometry(0.28, 0.07, 0.24);
const trayMesh = new THREE.InstancedMesh(
trayGeometry,
materials.tray,
48
);
trayMesh.count = 0;
trayMesh.castShadow = true;
trayMesh.receiveShadow = true;
scene.add(trayMesh);
const bunGeometry = new THREE.BoxGeometry(0.073, 0.07, 0.073);
const bunMesh = new THREE.InstancedMesh(
bunGeometry,
materials.pastry,
144
);
bunMesh.count = 0;
bunMesh.castShadow = true;
scene.add(bunMesh);
const discardedGeometry = new THREE.BoxGeometry(0.26, 0.065, 0.21);
const discardedMesh = new THREE.InstancedMesh(
discardedGeometry,
materials.discarded,
18
);
discardedMesh.count = 0;
discardedMesh.castShadow = true;
scene.add(discardedMesh);
function updateTrayVisuals() {
const count = Math.min(sim.stock, 48);
trayMesh.count = count;
bunMesh.count = count * 3;
let bunIndex = 0;
for (let i = 0; i < count; i++) {
const column = i % 12;
const row = Math.floor(i / 12);
const x = -0.82 + column * 0.38;
const y = shelfYs[row] + 0.085;
const z = -0.25;
transform.position.set(x, y, z);
transform.rotation.set(0, 0, 0);
transform.scale.set(1, 1, 1);
transform.updateMatrix();
trayMesh.setMatrixAt(i, transform.matrix);
for (let bun = 0; bun < 3; bun++) {
transform.position.set(x - 0.073 + bun * 0.073, y + 0.069, z);
transform.updateMatrix();
bunMesh.setMatrixAt(bunIndex, transform.matrix);
bunIndex++;
}
}
trayMesh.instanceMatrix.needsUpdate = true;
bunMesh.instanceMatrix.needsUpdate = true;
trayMesh.computeBoundingSphere();
bunMesh.computeBoundingSphere();
const visibleDiscarded = Math.min(sim.discarded, 18);
discardedMesh.count = visibleDiscarded;
for (let i = 0; i < visibleDiscarded; i++) {
const layer = Math.floor(i / 3);
const slot = i % 3;
transform.position.set(
-2.29 + slot * 0.22,
1.01 + layer * 0.075,
1.62 + (layer % 2) * 0.15
);
transform.rotation.set(0, 0, 0);
transform.scale.set(1, 1, 1);
transform.updateMatrix();
discardedMesh.setMatrixAt(i, transform.matrix);
}
discardedMesh.instanceMatrix.needsUpdate = true;
discardedMesh.computeBoundingSphere();
}
// -------------------------------------------------------------------------
// Demand-pulse customers
// -------------------------------------------------------------------------
const customers = [];
const redMarkerMaterial = new THREE.MeshStandardMaterial({
color: 0xc54d3d,
roughness: 0.8
});
const greenMarkerMaterial = new THREE.MeshStandardMaterial({
color: 0x72936e,
roughness: 0.8
});
function createCustomer(index, unmet) {
const customer = new THREE.Group();
const markerMaterial = unmet > 0 ? redMarkerMaterial : greenMarkerMaterial;
box(0.44, 0.56, 0.30, index % 2 ? materials.blue : materials.blueLight, 0, 0.70, 0, customer);
box(0.34, 0.34, 0.34, materials.skin, 0, 1.15, 0, customer);
box(0.08, 0.08, 0.04, materials.dark, -0.08, 1.17, -0.18, customer);
box(0.08, 0.08, 0.04, materials.dark, 0.08, 1.17, -0.18, customer);
box(0.15, 0.32, 0.17, materials.dark, -0.12, 0.22, 0, customer);
box(0.15, 0.32, 0.17, materials.dark, 0.12, 0.22, 0, customer);
box(0.27, 0.34, 0.18, materials.cream, 0.38, 0.61, 0, customer);
box(0.46, 0.025, 0.46, markerMaterial, 0, 0.055, 0, customer);
const count = Math.min(6, Math.max(1, Math.ceil(config.pulseSize / 3)));
const column = index % 3;
const row = Math.floor(index / 3);
customer.position.set(
2.55 + column * 0.64,
0.10,
2.70 + row * 0.68
);
customer.userData.born = sim.time;
customer.userData.phase = index * 1.7;
customer.scale.setScalar(0.01);
scene.add(customer);
customers.push(customer);
}
function clearCustomers() {
for (const customer of customers) {
scene.remove(customer);
}
customers.length = 0;
}
// -------------------------------------------------------------------------
// Simulation
// -------------------------------------------------------------------------
function formatTime(seconds) {
const whole = Math.max(0, Math.floor(seconds));
const minutes = Math.floor(whole / 60);
const remainder = whole % 60;
return `${String(minutes).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
function formatCount(value) {
return new Intl.NumberFormat("en-US").format(value);
}
function surplusCount() {
return sim.made - sim.fulfilled;
}
function stockoutCount() {
return sim.requested - sim.fulfilled;
}
function pushHistory(time = sim.time) {
sim.history.push({
time,
stock: sim.stock
});
if (sim.history.length > 800) {
sim.history.shift();
}
chartDirty = true;
}
function addLog(type, title, detail) {
const entry = document.createElement("div");
entry.className = `log-entry ${type}`;
const dot = document.createElement("span");
dot.className = "log-dot";
const time = document.createElement("span");
time.className = "log-time";
time.textContent = formatTime(sim.time);
const text = document.createElement("span");
text.className = "log-text";
const strong = document.createElement("strong");
strong.textContent = `${title} `;
text.append(strong);
text.append(document.createTextNode(detail));
entry.append(dot, time, text);
eventLog.prepend(entry);
while (eventLog.children.length > 9) {
eventLog.lastElementChild.remove();
}
}
function showToast(type, title, detail) {
toast.className = `visible ${type}`;
toast.replaceChildren();
const strong = document.createElement("strong");
strong.textContent = title;
const span = document.createElement("span");
span.textContent = detail;
toast.append(strong, span);
window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => {
toast.classList.remove("visible");
}, 2300);
}
function produceBatch() {
const batch = config.batchSize;
const room = Math.max(0, config.capacity - sim.stock);
const placed = Math.min(room, batch);
const discarded = batch - placed;
sim.made += batch;
sim.stock += placed;
sim.discarded += discarded;
sim.chartEvents.push({
time: sim.time,
type: "production",
discarded
});
updateTrayVisuals();
pushHistory();
addLog(
"production",
`Batch of ${batch}.`,
`${placed} placed; ${discarded} discarded for lack of display space.`
);
showToast(
"production",
`Batch ready: ${batch} trays`,
`${placed} placed on display · ${discarded} discarded`
);
ovenFlash = 1;
workerPulse = 1;
uiDirty = true;
}
function demandPulse() {
const requested = config.pulseSize;
const handedOut = Math.min(sim.stock, requested);
const unmet = requested - handedOut;
sim.requested += requested;
sim.fulfilled += handedOut;
sim.stock -= handedOut;
if (unmet > 0) {
sim.stockoutPulses++;
} else {
sim.fulfilledPulses++;
}
sim.chartEvents.push({
time: sim.time,
type: unmet > 0 ? "stockout" : "demand",
unmet
});
const customerCount = Math.min(
6,
Math.max(1, Math.ceil(requested / 3))
);
for (let i = 0; i < customerCount; i++) {
createCustomer(i, unmet);
}
updateTrayVisuals();
pushHistory();
addLog(
unmet > 0 ? "stockout" : "demand",
`Pulse for ${requested}.`,
`${handedOut} handed out; ${unmet} unavailable.`
);
if (unmet > 0) {
showToast(
"stockout",
`Stockout: ${unmet} trays`,
`${handedOut} of ${requested} requested trays were handed out`
);
serviceLightMaterial.color.setHex(0xc54d3d);
serviceLightMaterial.emissive.setHex(0x7d1e14);
} else {
showToast(
"demand",
`Pulse fulfilled: ${handedOut} trays`,
`All ${requested} requested trays were available`
);
serviceLightMaterial.color.setHex(0x73966f);
serviceLightMaterial.emissive.setHex(0x315b32);
}
serviceFlash = 1;
uiDirty = true;
}
function advanceSimulation(seconds) {
if (seconds <= 0) return;
let remaining = seconds;
let guard = 0;
while (remaining > 1e-7 && guard++ < 10000) {
const nextEvent = Math.min(sim.nextProduction, sim.nextDemand);
const gap = Math.max(0, nextEvent - sim.time);
const step = Math.min(remaining, gap);
sim.time += step;
remaining -= step;
while (sim.time + 1e-7 >= sim.nextSample) {
pushHistory(sim.nextSample);
sim.nextSample += 0.5;
}
if (Math.abs(sim.time - sim.nextProduction) < 1e-6) {
produceBatch();
sim.nextProduction += config.productionInterval;
}
if (Math.abs(sim.time - sim.nextDemand) < 1e-6) {
demandPulse();
sim.nextDemand += config.demandInterval;
}
if (step <= 1e-7 && remaining <= 1e-7) break;
}
}
function resetSimulation() {
clearCustomers();
sim = createEmptySimulation();
sim.nextProduction = config.productionInterval;
sim.nextDemand = config.demandInterval;
sim.history.push({ time: 0, stock: 0 });
eventLog.replaceChildren();
addLog("demand", "Simulation reset.", "Display starts with 0 trays.");
updateTrayVisuals();
uiDirty = true;
chartDirty = true;
}
// -------------------------------------------------------------------------
// Configuration UI
// -------------------------------------------------------------------------
function readConfigFromForm() {
return {
productionInterval: Number($("#productionInterval").value),
batchSize: Number($("#batchSize").value),
demandInterval: Number($("#demandInterval").value),
pulseSize: Number($("#pulseSize").value),
capacity: Number($("#capacity").value)
};
}
function updateInputLabels() {
document.querySelectorAll("[data-output]").forEach((output) => {
const input = document.getElementById(output.dataset.output);
output.value = output.textContent;
output.textContent = input.value + " " + output.value;
});
const pending =
JSON.stringify(readConfigFromForm()) !== JSON.stringify(config);
$("#pendingBadge").textContent = pending ? "Pending" : "Applied";
$("#pendingBadge").classList.toggle("pending", pending);
}
function applyConfiguration() {
if (!form.reportValidity()) return;
config = readConfigFromForm();
playbackSpeed = Number($("#playbackSpeed").value);
resetSimulation();
running = true;
updateInputLabels();
uiDirty = true;
}
numberInputs.forEach((input) => {
input.addEventListener("input", updateInputLabels);
});
form.addEventListener("submit", (event) => {
event.preventDefault();
applyConfiguration();
});
$("#pauseButton").addEventListener("click", () => {
running = !running;
uiDirty = true;
});
$("#resetButton").addEventListener("click", () => {
running = false;
resetSimulation();
});
$("#playbackSpeed").addEventListener("change", () => {
playbackSpeed = Number($("#playbackSpeed").value);
});
const presets = {
balanced: {
productionInterval: 6,
batchSize: 4,
demandInterval: 12,
pulseSize: 4,
capacity: 30
},
stockout: {
productionInterval: 7,
batchSize: 4,
demandInterval: 10,
pulseSize: 6,
capacity: 30
},
surplus: {
productionInterval: 4,
batchSize: 8,
demandInterval: 16,
pulseSize: 3,
capacity: 24
}
};
document.querySelectorAll("[data-preset]").forEach((button) => {
button.addEventListener("click", () => {
const preset = presets[button.dataset.preset];
$("#productionInterval").value = preset.productionInterval;
$("#batchSize").value = preset.batchSize;
$("#demandInterval").value = preset.demandInterval;
$("#pulseSize").value = preset.pulseSize;
$("#capacity").value = preset.capacity;
updateInputLabels();
applyConfiguration();
});
});
// -------------------------------------------------------------------------
// Inventory chart
// -------------------------------------------------------------------------
function renderChart() {
const width = chartCanvas.clientWidth;
const height = chartCanvas.clientHeight;
if (!width || !height) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const targetWidth = Math.round(width * dpr);
const targetHeight = Math.round(height * dpr);
if (chartCanvas.width !== targetWidth || chartCanvas.height !== targetHeight) {
chartCanvas.width = targetWidth;
chartCanvas.height = targetHeight;
}
chartContext.setTransform(dpr, 0, 0, dpr, 0, 0);
chartContext.clearRect(0, 0, width, height);
const padding = { left: 27, right: 9, top: 9, bottom: 20 };
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
const endTime = Math.max(30, sim.time);
const startTime = Math.max(0, endTime - 60);
const visibleDuration = Math.max(1, endTime - startTime);
const maxStock = Math.max(
config.capacity,
...sim.history.map((sample) => sample.stock)
);
const xFor = (time) =>
padding.left + ((time - startTime) / visibleDuration) * plotWidth;
const yFor = (stock) =>
padding.top + plotHeight - (stock / maxStock) * plotHeight;
chartContext.lineWidth = 1;
chartContext.strokeStyle = "rgba(89, 70, 55, 0.10)";
chartContext.fillStyle = "rgba(93, 77, 62, 0.58)";
chartContext.font = "9px ui-monospace, monospace";
for (let i = 0; i <= 2; i++) {
const value = (maxStock / 2) * i;
const y = yFor(value);
chartContext.beginPath();
chartContext.moveTo(padding.left, y);
chartContext.lineTo(width - padding.right, y);
chartContext.stroke();
chartContext.fillText(String(Math.round(value)), 2, y + 3);
}
for (const event of sim.chartEvents) {
if (event.time < startTime || event.time > endTime) continue;
const x = xFor(event.time);
if (event.type === "stockout") {
chartContext.strokeStyle = "rgba(197, 77, 61, 0.65)";
chartContext.lineWidth = 1.5;
chartContext.beginPath();
chartContext.moveTo(x, padding.top);
chartContext.lineTo(x, padding.top + plotHeight);
chartContext.stroke();
chartContext.fillStyle = "#c54d3d";
chartContext.beginPath();
chartContext.moveTo(x, padding.top);
chartContext.lineTo(x - 4, padding.top - 5);
chartContext.lineTo(x + 4, padding.top - 5);
chartContext.closePath();
chartContext.fill();
}
if (event.discarded > 0) {
chartContext.fillStyle = "#d99a48";
chartContext.beginPath();
chartContext.arc(x, padding.top + 4, 3, 0, Math.PI * 2);
chartContext.fill();
}
}
chartContext.save();
chartContext.beginPath();
chartContext.rect(
padding.left,
padding.top,
plotWidth,
plotHeight
);
chartContext.clip();
chartContext.strokeStyle = "#6f866d";
chartContext.lineWidth = 2.2;
chartContext.lineJoin = "round";
chartContext.lineCap = "round";
chartContext.beginPath();
let drawing = false;
for (const sample of sim.history) {
if (sample.time < startTime) continue;
const x = xFor(sample.time);
const y = yFor(sample.stock);
if (!drawing) {
chartContext.moveTo(x, y);
drawing = true;
} else {
chartContext.lineTo(x, y);
}
}
chartContext.stroke();
const areaPath = new Path2D();
let areaStarted = false;
let lastX = padding.left;
for (const sample of sim.history) {
if (sample.time < startTime) continue;
const x = xFor(sample.time);
const y = yFor(sample.stock);
lastX = x;
if (!areaStarted) {
areaPath.moveTo(x, padding.top + plotHeight);
areaPath.lineTo(x, y);
areaStarted = true;
} else {
areaPath.lineTo(x, y);
}
}
if (areaStarted) {
areaPath.lineTo(lastX, padding.top + plotHeight);
areaPath.closePath();
chartContext.fillStyle = "rgba(111, 134, 109, 0.12)";
chartContext.fill(areaPath);
}
chartContext.restore();
chartContext.fillStyle = "rgba(93, 77, 62, 0.58)";
chartContext.fillText(formatTime(startTime), padding.left, height - 4);
chartContext.textAlign = "right";
chartContext.fillText(formatTime(endTime), width - padding.right, height - 4);
chartContext.textAlign = "left";
chartDirty = false;
}
// -------------------------------------------------------------------------
// UI synchronization
// -------------------------------------------------------------------------
function updateUI() {
$("#clock").textContent = formatTime(sim.time);
$("#runStatus").textContent = running ? "RUNNING" : "PAUSED";
$("#statusDot").classList.toggle("paused", !running);
$("#pauseButton").textContent = running ? "Pause" : "Start";
const stock = sim.stock;
const stockout = stockoutCount();
const surplus = surplusCount();
$("#metricStock").textContent = formatCount(stock);
$("#metricMade").textContent = formatCount(sim.made);
$("#metricFulfilled").textContent = formatCount(sim.fulfilled);
$("#metricRequested").textContent = formatCount(sim.requested);
$("#metricStockout").textContent = formatCount(stockout);
$("#metricSurplus").textContent = formatCount(surplus);
$("#metricStockoutCard").classList.toggle("alert", stockout > 0);
$("#metricSurplusCard").classList.toggle("alert", false);
$("#shelfCaption").textContent = `${stock} / ${config.capacity} trays`;
$("#stockSceneLabel").textContent = `SHELF ${stock} / ${config.capacity}`;
$("#stockSceneLabel").classList.toggle("empty", stock === 0);
const productionIn = Math.max(0, sim.nextProduction - sim.time);
const demandIn = Math.max(0, sim.nextDemand - sim.time);
$("#nextProduction").textContent =
productionIn < 1 ? "now" : `${Math.ceil(productionIn)} sec`;
$("#nextDemand").textContent =
demandIn < 1 ? "now" : `${Math.ceil(demandIn)} sec`;
$("#accountingEquation").innerHTML = `
Made ${sim.made} = handed out ${sim.fulfilled} + on display ${stock} + discarded ${sim.discarded}<br>
Stockout trays = requested ${sim.requested} − handed out ${sim.fulfilled}<br>
Surplus trays = on display ${stock} + discarded ${sim.discarded}
`;
uiDirty = false;
}
// -------------------------------------------------------------------------
// Direct camera controls: drag orbit, shift-drag pan, wheel zoom, keyboard
// -------------------------------------------------------------------------
let dragging = false;
let pointerId = null;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerId = event.pointerId;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== pointerId) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (event.shiftKey) {
const scale = cameraState.radius * 0.0015;
const right = new THREE.Vector3(
Math.cos(cameraState.yaw),
0,
-Math.sin(cameraState.yaw)
);
const forward = new THREE.Vector3(
Math.sin(cameraState.yaw),
0,
Math.cos(cameraState.yaw)
);
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, -dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-3,
3
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-3,
3
);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.22,
1.25
);
}
});
function endDrag(event) {
if (pointerId !== null && event.pointerId !== pointerId) return;
dragging = false;
pointerId = null;
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
8.5,
24
);
},
{ passive: false }
);
function resetCamera() {
cameraState.yaw = 0.72;
cameraState.pitch = 0.62;
cameraState.radius = 14.5;
cameraState.target.set(0.25, 1.45, 0);
}
$("#camReset").addEventListener("click", resetCamera);
$("#camIn").addEventListener("click", () => {
cameraState.radius = Math.max(8.5, cameraState.radius - 1);
});
$("#camOut").addEventListener("click", () => {
cameraState.radius = Math.min(24, cameraState.radius + 1);
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLSelectElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
if (event.key === "ArrowLeft") cameraState.yaw += 0.08;
if (event.key === "ArrowRight") cameraState.yaw -= 0.08;
if (event.key === "ArrowUp") {
cameraState.pitch = Math.min(1.25, cameraState.pitch + 0.06);
}
if (event.key === "ArrowDown") {
cameraState.pitch = Math.max(0.22, cameraState.pitch - 0.06);
}
if (event.key === "+" || event.key === "=") {
cameraState.radius = Math.max(8.5, cameraState.radius - 0.8);
}
if (event.key === "-" || event.key === "_") {
cameraState.radius = Math.min(24, cameraState.radius + 0.8);
}
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
let ovenFlash = 0;
let workerPulse = 0;
let serviceFlash = 0;
let elapsedReal = 0;
let lastFrame = performance.now();
let uiTimer = 0;
let chartTimer = 0;
const projectedLabelPosition = new THREE.Vector3();
function animate(now) {
const delta = Math.min((now - lastFrame) / 1000, 0.05);
lastFrame = now;
elapsedReal += delta;
if (running) {
advanceSimulation(delta * playbackSpeed);
}
ovenFlash = Math.max(0, ovenFlash - delta * 1.9);
workerPulse = Math.max(0, workerPulse - delta * 2.2);
serviceFlash = Math.max(0, serviceFlash - delta * 1.7);
ovenLightMaterial.emissiveIntensity =
0.35 + ovenFlash * 3.2 + Math.sin(elapsedReal * 3) * 0.05;
serviceLightMaterial.emissiveIntensity =
0.35 + serviceFlash * 2.5 + Math.sin(elapsedReal * 4) * 0.08;
workerArmLeft.rotation.x =
-0.42 - workerPulse * 0.65 + Math.sin(elapsedReal * 2.2) * 0.04;
workerArmRight.rotation.x =
-0.42 - workerPulse * 0.48 + Math.cos(elapsedReal * 2.2) * 0.04;
worker.position.y = Math.sin(elapsedReal * 2) * 0.015;
for (let i = customers.length - 1; i >= 0; i--) {
const customer = customers[i];
const age = sim.time - customer.userData.born;
if (age > 5) {
scene.remove(customer);
customers.splice(i, 1);
continue;
}
const appear = Math.min(1, age / 0.35);
const leave = Math.min(1, Math.max(0, (5 - age) / 0.7));
const scale = Math.max(0.01, Math.min(appear, leave));
customer.scale.setScalar(scale);
customer.position.y =
0.10 + Math.sin(elapsedReal * 3 + customer.userData.phase) * 0.025;
}
updateCamera();
projectedLabelPosition.set(1.45, 3.34, -0.15).project(camera);
const labelX = (projectedLabelPosition.x * 0.5 + 0.5) * window.innerWidth;
const labelY = (-projectedLabelPosition.y * 0.5 + 0.5) * window.innerHeight;
stockSceneLabel.style.left = `${labelX}px`;
stockSceneLabel.style.top = `${labelY}px`;
stockSceneLabel.style.display =
projectedLabelPosition.z > -1 && projectedLabelPosition.z < 1
? "block"
: "none";
uiTimer += delta;
chartTimer += delta;
if (uiDirty || uiTimer > 0.1) {
updateUI();
uiTimer = 0;
}
if (chartDirty || chartTimer > 0.25) {
renderChart();
chartTimer = 0;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
chartDirty = true;
});
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
updateInputLabels();
resetSimulation();
updateUI();
renderChart();
$("#loading").classList.add("hidden");
requestAnimationFrame(animate);
</script>
</body>
</html>
```