Prompt specification
Build or customize the Three.js 3D scene "Fraction-allocation food-system game" 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: Fraction-allocation food-system game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/fraction-allocation-food-system-game-x1084
Scene Description Prompt:
Create a toy milling system with declared product fractions and demand cards; users route outputs to different uses while a mass-accounting display prevents material from disappearing. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Working Three.js Starter (fraction-allocation-food-system-game-x1084):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grain Route — Voxel Milling Lab</title>
<style>
:root {
--paper: #f2eee5;
--panel: #fffdf8;
--ink: #17251f;
--muted: #69736c;
--line: #d9d8ce;
--green: #466c58;
--green-dark: #294d3d;
--green-soft: #e1ebe3;
--amber: #d79a35;
--brown: #ae6540;
--meal: #c49a68;
--danger: #a84f3f;
--shadow: 0 12px 30px rgba(39, 48, 42, 0.09);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
}
header {
height: 72px;
flex: 0 0 72px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(255, 253, 248, 0.96);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.voxel-logo {
width: 38px;
height: 38px;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 3px;
transform: rotate(-3deg);
}
.voxel-logo i {
display: block;
background: var(--green);
border-radius: 2px;
}
.voxel-logo i:nth-child(2),
.voxel-logo i:nth-child(4),
.voxel-logo i:nth-child(9) {
opacity: 0.35;
}
.voxel-logo i:nth-child(5) {
background: var(--amber);
}
.brand-title {
font-size: 17px;
font-weight: 850;
letter-spacing: -0.03em;
}
.brand-subtitle {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.header-actions {
display: flex;
align-items: center;
gap: 11px;
}
.header-balance {
display: flex;
align-items: center;
gap: 9px;
padding: 9px 12px;
border: 1px solid #ccd8ce;
border-radius: 10px;
background: #edf4ee;
color: var(--green-dark);
font-size: 12px;
font-weight: 750;
}
.header-balance.bad {
border-color: #e5c4bd;
background: #fff0ec;
color: var(--danger);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 4px rgba(70, 108, 88, 0.11);
}
.ghost-button,
.secondary-button {
border: 1px solid var(--line);
background: var(--panel);
border-radius: 10px;
padding: 10px 13px;
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: transform 140ms ease, background 140ms ease, border-color 140ms ease;
}
.ghost-button:hover,
.secondary-button:hover {
transform: translateY(-1px);
border-color: #aeb8b0;
background: #fff;
}
.workspace {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 300px minmax(420px, 1fr) 342px;
}
.panel {
min-height: 0;
overflow-y: auto;
padding: 22px;
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #c9cec8 transparent;
}
.recipe-panel {
border-right: 1px solid var(--line);
}
.demand-panel {
border-left: 1px solid var(--line);
}
.eyebrow {
margin-bottom: 7px;
color: var(--green);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1,
h2,
h3,
p {
margin-top: 0;
}
h2 {
margin-bottom: 7px;
font-size: 23px;
line-height: 1.08;
letter-spacing: -0.045em;
}
.intro {
margin-bottom: 20px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.batch-card {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 19px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: #f7f5ef;
}
.batch-card span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.batch-card strong {
font-size: 17px;
letter-spacing: -0.03em;
}
.batch-chip {
padding: 7px 9px;
border-radius: 8px;
background: var(--ink);
color: white;
font-size: 11px;
font-weight: 800;
}
.fraction {
margin-bottom: 17px;
}
.fraction-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
font-size: 12px;
font-weight: 800;
}
.fraction-name {
display: flex;
align-items: center;
gap: 8px;
}
.color-dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--accent);
box-shadow: inset 0 -2px 0 rgba(0, 0, 0, 0.12);
}
.fraction-inputs {
display: grid;
grid-template-columns: 1fr 66px;
align-items: center;
gap: 10px;
}
input[type="range"] {
width: 100%;
accent-color: var(--accent);
cursor: pointer;
}
.number-wrap {
position: relative;
}
.number-wrap input {
width: 100%;
padding: 8px 24px 8px 9px;
border: 1px solid var(--line);
border-radius: 8px;
background: #fbfaf6;
color: var(--ink);
font-size: 12px;
font-weight: 800;
outline: none;
}
.number-wrap input:focus {
border-color: var(--green);
box-shadow: 0 0 0 3px rgba(70, 108, 88, 0.1);
}
.number-wrap::after {
content: "%";
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
color: var(--muted);
font-size: 10px;
pointer-events: none;
}
.fraction-preview {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
text-align: right;
}
.sum-row {
display: flex;
align-items: center;
justify-content: space-between;
margin: 5px 0 13px;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: #faf9f4;
}
.sum-row span {
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
.sum-badge {
padding: 5px 8px;
border-radius: 7px;
background: var(--green-soft);
color: var(--green-dark);
font-size: 11px;
font-weight: 850;
}
.sum-badge.invalid {
background: #f9e4de;
color: var(--danger);
}
.primary-button {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
padding: 13px 15px;
border: 0;
border-radius: 11px;
background: var(--green-dark);
color: white;
cursor: pointer;
font-size: 12px;
font-weight: 850;
box-shadow: 0 8px 18px rgba(41, 77, 61, 0.18);
transition: transform 140ms ease, opacity 140ms ease, background 140ms ease;
}
.primary-button:hover:not(:disabled) {
transform: translateY(-2px);
background: #1f4435;
}
.primary-button:disabled {
opacity: 0.45;
cursor: not-allowed;
box-shadow: none;
}
.run-icon {
font-size: 10px;
}
.text-button {
width: 100%;
margin-top: 9px;
padding: 8px;
border: 0;
background: transparent;
color: var(--green);
cursor: pointer;
font-size: 11px;
font-weight: 800;
}
.tip {
margin-top: 20px;
padding: 13px;
border: 1px dashed #bfc9c0;
border-radius: 11px;
background: #f4f7f2;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.tip strong {
color: var(--ink);
}
.stage {
position: relative;
min-width: 0;
min-height: 560px;
overflow: hidden;
background: #e8e4d9;
}
#scene {
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
outline: none;
}
#scene:active {
cursor: grabbing;
}
.stage-top {
position: absolute;
top: 18px;
left: 18px;
right: 18px;
display: flex;
align-items: flex-start;
justify-content: space-between;
pointer-events: none;
}
.scene-tag {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border: 1px solid rgba(23, 37, 31, 0.1);
border-radius: 9px;
background: rgba(255, 253, 248, 0.87);
backdrop-filter: blur(8px);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.scene-tag .status-dot {
width: 6px;
height: 6px;
color: var(--green);
background: var(--green);
box-shadow: 0 0 0 3px rgba(70, 108, 88, 0.12);
}
.scene-note {
max-width: 210px;
padding: 9px 11px;
border-radius: 9px;
background: rgba(23, 37, 31, 0.84);
color: white;
font-size: 10px;
font-weight: 650;
line-height: 1.45;
text-align: right;
}
.stage-bottom {
position: absolute;
left: 18px;
right: 18px;
bottom: 17px;
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 12px;
pointer-events: none;
}
.control-hints {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.control-hints span {
padding: 7px 9px;
border: 1px solid rgba(23, 37, 31, 0.1);
border-radius: 8px;
background: rgba(255, 253, 248, 0.84);
color: #536058;
font-size: 9px;
font-weight: 750;
backdrop-filter: blur(8px);
}
.scene-caption {
color: rgba(23, 37, 31, 0.63);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-align: right;
text-transform: uppercase;
}
.toast {
position: absolute;
left: 50%;
bottom: 72px;
z-index: 5;
max-width: min(460px, calc(100% - 32px));
padding: 11px 15px;
border-radius: 10px;
background: var(--ink);
color: white;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
line-height: 1.4;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition: opacity 180ms ease, transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.error {
background: #8f4437;
}
.order-summary {
margin-bottom: 16px;
padding: 14px;
border-radius: 13px;
background: var(--green-dark);
color: white;
}
.summary-top {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
}
.summary-top span {
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
opacity: 0.72;
}
.summary-top strong {
font-size: 18px;
letter-spacing: -0.04em;
}
.progress-track {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.17);
}
.progress-fill {
height: 100%;
width: 0;
border-radius: inherit;
background: #f0c66f;
transition: width 280ms ease;
}
.inventory-label {
margin: 18px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.inventory-list {
display: grid;
gap: 7px;
}
.inventory-row {
width: 100%;
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 10px;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fbfaf6;
cursor: pointer;
text-align: left;
transition: border-color 140ms ease, background 140ms ease, transform 140ms ease;
}
.inventory-row:hover {
transform: translateY(-1px);
border-color: #aab6ad;
}
.inventory-row.active {
border-color: var(--green);
background: var(--green-soft);
box-shadow: inset 3px 0 0 var(--green);
}
.inventory-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 11px;
font-weight: 800;
}
.inventory-name small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 650;
}
.inventory-weight {
font-size: 13px;
font-weight: 850;
}
.route-strip {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 11px 0 18px;
padding: 10px 11px;
border: 1px dashed #b8c1ba;
border-radius: 10px;
background: #f7f8f3;
font-size: 10px;
color: var(--muted);
}
.route-strip strong {
color: var(--ink);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin: 20px 0 10px;
}
.section-heading h3 {
margin: 0;
font-size: 13px;
letter-spacing: -0.02em;
}
.section-heading span {
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.demand-list {
display: grid;
gap: 9px;
}
.demand-card {
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fbfaf6;
transition: border-color 140ms ease, transform 140ms ease;
}
.demand-card:hover {
transform: translateY(-1px);
border-color: #b7c0b9;
}
.demand-card.fulfilled {
background: #f0f5ef;
border-color: #bdd0bf;
}
.demand-top {
display: grid;
grid-template-columns: 34px 1fr auto;
align-items: center;
gap: 9px;
}
.demand-icon {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border-radius: 9px;
background: var(--accent);
color: white;
font-size: 12px;
font-weight: 900;
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.12);
}
.demand-name {
font-size: 11px;
font-weight: 850;
}
.demand-note {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.demand-amount {
text-align: right;
font-size: 11px;
font-weight: 850;
}
.demand-amount small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
text-transform: uppercase;
}
.demand-progress {
height: 4px;
margin: 10px 0 9px;
overflow: hidden;
border-radius: 99px;
background: #e3e3db;
}
.demand-progress span {
display: block;
height: 100%;
width: 0;
border-radius: inherit;
background: var(--accent);
transition: width 220ms ease;
}
.route-button {
width: 100%;
padding: 8px;
border: 1px solid #ccd2cc;
border-radius: 8px;
background: white;
cursor: pointer;
font-size: 10px;
font-weight: 850;
transition: background 140ms ease, transform 140ms ease;
}
.route-button:hover:not(:disabled) {
transform: translateY(-1px);
background: #f0f5ef;
}
.route-button:disabled {
opacity: 0.46;
cursor: not-allowed;
}
.accounting {
margin-top: 20px;
padding: 14px;
border: 1px solid #cbd8ce;
border-radius: 13px;
background: #edf4ee;
}
.accounting-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.accounting-head strong {
font-size: 12px;
}
.balance-badge {
padding: 5px 7px;
border-radius: 7px;
background: var(--green-dark);
color: white;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
}
.balance-badge.bad {
background: var(--danger);
}
.mass-bar {
height: 9px;
display: flex;
overflow: hidden;
border-radius: 99px;
background: #d7e0d8;
margin-bottom: 12px;
}
.mass-bar span {
height: 100%;
transition: width 220ms ease;
}
.mass-bar .waiting {
background: var(--amber);
}
.mass-bar .delivered {
background: var(--green);
}
.mass-bar .wip {
background: #7b8e82;
}
.account-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px 0;
color: var(--muted);
font-size: 10px;
}
.account-row strong {
color: var(--ink);
font-size: 11px;
}
.equation {
margin-top: 9px;
padding-top: 10px;
border-top: 1px solid #cbd8ce;
color: var(--green-dark);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
line-height: 1.6;
}
.unaccounted {
margin-top: 6px;
color: var(--green-dark);
font-size: 9px;
font-weight: 800;
}
.modal {
position: fixed;
inset: 0;
z-index: 100;
display: none;
align-items: center;
justify-content: center;
padding: 20px;
background: rgba(15, 26, 21, 0.55);
backdrop-filter: blur(5px);
}
.modal.open {
display: flex;
}
.modal-card {
width: min(470px, 100%);
padding: 24px;
border: 1px solid rgba(255, 255, 255, 0.25);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 30px 80px rgba(0, 0, 0, 0.3);
}
.modal-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 15px;
}
.modal-head h2 {
margin: 0;
}
.close-button {
width: 32px;
height: 32px;
border: 0;
border-radius: 8px;
background: #ecebe4;
cursor: pointer;
font-weight: 900;
}
.help-list {
display: grid;
gap: 13px;
counter-reset: help;
}
.help-item {
display: grid;
grid-template-columns: 28px 1fr;
gap: 10px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.help-item::before {
counter-increment: help;
content: counter(help);
width: 26px;
height: 26px;
display: grid;
place-items: center;
border-radius: 7px;
background: var(--green-soft);
color: var(--green-dark);
font-size: 10px;
font-weight: 900;
}
.help-item strong {
color: var(--ink);
}
@media (max-width: 1120px) {
body {
overflow: auto;
}
.workspace {
grid-template-columns: 280px minmax(420px, 1fr);
}
.stage {
min-height: 680px;
}
.demand-panel {
grid-column: 1 / -1;
border-top: 1px solid var(--line);
border-left: 0;
}
.demand-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 720px) {
header {
height: auto;
min-height: 68px;
padding: 12px 14px;
}
.brand-subtitle,
.header-balance {
display: none;
}
.workspace {
display: flex;
flex-direction: column;
}
.recipe-panel {
border-right: 0;
border-bottom: 1px solid var(--line);
}
.stage {
height: 560px;
min-height: 560px;
}
.demand-panel {
border-left: 0;
}
.demand-list {
grid-template-columns: 1fr;
}
.scene-note {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="voxel-logo" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<div>
<div class="brand-title">Grain Route</div>
<div class="brand-subtitle">Voxel milling lab</div>
</div>
</div>
<div class="header-actions">
<div class="header-balance" id="headerBalance">
<span class="status-dot"></span>
<span id="headerBalanceText">0.0 kg unaccounted</span>
</div>
<button class="ghost-button" id="resetView">Reset view</button>
<button class="ghost-button" id="helpButton">How to play</button>
</div>
</header>
<main class="workspace">
<aside class="panel recipe-panel">
<div class="eyebrow">01 / Declare the split</div>
<h2>Set your recipe</h2>
<p class="intro">
Every kilogram leaving the mill is assigned to a declared product.
The fractions must total 100%.
</p>
<div class="batch-card">
<div>
<span>Batch size</span>
<strong>60 kg grain</strong>
</div>
<div class="batch-chip">1 DAY</div>
</div>
<div class="fraction" style="--accent: var(--amber)">
<div class="fraction-head">
<div class="fraction-name">
<span class="color-dot"></span>
Fine flour
</div>
</div>
<div class="fraction-inputs">
<input
class="frac-range"
data-product="flour"
type="range"
min="0"
max="100"
step="1"
value="60"
aria-label="Fine flour percentage"
/>
<div class="number-wrap">
<input
class="frac-number"
data-product="flour"
type="number"
min="0"
max="100"
step="1"
value="60"
aria-label="Fine flour numeric percentage"
/>
</div>
</div>
<div class="fraction-preview" id="preview-flour">36.0 kg per batch</div>
</div>
<div class="fraction" style="--accent: var(--brown)">
<div class="fraction-head">
<div class="fraction-name">
<span class="color-dot"></span>
Husk / bran
</div>
</div>
<div class="fraction-inputs">
<input
class="frac-range"
data-product="bran"
type="range"
min="0"
max="100"
step="1"
value="15"
aria-label="Bran percentage"
/>
<div class="number-wrap">
<input
class="frac-number"
data-product="bran"
type="number"
min="0"
max="100"
step="1"
value="15"
aria-label="Bran numeric percentage"
/>
</div>
</div>
<div class="fraction-preview" id="preview-bran">9.0 kg per batch</div>
</div>
<div class="fraction" style="--accent: var(--meal)">
<div class="fraction-head">
<div class="fraction-name">
<span class="color-dot"></span>
Whole meal
</div>
</div>
<div class="fraction-inputs">
<input
class="frac-range"
data-product="meal"
type="range"
min="0"
max="100"
step="1"
value="25"
aria-label="Whole meal percentage"
/>
<div class="number-wrap">
<input
class="frac-number"
data-product="meal"
type="number"
min="0"
max="100"
step="1"
value="25"
aria-label="Whole meal numeric percentage"
/>
</div>
</div>
<div class="fraction-preview" id="preview-meal">15.0 kg per batch</div>
</div>
<div class="sum-row">
<span>Declared total</span>
<span class="sum-badge" id="sumBadge">100%</span>
</div>
<button class="primary-button" id="runButton">
<span class="run-icon">▶</span>
<span id="runButtonText">Mill 60 kg</span>
</button>
<button class="text-button" id="balanceButton">Auto-balance recipe to 100%</button>
<div class="tip">
<strong>Material rule:</strong> routed grain moves from “waiting” to
“delivered.” Nothing can be deleted, so the mass ledger always balances.
</div>
</aside>
<section class="stage" id="stage">
<canvas id="scene" aria-label="Interactive voxel milling system"></canvas>
<div class="stage-top">
<div class="scene-tag">
<span class="status-dot"></span>
Live milling floor
</div>
<div class="scene-note">
Click a colored output bin to select it, then route it to a demand card.
</div>
</div>
<div class="stage-bottom">
<div class="control-hints">
<span>Drag to orbit</span>
<span>Scroll to zoom</span>
<span>1 / 2 / 3 select output</span>
</div>
<div class="scene-caption">Block mill / district 07</div>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
</section>
<aside class="panel demand-panel">
<div class="eyebrow">02 / Route the output</div>
<h2>Demand cards</h2>
<p class="intro">
Select an output, then send five kilograms at a time to an eligible use.
</p>
<div class="order-summary">
<div class="summary-top">
<span>Orders fulfilled</span>
<strong id="fulfillmentText">0 / 60 kg</strong>
</div>
<div class="progress-track">
<div class="progress-fill" id="fulfillmentFill"></div>
</div>
</div>
<div class="inventory-label">Waiting at the mill</div>
<div class="inventory-list" id="inventoryList"></div>
<div class="route-strip">
<span>Selected output</span>
<strong id="selectedOutputText">Fine flour</strong>
</div>
<div class="section-heading">
<h3>Active demand</h3>
<span>Route in 5 kg blocks</span>
</div>
<div class="demand-list" id="demandList"></div>
<section class="accounting" aria-label="Mass accounting display">
<div class="accounting-head">
<strong>Mass ledger</strong>
<span class="balance-badge" id="balanceBadge">BALANCED</span>
</div>
<div class="mass-bar" aria-hidden="true">
<span class="waiting" id="barWaiting"></span>
<span class="delivered" id="barDelivered"></span>
<span class="wip" id="barWip"></span>
</div>
<div class="account-row">
<span>Waiting output</span>
<strong id="waitingMass">0.0 kg</strong>
</div>
<div class="account-row">
<span>Delivered</span>
<strong id="deliveredMass">0.0 kg</strong>
</div>
<div class="account-row">
<span>In the mill</span>
<strong id="wipMass">0.0 kg</strong>
</div>
<div class="equation" id="balanceEquation">
0.0 processed = 0.0 waiting + 0.0 delivered + 0.0 in mill
</div>
<div class="unaccounted" id="unaccountedText">
0.0 kg unaccounted — ledger verified
</div>
</section>
</aside>
</main>
</div>
<div class="modal" id="helpModal" role="dialog" aria-modal="true" aria-labelledby="helpTitle">
<div class="modal-card">
<div class="modal-head">
<h2 id="helpTitle">How the mill works</h2>
<button class="close-button" id="closeHelp" aria-label="Close help">×</button>
</div>
<div class="help-list">
<div class="help-item">
<div><strong>Declare the split.</strong> Adjust the three product fractions until they total 100%, then mill a 60 kg batch.</div>
</div>
<div class="help-item">
<div><strong>Select an output.</strong> Click a colored bin or use the inventory list. Keyboard keys 1, 2, and 3 also work.</div>
</div>
<div class="help-item">
<div><strong>Fill demand cards.</strong> Route 5 kg from the selected output to an eligible card. The overflow shelf accepts any product.</div>
</div>
<div class="help-item">
<div><strong>Trust the ledger.</strong> Grain is only moved between “waiting,” “delivered,” and “in mill.” Unaccounted mass must always be zero.</div>
</div>
</div>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
const fmt = (value) => Number(value).toFixed(1);
const PRODUCTS = {
flour: {
label: "Fine flour",
short: "FLOUR",
css: "#d79a35",
color: 0xe3ad46,
key: "1"
},
bran: {
label: "Husk / bran",
short: "BRAN",
css: "#ae6540",
color: 0xa85f3c,
key: "2"
},
meal: {
label: "Whole meal",
short: "MEAL",
css: "#c49a68",
color: 0xc39764,
key: "3"
}
};
const PRODUCT_KEYS = Object.keys(PRODUCTS);
const BATCH_SIZE = 60;
const ROUTE_SIZE = 5;
const state = {
fractions: { flour: 60, bran: 15, meal: 25 },
inventory: { flour: 0, bran: 0, meal: 0 },
selected: "flour",
inputProcessed: 0,
delivered: 0,
wip: 0,
processing: false,
runStarted: 0,
outputParticlesSpawned: false,
lastFeedParticle: 0,
demands: [
{
id: "bakery",
name: "Village bakery",
note: "Fresh daily loaves",
product: "flour",
need: 26,
received: 0,
icon: "B"
},
{
id: "cereal",
name: "Breakfast co-op",
note: "Bran for oat clusters",
product: "bran",
need: 9,
received: 0,
icon: "C"
},
{
id: "home",
name: "Family kitchens",
note: "Everyday household flour",
product: "flour",
need: 10,
received: 0,
icon: "H"
},
{
id: "feed",
name: "Livestock feed",
note: "Whole-meal ration",
product: "meal",
need: 15,
received: 0,
icon: "F"
},
{
id: "overflow",
name: "Overflow shelf",
note: "Open local use · accepts any product",
product: null,
need: 0,
received: 0,
icon: "O",
any: true
}
]
};
const canvas = $("#scene");
const stage = $("#stage");
const scene3d = new THREE.Scene();
scene3d.background = new THREE.Color(0xe8e4d9);
scene3d.fog = new THREE.Fog(0xe8e4d9, 16, 30);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
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;
const hemisphere = new THREE.HemisphereLight(0xfff8e7, 0x758177, 2.3);
scene3d.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d2, 3.1);
sun.position.set(-6, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0005;
scene3d.add(sun);
const fillLight = new THREE.DirectionalLight(0xb9d2e0, 0.7);
fillLight.position.set(8, 5, -8);
scene3d.add(fillLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(32, 32),
new THREE.MeshStandardMaterial({
color: 0xd8d4c8,
roughness: 0.96,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.015;
floor.receiveShadow = true;
scene3d.add(floor);
const grid = new THREE.GridHelper(28, 28, 0x87968b, 0xb9beb5);
grid.position.y = 0.005;
grid.material.transparent = true;
grid.material.opacity = 0.3;
scene3d.add(grid);
const interactiveMeshes = [];
const effects = [];
const stockGroups = {};
const stockMaterials = {};
const productLabels = {};
const controlButtons = {};
PRODUCT_KEYS.forEach((key) => {
stockMaterials[key] = new THREE.MeshStandardMaterial({
color: PRODUCTS[key].color,
roughness: 0.78,
metalness: 0.02
});
stockGroups[key] = new THREE.Group();
scene3d.add(stockGroups[key]);
});
function addBox(parent, width, height, depth, color, x, y, z, options = {}) {
const material =
options.material ||
new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.78,
metalness: options.metalness ?? 0.03
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow !== false;
mesh.receiveShadow = options.receiveShadow !== false;
parent.add(mesh);
return mesh;
}
function markInteractive(mesh, product) {
mesh.userData.product = product;
interactiveMeshes.push(mesh);
return mesh;
}
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeTextSprite(initialText, accent = "#d79a35", width = 512, height = 144) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = width;
labelCanvas.height = height;
const context = labelCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: true
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(2.25, 0.63, 1);
function update(text, textColor = "#ffffff") {
context.clearRect(0, 0, width, height);
context.fillStyle = "rgba(23, 37, 31, 0.92)";
roundedRect(context, 5, 5, width - 10, height - 10, 22);
context.fill();
context.fillStyle = accent;
roundedRect(context, 18, 25, 10, height - 50, 5);
context.fill();
const lines = text.split("\n");
context.textAlign = "center";
context.textBaseline = "middle";
if (lines.length === 1) {
context.fillStyle = textColor;
context.font = "800 34px system-ui, sans-serif";
context.fillText(lines[0], width / 2 + 5, height / 2);
} else {
context.fillStyle = textColor;
context.font = "850 31px system-ui, sans-serif";
context.fillText(lines[0], width / 2 + 5, height / 2 - 23);
context.fillStyle = accent;
context.font = "800 25px system-ui, sans-serif";
context.fillText(lines[1], width / 2 + 5, height / 2 + 25);
}
texture.needsUpdate = true;
}
update(initialText);
return { sprite, update };
}
// Machine foundation and body.
addBox(scene3d, 4.2, 0.34, 2.9, 0x36483f, -1.8, 0.16, 0);
addBox(scene3d, 3.45, 0.18, 2.45, 0x52665c, -1.8, 0.39, 0);
[-3.1, -0.5].forEach((x) => {
[-0.85, 0.85].forEach((z) => {
addBox(scene3d, 0.28, 0.62, 0.28, 0x263a31, x, 0.66, z);
});
});
addBox(scene3d, 3.05, 2.25, 2.15, 0x3e5148, -1.8, 2.05, 0);
addBox(scene3d, 2.65, 1.7, 0.1, 0x182821, -1.8, 2.05, 1.12);
addBox(scene3d, 2.78, 0.16, 0.18, 0x6f8177, -1.8, 2.96, 1.15);
addBox(scene3d, 0.16, 1.7, 0.18, 0x6f8177, -3.11, 2.05, 1.15);
addBox(scene3d, 0.16, 1.7, 0.18, 0x6f8177, -0.49, 2.05, 1.15);
// Chute neck and voxel hopper.
addBox(scene3d, 1.05, 0.7, 1.05, 0x596c61, -1.8, 3.4, 0);
addBox(scene3d, 2.35, 0.45, 1.95, 0x4b6155, -1.8, 3.91, 0);
addBox(scene3d, 0.22, 0.75, 2.15, 0x5e7368, -2.96, 4.12, 0);
addBox(scene3d, 0.22, 0.75, 2.15, 0x5e7368, -0.64, 4.12, 0);
addBox(scene3d, 2.5, 0.75, 0.22, 0x5e7368, -1.8, 4.12, -0.97);
addBox(scene3d, 2.5, 0.75, 0.22, 0x5e7368, -1.8, 4.12, 0.97);
addBox(scene3d, 2.7, 0.18, 2.3, 0x6f8277, -1.8, 4.53, 0);
const grainMaterial = new THREE.MeshStandardMaterial({
color: 0xd5a84e,
roughness: 0.88
});
for (let i = 0; i < 18; i++) {
const x = -2.72 + (i % 5) * 0.43 + (Math.floor(i / 5) % 2) * 0.12;
const z = -0.58 + Math.floor(i / 10) * 0.52 + (i % 3) * 0.08;
addBox(scene3d, 0.32, 0.26, 0.32, 0, x, 4.72 + (i % 2) * 0.03, z, {
material: grainMaterial
});
}
// Visible cutting rotor.
const rotor = new THREE.Group();
rotor.position.set(-1.8, 2.05, 1.28);
scene3d.add(rotor);
for (let i = 0; i < 8; i++) {
const angle = (i / 8) * Math.PI * 2;
const blade = addBox(
rotor,
0.48,
0.26,
0.3,
i % 2 === 0 ? 0xb2beb4 : 0x85978b,
Math.cos(angle) * 0.52,
Math.sin(angle) * 0.52,
0
);
blade.rotation.z = angle + 0.35;
}
addBox(rotor, 0.48, 0.48, 0.38, 0xd8b54e, 0, 0, 0.1);
// Control panel and output-selection buttons.
addBox(scene3d, 1.25, 0.65, 0.14, 0x172821, -1.8, 1.05, 1.16);
addBox(scene3d, 0.68, 0.27, 0.06, 0x8bc8a5, -1.8, 1.19, 1.25);
PRODUCT_KEYS.forEach((key, index) => {
const x = -2.2 + index * 0.4;
const material = new THREE.MeshStandardMaterial({
color: PRODUCTS[key].color,
emissive: 0x000000,
emissiveIntensity: 0.7,
roughness: 0.55
});
const button = addBox(scene3d, 0.27, 0.18, 0.12, 0, x, 0.9, 1.27, {
material
});
controlButtons[key] = button;
markInteractive(button, key);
});
// Conveyor and roller blocks.
addBox(scene3d, 5.15, 0.13, 0.16, 0x65786d, 2.72, 1.77, -0.52);
addBox(scene3d, 5.15, 0.13, 0.16, 0x65786d, 2.72, 1.77, 0.52);
addBox(scene3d, 0.32, 0.4, 1.15, 0x52675b, 0.18, 2.03, 0);
for (let i = 0; i < 11; i++) {
const roller = addBox(
scene3d,
0.32,
0.18,
0.86,
i % 2 ? 0x788a7e : 0x87998d,
0.48 + i * 0.46,
1.65,
0
);
roller.rotation.y = Math.PI / 2;
}
const BIN_X = {
flour: 1.65,
bran: 3.25,
meal: 4.85
};
const binGroups = {};
PRODUCT_KEYS.forEach((key) => {
const x = BIN_X[key];
const group = new THREE.Group();
group.position.set(x, 0, 0.35);
scene3d.add(group);
binGroups[key] = group;
const base = addBox(group, 1.48, 0.34, 1.52, 0x43574c, 0, 0.48, 0);
markInteractive(base, key);
addBox(group, 1.48, 0.7, 0.13, 0x6a7d71, 0, 0.85, -0.69);
addBox(group, 0.13, 0.7, 1.3, 0x6a7d71, -0.675, 0.85, 0);
addBox(group, 0.13, 0.7, 1.3, 0x6a7d71, 0.675, 0.85, 0);
const strip = addBox(
group,
1.2,
0.16,
0.08,
0,
0,
0.74,
0.72,
{ material: stockMaterials[key] }
);
markInteractive(strip, key);
const support = addBox(group, 0.18, 0.45, 0.18, 0x43574c, -0.47, 0.18, -0.4);
support.castShadow = true;
addBox(group, 0.18, 0.45, 0.18, 0x43574c, 0.47, 0.18, -0.4);
// Colored chute from conveyor to output.
for (let i = 0; i < 3; i++) {
const chute = addBox(
scene3d,
0.44,
0.17,
0.62,
0,
x,
1.48 - i * 0.13,
-0.08 + i * 0.18,
{ material: stockMaterials[key] }
);
chute.rotation.x = -0.12;
}
const label = makeTextSprite(
`${PRODUCTS[key].short}\n0.0 kg waiting`,
PRODUCTS[key].css
);
label.sprite.position.set(x, 0.18, -0.68);
scene3d.add(label.sprite);
productLabels[key] = label;
stockGroups[key].position.set(x, 0, 0.35);
});
// Machine label.
const millLabel = makeTextSprite("BLOCK MILL 60", "#8fc29f");
millLabel.sprite.scale.set(2.25, 0.58, 1);
millLabel.sprite.position.set(-1.8, 5.03, 0);
scene3d.add(millLabel.sprite);
// Selection frame around active bin.
const selectionFrame = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1.57, 1.55, 1.58)),
new THREE.LineBasicMaterial({
color: 0xf8f4e8,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
selectionFrame.position.set(BIN_X.flour, 1.02, 0.35);
selectionFrame.renderOrder = 20;
scene3d.add(selectionFrame);
// Small voxel pointer above selected output.
const pointer = new THREE.Group();
addBox(pointer, 0.18, 0.4, 0.18, 0xf7f3e8, 0, 0.2, 0);
addBox(pointer, 0.45, 0.18, 0.18, 0xf7f3e8, 0, -0.04, 0);
addBox(pointer, 0.7, 0.15, 0.18, 0xf7f3e8, 0, -0.22, 0);
pointer.position.set(BIN_X.flour, 2.14, 0.35);
scene3d.add(pointer);
// Camera controls implemented directly.
const cameraState = {
theta: 0.67,
phi: 1.04,
radius: 13.6,
target: new THREE.Vector3(0.85, 2.05, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.cos(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.sin(theta)
);
camera.lookAt(target);
}
function resetView() {
cameraState.theta = 0.67;
cameraState.phi = 1.04;
cameraState.radius = 13.6;
cameraState.target.set(0.85, 2.05, 0);
updateCamera();
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
let dragging = false;
let movedDistance = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function setRayFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointerNdc.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNdc.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNdc, camera);
}
function pickedProduct(event) {
setRayFromEvent(event);
const hits = raycaster.intersectObjects(interactiveMeshes, false);
return hits.length ? hits[0].object.userData.product : null;
}
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
movedDistance = 0;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", (event) => {
if (dragging) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
movedDistance += Math.abs(dx) + Math.abs(dy);
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(cameraState.phi - dy * 0.005, 0.55, 1.34);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
} else {
canvas.style.cursor = pickedProduct(event) ? "pointer" : "grab";
}
});
canvas.addEventListener("pointerup", (event) => {
dragging = false;
canvas.style.cursor = "grab";
if (movedDistance < 6) {
const product = pickedProduct(event);
if (product) selectProduct(product);
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
canvas.style.cursor = "grab";
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(cameraState.radius + event.deltaY * 0.009, 8.5, 19);
updateCamera();
},
{ passive: false }
);
function resizeRenderer() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
resizeRenderer();
function selectProduct(product) {
if (!PRODUCTS[product]) return;
state.selected = product;
renderUI();
}
function updateSelectionVisuals() {
selectionFrame.position.x = BIN_X[state.selected];
pointer.position.x = BIN_X[state.selected];
PRODUCT_KEYS.forEach((key) => {
const selected = key === state.selected;
controlButtons[key].material.emissive.setHex(selected ? 0xffffff : 0x000000);
controlButtons[key].material.emissiveIntensity = selected ? 0.42 : 0;
controlButtons[key].scale.setScalar(selected ? 1.18 : 1);
});
}
function rebuildStockVisuals() {
PRODUCT_KEYS.forEach((key) => {
const group = stockGroups[key];
while (group.children.length) {
const child = group.children[0];
group.remove(child);
child.geometry.dispose();
}
const kilograms = state.inventory[key];
const blockCount = Math.ceil(Math.max(0, kilograms) / ROUTE_SIZE - 0.000001);
for (let i = 0; i < blockCount; i++) {
const amount = Math.min(
ROUTE_SIZE,
Math.max(0, kilograms - i * ROUTE_SIZE)
);
if (amount <= 0.001) continue;
const layer = Math.floor(i / 6);
const withinLayer = i % 6;
const column = withinLayer % 3;
const row = Math.floor(withinLayer / 3);
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.3, 0.3, 0.3),
stockMaterials[key]
);
const scaleY = amount / ROUTE_SIZE;
block.scale.set(1, Math.max(0.12, scaleY), 1);
block.position.set(
(column - 1) * 0.34,
0.63 + layer * 0.31 + 0.15 * Math.max(0.12, scaleY),
(row - 0.5) * 0.37
);
block.rotation.y = ((i % 3) - 1) * 0.035;
block.castShadow = true;
block.receiveShadow = true;
group.add(block);
}
});
}
function updateProductLabels() {
PRODUCT_KEYS.forEach((key) => {
productLabels[key].update(
`${PRODUCTS[key].short}\n${fmt(state.inventory[key])} kg waiting`
);
});
}
const effectGeometry = new THREE.BoxGeometry(0.28, 0.28, 0.28);
function spawnFeedParticle(now) {
const mesh = new THREE.Mesh(effectGeometry, grainMaterial);
scene3d.add(mesh);
const from = new THREE.Vector3(
-1.8 + (Math.random() - 0.5) * 0.8,
4.45,
(Math.random() - 0.5) * 0.65
);
const to = new THREE.Vector3(
-1.8 + (Math.random() - 0.5) * 0.25,
2.9,
0.5
);
effects.push({
mesh,
from,
to,
start: now,
duration: 650,
arc: 0.2,
spin: 0.08
});
}
function spawnOutputParticles(now) {
PRODUCT_KEYS.forEach((key) => {
const quantity = (state.fractions[key] / 100) * BATCH_SIZE;
const count = Math.ceil(quantity / ROUTE_SIZE - 0.000001);
for (let i = 0; i < count; i++) {
const mesh = new THREE.Mesh(effectGeometry, stockMaterials[key]);
scene3d.add(mesh);
const from = new THREE.Vector3(0.18, 2.15, 0.45);
const to = new THREE.Vector3(
BIN_X[key] + (Math.random() - 0.5) * 0.35,
1.2 + Math.random() * 0.12,
0.35 + (Math.random() - 0.5) * 0.35
);
effects.push({
mesh,
from,
to,
start: now + i * 25,
duration: 950 + Math.random() * 300,
arc: 1.05,
spin: 0.055
});
}
});
}
function spawnTransferLabel(product) {
const label = makeTextSprite(`+${ROUTE_SIZE} KG`, PRODUCTS[product].css, 384, 128);
label.sprite.scale.set(1.6, 0.53, 1);
scene3d.add(label.sprite);
const from = new THREE.Vector3(BIN_X[product], 1.9, 0.35);
const to = from.clone().add(new THREE.Vector3(0, 1.1, 0));
effects.push({
mesh: label.sprite,
from,
to,
start: performance.now(),
duration: 850,
arc: 0.15,
spin: 0,
floatingLabel: true
});
}
function updateEffects(now) {
for (let i = effects.length - 1; i >= 0; i--) {
const effect = effects[i];
const progress = clamp(
(now - effect.start) / effect.duration,
0,
1
);
if (progress >= 1) {
scene3d.remove(effect.mesh);
if (effect.floatingLabel) {
effect.mesh.material.map.dispose();
effect.mesh.material.dispose();
}
effects.splice(i, 1);
continue;
}
effect.mesh.position.lerpVectors(effect.from, effect.to, progress);
effect.mesh.position.y += Math.sin(progress * Math.PI) * effect.arc;
effect.mesh.rotation.y += effect.spin;
if (effect.floatingLabel) {
effect.mesh.material.opacity = 1 - progress;
}
}
}
function showToast(message, type = "") {
const toast = $("#toast");
toast.textContent = message;
toast.className = `toast show ${type}`;
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => {
toast.className = "toast";
}, 2600);
}
function runMill() {
const total = fractionTotal();
if (total !== 100) {
showToast("The declared fractions must total exactly 100%.", "error");
return;
}
if (state.processing) return;
state.processing = true;
state.runStarted = performance.now();
state.outputParticlesSpawned = false;
state.lastFeedParticle = 0;
state.wip = BATCH_SIZE;
state.inputProcessed += BATCH_SIZE;
renderUI();
showToast("Milling started — 60 kg is now in process.");
}
function completeRun() {
PRODUCT_KEYS.forEach((key) => {
state.inventory[key] +=
(state.fractions[key] / 100) * BATCH_SIZE;
});
state.wip = 0;
state.processing = false;
rebuildStockVisuals();
renderUI();
const summary = PRODUCT_KEYS.map(
(key) => `${fmt(state.inventory[key])} kg ${PRODUCTS[key].short.toLowerCase()}`
).join(", ");
showToast(`Batch complete. Waiting output: ${summary}.`);
}
function routeToDemand(demandId) {
if (state.processing) {
showToast("Wait for the current batch to finish.", "error");
return;
}
const demand = state.demands.find((item) => item.id === demandId);
if (!demand) return;
if (!demand.any && demand.product !== state.selected) {
showToast(
`This card needs ${PRODUCTS[demand.product].label.toLowerCase()}. Select that output first.`,
"error"
);
return;
}
if (!demand.any && demand.received >= demand.need) {
showToast("That demand card is already fulfilled.");
return;
}
if (state.inventory[state.selected] < ROUTE_SIZE) {
showToast(
`There is not enough ${PRODUCTS[state.selected].label.toLowerCase()} waiting to route 5 kg.`,
"error"
);
return;
}
state.inventory[state.selected] -= ROUTE_SIZE;
state.delivered += ROUTE_SIZE;
demand.received += ROUTE_SIZE;
rebuildStockVisuals();
spawnTransferLabel(state.selected);
renderUI();
showToast(
`${ROUTE_SIZE} kg of ${PRODUCTS[state.selected].label.toLowerCase()} routed to ${demand.name.toLowerCase()}.`
);
}
function fractionTotal() {
return PRODUCT_KEYS.reduce(
(total, key) => total + Number(state.fractions[key]),
0
);
}
function syncFractionInputs(product) {
document
.querySelectorAll(`.frac-range[data-product="${product}"]`)
.forEach((input) => {
input.value = state.fractions[product];
});
document
.querySelectorAll(`.frac-number[data-product="${product}"]`)
.forEach((input) => {
input.value = state.fractions[product];
});
}
function updateRecipeUI() {
const total = fractionTotal();
const badge = $("#sumBadge");
badge.textContent = `${fmt(total)}%`;
badge.classList.toggle("invalid", Math.abs(total - 100) > 0.001);
PRODUCT_KEYS.forEach((key) => {
const quantity = (state.fractions[key] / 100) * BATCH_SIZE;
$(`#preview-${key}`).textContent = `${fmt(quantity)} kg per batch`;
});
}
function setFraction(product, value) {
const numeric = Number.isFinite(value) ? value : 0;
state.fractions[product] = clamp(numeric, 0, 100);
syncFractionInputs(product);
updateRecipeUI();
renderUI();
}
function balanceFractions() {
const values = PRODUCT_KEYS.map((key) => Number(state.fractions[key]));
const total = values.reduce((sum, value) => sum + value, 0);
if (total <= 0) {
state.fractions = { flour: 34, bran: 33, meal: 33 };
} else {
const exact = values.map((value) => (value / total) * 100);
const rounded = exact.map(Math.floor);
let remainder = 100 - rounded.reduce((sum, value) => sum + value, 0);
const order = exact
.map((value, index) => ({
index,
fraction: value - Math.floor(value)
}))
.sort((a, b) => b.fraction - a.fraction);
for (let i = 0; i < remainder; i++) {
rounded[order[i % order.length].index] += 1;
}
PRODUCT_KEYS.forEach((key, index) => {
state.fractions[key] = rounded[index];
});
}
PRODUCT_KEYS.forEach(syncFractionInputs);
updateRecipeUI();
renderUI();
showToast("Recipe balanced to 100%.");
}
function renderInventory() {
$("#inventoryList").innerHTML = PRODUCT_KEYS.map((key) => {
const product = PRODUCTS[key];
const active = state.selected === key ? "active" : "";
return `
<button class="inventory-row ${active}" data-product="${key}">
<span class="inventory-name">
<span class="color-dot" style="--accent:${product.css}"></span>
<span>
${product.label}
<small>Click to select</small>
</span>
</span>
<strong class="inventory-weight">${fmt(state.inventory[key])} kg</strong>
</button>
`;
}).join("");
}
function renderDemands() {
$("#demandList").innerHTML = state.demands.map((demand) => {
const product = demand.any
? { css: "#718078", label: "Any output" }
: PRODUCTS[demand.product];
const fulfilled = !demand.any && demand.received >= demand.need;
const progress = demand.any
? Math.min(demand.received / 10, 1)
: Math.min(demand.received / Math.max(demand.need, 1), 1);
const mismatch = !demand.any && demand.product !== state.selected;
const noStock = state.inventory[state.selected] < ROUTE_SIZE;
const disabled =
state.processing ||
fulfilled ||
mismatch ||
noStock;
let buttonText = `Route ${ROUTE_SIZE} kg`;
if (state.processing) buttonText = "Mill is running";
else if (fulfilled) buttonText = "Fulfilled";
else if (mismatch) buttonText = `Needs ${PRODUCTS[demand.product].label.toLowerCase()}`;
else if (noStock) buttonText = `No ${PRODUCTS[state.selected].short.toLowerCase()} waiting`;
return `
<article class="demand-card ${fulfilled ? "fulfilled" : ""}">
<div class="demand-top">
<div class="demand-icon" style="--accent:${product.css}">${demand.icon}</div>
<div>
<div class="demand-name">${demand.name}</div>
<div class="demand-note">${demand.note}</div>
</div>
<div class="demand-amount">
${demand.any ? `${fmt(demand.received)} kg` : `${fmt(demand.received)} / ${demand.need}`}
<small>${demand.any ? "overflow" : "kg received"}</small>
</div>
</div>
<div class="demand-progress">
<span style="width:${progress * 100}%;--accent:${product.css}"></span>
</div>
<button class="route-button" data-demand="${demand.id}" ${disabled ? "disabled" : ""}>
${buttonText}
</button>
</article>
`;
}).join("");
}
function renderAccounting() {
const waiting = PRODUCT_KEYS.reduce(
(sum, key) => sum + state.inventory[key],
0
);
const accounted = waiting + state.delivered + state.wip;
const difference = Math.abs(state.inputProcessed - accounted);
const balanced = difference < 0.001;
$("#waitingMass").textContent = `${fmt(waiting)} kg`;
$("#deliveredMass").textContent = `${fmt(state.delivered)} kg`;
$("#wipMass").textContent = `${fmt(state.wip)} kg`;
$("#balanceEquation").textContent =
`${fmt(state.inputProcessed)} processed = ${fmt(waiting)} waiting + ` +
`${fmt(state.delivered)} delivered + ${fmt(state.wip)} in mill`;
$("#unaccountedText").textContent = balanced
? `${fmt(difference)} kg unaccounted — ledger verified`
: `${fmt(difference)} kg unaccounted — accounting error`;
const badge = $("#balanceBadge");
badge.textContent = balanced ? "BALANCED" : "CHECK LEDGER";
badge.classList.toggle("bad", !balanced);
const headerBalance = $("#headerBalance");
headerBalance.classList.toggle("bad", !balanced);
$("#headerBalanceText").textContent = `${fmt(difference)} kg unaccounted`;
const denominator = Math.max(state.inputProcessed, 1);
$("#barWaiting").style.width = `${(waiting / denominator) * 100}%`;
$("#barDelivered").style.width = `${(state.delivered / denominator) * 100}%`;
$("#barWip").style.width = `${(state.wip / denominator) * 100}%`;
}
function renderUI() {
renderInventory();
renderDemands();
renderAccounting();
updateSelectionVisuals();
updateProductLabels();
const selected = PRODUCTS[state.selected];
$("#selectedOutputText").textContent = selected.label;
const totalNeed = state.demands.reduce(
(sum, demand) => sum + demand.need,
0
);
const totalReceived = state.demands.reduce((sum, demand) => {
if (demand.any) return sum;
return sum + Math.min(demand.received, demand.need);
}, 0);
const percent = totalNeed ? (totalReceived / totalNeed) * 100 : 0;
$("#fulfillmentText").textContent =
`${fmt(totalReceived)} / ${totalNeed} kg`;
$("#fulfillmentFill").style.width = `${percent}%`;
const total = fractionTotal();
$("#runButton").disabled =
Math.abs(total - 100) > 0.001 || state.processing;
$("#runButtonText").textContent = state.processing
? "Milling in progress…"
: "Mill 60 kg";
}
document.querySelectorAll(".frac-range").forEach((input) => {
input.addEventListener("input", () => {
setFraction(input.dataset.product, Number(input.value));
});
});
document.querySelectorAll(".frac-number").forEach((input) => {
input.addEventListener("input", () => {
const value = input.value === "" ? 0 : Number(input.value);
setFraction(input.dataset.product, value);
});
});
$("#balanceButton").addEventListener("click", balanceFractions);
$("#runButton").addEventListener("click", runMill);
$("#resetView").addEventListener("click", resetView);
$("#inventoryList").addEventListener("click", (event) => {
const button = event.target.closest("[data-product]");
if (button) selectProduct(button.dataset.product);
});
$("#demandList").addEventListener("click", (event) => {
const button = event.target.closest("[data-demand]");
if (button && !button.disabled) routeToDemand(button.dataset.demand);
});
$("#helpButton").addEventListener("click", () => {
$("#helpModal").classList.add("open");
});
$("#closeHelp").addEventListener("click", () => {
$("#helpModal").classList.remove("open");
});
$("#helpModal").addEventListener("click", (event) => {
if (event.target === $("#helpModal")) {
$("#helpModal").classList.remove("open");
}
});
window.addEventListener("keydown", (event) => {
if (event.target.matches("input, textarea, select")) return;
if (event.key === "1") selectProduct("flour");
if (event.key === "2") selectProduct("bran");
if (event.key === "3") selectProduct("meal");
if (event.code === "Space") {
event.preventDefault();
runMill();
}
if (event.key === "Escape") {
$("#helpModal").classList.remove("open");
}
});
function animate(now) {
requestAnimationFrame(animate);
if (state.processing) {
const elapsed = now - state.runStarted;
if (elapsed < 1450 && now - state.lastFeedParticle > 105) {
spawnFeedParticle(now);
state.lastFeedParticle = now;
}
if (elapsed > 1450 && !state.outputParticlesSpawned) {
spawnOutputParticles(now);
state.outputParticlesSpawned = true;
}
rotor.rotation.z += 0.17;
if (elapsed >= 2800) {
completeRun();
}
} else {
rotor.rotation.z += 0.025;
}
pointer.position.y = 2.14 + Math.sin(now * 0.003) * 0.07;
pointer.rotation.y = now * 0.0013;
updateEffects(now);
renderer.render(scene3d, camera);
}
updateRecipeUI();
rebuildStockVisuals();
renderUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```