Prompt specification
Build or customize the Three.js 3D scene "Negotiate a shared-water schedule" 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: Negotiate a shared-water schedule
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/negotiate-a-shared-water-schedule-x2380
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing medieval watermills and shared irrigation flows. Let users assign time windows to mill operation and field irrigation in a fictional settlement. Track delivered water and mechanical running time under explicitly stated simplified rules. Voxel style.
Working Three.js Starter (negotiate-a-shared-water-schedule-x2380):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Merebrook Watercommons</title>
<style>
:root {
--ink: #26352f;
--muted: #65746b;
--panel: #f7f3e8;
--paper: #fffdf7;
--line: #d9d1bd;
--green: #497c57;
--green-dark: #315c40;
--blue: #3d91ae;
--gold: #d39b42;
--danger: #b85f4d;
--shadow: 0 12px 34px rgba(37, 51, 43, .14);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: #d9e4d7;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body { overflow: hidden; }
button, input, select { font: inherit; }
button { cursor: pointer; }
#app {
height: 100vh;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
}
header {
z-index: 5;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
min-height: 76px;
padding: 13px 22px;
color: #fffaf0;
background:
linear-gradient(110deg, rgba(31, 60, 43, .98), rgba(51, 93, 61, .96)),
repeating-linear-gradient(90deg, transparent 0 18px, rgba(255,255,255,.05) 18px 19px);
border-bottom: 4px solid #d2ad64;
box-shadow: 0 4px 18px rgba(20, 37, 28, .24);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 43px;
height: 43px;
flex: 0 0 auto;
display: grid;
place-items: center;
border: 2px solid #dfc37e;
background: #294c35;
box-shadow: inset 0 0 0 3px rgba(255,255,255,.08);
font-size: 24px;
}
header h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(20px, 2.4vw, 30px);
letter-spacing: .02em;
line-height: 1.05;
}
.subtitle {
margin-top: 4px;
color: #d7e5d6;
font-size: 12px;
letter-spacing: .08em;
text-transform: uppercase;
}
.header-note {
max-width: 390px;
padding: 8px 12px;
border: 1px solid rgba(255,255,255,.2);
background: rgba(255,255,255,.08);
color: #edf4e8;
font-size: 12px;
line-height: 1.45;
text-align: right;
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #b9d5cf;
}
#sceneCanvas, #sceneCanvas canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
#sceneCanvas canvas { cursor: grab; }
#sceneCanvas canvas.dragging { cursor: grabbing; }
.scene-card {
position: absolute;
z-index: 3;
top: 16px;
left: 16px;
max-width: min(360px, calc(100% - 32px));
padding: 11px 13px;
color: #f9f4e6;
background: rgba(35, 55, 45, .87);
border: 1px solid rgba(255,255,255,.25);
border-radius: 4px;
box-shadow: var(--shadow);
pointer-events: none;
}
.scene-card strong {
display: block;
margin-bottom: 3px;
font-family: Georgia, serif;
font-size: 16px;
letter-spacing: .03em;
}
.scene-card span {
color: #dce9d8;
font-size: 12px;
line-height: 1.4;
}
.camera-tools {
position: absolute;
z-index: 4;
top: 16px;
right: 16px;
display: flex;
gap: 6px;
}
.camera-tools button {
width: 36px;
height: 36px;
border: 1px solid rgba(255,255,255,.4);
border-radius: 4px;
color: white;
background: rgba(39, 60, 48, .84);
box-shadow: 0 4px 12px rgba(25, 39, 31, .2);
font-weight: 800;
}
.camera-tools button:hover { background: rgba(49, 87, 58, .95); }
.legend {
position: absolute;
z-index: 3;
left: 16px;
bottom: 16px;
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
max-width: calc(100% - 32px);
padding: 9px 11px;
color: #31443a;
background: rgba(255, 253, 246, .9);
border: 1px solid rgba(74, 91, 78, .18);
border-radius: 4px;
box-shadow: var(--shadow);
font-size: 11px;
pointer-events: none;
}
.legend span { display: inline-flex; align-items: center; gap: 6px; }
.swatch { width: 10px; height: 10px; display: inline-block; border-radius: 2px; }
#labels {
position: absolute;
inset: 0;
z-index: 2;
overflow: hidden;
pointer-events: none;
}
.scene-label {
position: absolute;
display: flex;
align-items: center;
gap: 6px;
max-width: 170px;
padding: 5px 8px;
color: #26382f;
background: rgba(255, 253, 246, .91);
border: 1px solid rgba(42, 68, 51, .23);
border-radius: 3px;
box-shadow: 0 4px 12px rgba(25, 39, 31, .16);
font-size: 10px;
font-weight: 750;
line-height: 1.15;
text-align: left;
transform: translate(-50%, -100%);
pointer-events: auto;
white-space: nowrap;
}
.scene-label.selected {
color: #fff;
background: #315c40;
border-color: #e2bd69;
box-shadow: 0 0 0 2px rgba(226, 189, 105, .36), 0 5px 15px rgba(25, 39, 31, .22);
}
.scene-label .dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 2px;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 17px;
background:
linear-gradient(rgba(255,255,255,.44), rgba(255,255,255,.44)),
repeating-linear-gradient(0deg, transparent 0 25px, rgba(84, 71, 45, .035) 25px 26px),
var(--panel);
border-left: 1px solid #c9c1ad;
box-shadow: -8px 0 24px rgba(38, 51, 43, .09);
}
.section-heading {
display: flex;
align-items: end;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.section-heading h2 {
margin: 0;
font-family: Georgia, serif;
font-size: 22px;
}
.eyebrow {
color: var(--green-dark);
font-size: 10px;
font-weight: 850;
letter-spacing: .12em;
text-transform: uppercase;
}
#entityButtons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-bottom: 13px;
}
.entity-button {
display: flex;
align-items: center;
gap: 7px;
min-height: 38px;
padding: 7px 8px;
border: 1px solid var(--line);
border-radius: 4px;
color: #34483c;
background: var(--paper);
font-size: 11px;
font-weight: 750;
text-align: left;
}
.entity-button:hover { border-color: #8fa78e; }
.entity-button.active {
color: #fff;
background: var(--green-dark);
border-color: var(--green-dark);
}
.entity-button .swatch {
flex: 0 0 auto;
border: 1px solid rgba(0,0,0,.12);
}
.panel-card {
margin-bottom: 12px;
padding: 12px;
background: var(--paper);
border: 1px solid var(--line);
border-radius: 5px;
box-shadow: 0 4px 12px rgba(49, 59, 50, .05);
}
.selected-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 5px;
}
.selected-title h3 {
margin: 0;
font-family: Georgia, serif;
font-size: 18px;
}
.type-chip {
padding: 3px 7px;
color: #fff;
background: var(--green);
border-radius: 999px;
font-size: 9px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
}
.muted {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#nowState {
margin-top: 9px;
padding: 7px 8px;
color: #385140;
background: #edf3e8;
border-left: 3px solid var(--green);
font-size: 11px;
line-height: 1.35;
}
.window-list {
display: grid;
gap: 6px;
margin: 10px 0;
}
.window-row {
display: grid;
grid-template-columns: 1fr 14px 1fr 28px;
align-items: center;
gap: 4px;
}
.clock-input {
width: 100%;
min-width: 0;
padding: 6px;
border: 1px solid #cfc7b3;
border-radius: 3px;
color: var(--ink);
background: #fffef9;
font-size: 12px;
text-align: center;
}
.window-row .arrow { color: #78857b; text-align: center; }
.remove-window {
width: 28px;
height: 28px;
padding: 0;
border: 1px solid #d9c9ba;
border-radius: 3px;
color: var(--danger);
background: #fff8f1;
font-weight: 900;
}
.empty-note {
padding: 11px;
color: #7a776b;
background: #f1ecdf;
border: 1px dashed #c9bea6;
font-size: 11px;
text-align: center;
}
.add-window {
display: grid;
grid-template-columns: 1fr 14px 1fr auto;
align-items: center;
gap: 4px;
margin-top: 8px;
}
.button {
min-height: 31px;
padding: 6px 10px;
border: 1px solid var(--green-dark);
border-radius: 3px;
color: white;
background: var(--green-dark);
font-size: 11px;
font-weight: 800;
}
.button:hover { background: #244a31; }
.button.secondary {
color: var(--green-dark);
background: #edf2e8;
border-color: #a9bba8;
}
.button.danger {
color: #994c3d;
background: #fff5ed;
border-color: #d9b6aa;
}
.small-actions {
display: flex;
gap: 6px;
margin-top: 8px;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.stat {
min-height: 75px;
padding: 9px;
background: #f1f4e9;
border: 1px solid #ccd5c3;
border-radius: 4px;
}
.stat:nth-child(2) { background: #f5eddb; border-color: #ddcfb0; }
.stat:nth-child(3) { background: #e8f0ef; border-color: #c3d6d4; }
.stat-label {
color: #617064;
font-size: 9px;
font-weight: 850;
letter-spacing: .06em;
text-transform: uppercase;
}
.stat-value {
margin: 4px 0 2px;
color: #2e4939;
font-family: Georgia, serif;
font-size: 21px;
font-weight: 700;
}
.stat-note {
color: #707b70;
font-size: 9px;
line-height: 1.3;
}
#shortfallNote {
margin-top: 8px;
padding: 7px 8px;
border-left: 3px solid var(--gold);
color: #745d38;
background: #faf2df;
font-size: 10px;
line-height: 1.35;
}
.ledger {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
.ledger th {
padding: 5px 3px;
color: #798178;
border-bottom: 1px solid var(--line);
font-size: 8px;
letter-spacing: .08em;
text-align: left;
text-transform: uppercase;
}
.ledger td {
padding: 7px 3px;
border-bottom: 1px solid #e6dfcf;
vertical-align: middle;
}
.ledger tr.selected td { background: #edf3e8; }
.ledger-name {
display: flex;
align-items: center;
gap: 6px;
font-weight: 750;
}
.ledger-outcome small {
display: block;
margin-top: 2px;
color: #7a8278;
font-size: 8px;
}
.mini-track {
width: 54px;
height: 5px;
overflow: hidden;
background: #dedbcf;
border-radius: 999px;
}
.mini-track > i {
display: block;
height: 100%;
background: var(--green);
}
details {
border-top: 1px solid var(--line);
}
summary {
padding: 12px 0 7px;
color: var(--green-dark);
font-size: 11px;
font-weight: 850;
cursor: pointer;
letter-spacing: .04em;
text-transform: uppercase;
}
details ol {
margin: 0;
padding-left: 19px;
color: #59665c;
font-size: 10px;
line-height: 1.5;
}
details li { margin-bottom: 5px; }
footer {
z-index: 6;
padding: 9px 16px 12px;
background: #f2eddf;
border-top: 1px solid #c8c0ac;
box-shadow: 0 -5px 20px rgba(35, 48, 39, .08);
}
.playback {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 6px;
}
.playback button {
height: 31px;
min-width: 31px;
padding: 0 10px;
border: 1px solid var(--green-dark);
border-radius: 3px;
color: #fff;
background: var(--green-dark);
font-size: 11px;
font-weight: 850;
}
.playback .secondary {
color: var(--green-dark);
background: #fffdf7;
}
#clock {
min-width: 55px;
color: #294532;
font-family: Georgia, serif;
font-size: 17px;
font-weight: 700;
text-align: center;
}
#timeSlider {
flex: 1;
accent-color: var(--green-dark);
}
.speed-note {
color: #69746b;
font-size: 10px;
white-space: nowrap;
}
#timeline {
width: 100%;
height: 160px;
display: block;
border: 1px solid #cec6b3;
border-radius: 4px;
background: #fffdf7;
cursor: crosshair;
}
#toast {
position: fixed;
z-index: 20;
left: 50%;
bottom: 190px;
max-width: min(440px, calc(100% - 30px));
padding: 10px 14px;
color: white;
background: rgba(34, 55, 43, .95);
border: 1px solid rgba(255,255,255,.25);
border-radius: 4px;
box-shadow: var(--shadow);
font-size: 12px;
transform: translate(-50%, 16px);
opacity: 0;
pointer-events: none;
transition: opacity .18s, transform .18s;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 950px) {
body { overflow: auto; }
#app { height: auto; min-height: 100vh; }
header { align-items: flex-start; }
.header-note { display: none; }
main { grid-template-columns: 1fr; }
#viewport { height: 58vh; min-height: 470px; }
aside { overflow: visible; border-left: 0; border-top: 1px solid var(--line); }
footer { position: sticky; bottom: 0; }
}
@media (max-width: 520px) {
header { padding: 11px 13px; }
.brand-mark { width: 36px; height: 36px; }
.subtitle { font-size: 9px; }
#viewport { min-height: 440px; }
.scene-card { top: 10px; left: 10px; }
.camera-tools { top: 10px; right: 10px; }
aside { padding: 13px; }
#entityButtons { grid-template-columns: 1fr; }
.playback .speed-note { display: none; }
footer { padding: 7px 8px 9px; }
#timeline { height: 145px; }
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">≈</div>
<div>
<h1>Merebrook Watercommons</h1>
<div class="subtitle">A voxel mill-and-irrigation planner</div>
</div>
</div>
<div class="header-note">
One shared stream serves three medieval mills and three fields.
Schedule operations, inspect competition, and follow every cubic metre through the day.
</div>
</header>
<main>
<section id="viewport" aria-label="Interactive voxel settlement">
<div id="sceneCanvas"></div>
<div id="labels"></div>
<div class="scene-card">
<strong>The Common Headrace</strong>
<span>
Blue channels carry the stream east from the river.
Mill wheels and fields draw from the same limited supply.
</span>
</div>
<div class="camera-tools" aria-label="Camera controls">
<button id="zoomIn" title="Zoom in" aria-label="Zoom in">+</button>
<button id="zoomOut" title="Zoom out" aria-label="Zoom out">−</button>
<button id="resetView" title="Reset view" aria-label="Reset view">⌂</button>
</div>
<div class="legend">
<span><i class="swatch" style="background:#4aa6c1"></i>Shared water</span>
<span><i class="swatch" style="background:#b97845"></i>Operating mill</span>
<span><i class="swatch" style="background:#d4ad4e"></i>Drought flow</span>
<span>Drag to orbit · Wheel to zoom · Click a mill or field</span>
</div>
</section>
<aside>
<div class="section-heading">
<div>
<div class="eyebrow">Settlement schedule</div>
<h2>Operating plan</h2>
</div>
</div>
<div id="entityButtons" aria-label="Select an asset"></div>
<div class="panel-card">
<div class="selected-title">
<h3 id="selectedName"></h3>
<span class="type-chip" id="selectedType"></span>
</div>
<div class="muted" id="selectedFacts"></div>
<div id="nowState"></div>
</div>
<div class="panel-card">
<div class="section-heading" style="margin-bottom:6px">
<strong style="font-size:12px">Time windows</strong>
<span class="muted">End time is excluded</span>
</div>
<div id="windowList" class="window-list"></div>
<div class="add-window">
<input id="newStart" class="clock-input" value="08:00" aria-label="New window start" inputmode="numeric">
<span class="arrow">→</span>
<input id="newEnd" class="clock-input" value="12:00" aria-label="New window end" inputmode="numeric">
<button id="addWindow" class="button">Add</button>
</div>
<div class="small-actions">
<button id="loadPreset" class="button secondary">Suggested shift</button>
<button id="clearSchedule" class="button danger">Clear selected</button>
</div>
</div>
<div class="panel-card">
<div class="section-heading" style="margin-bottom:7px">
<div>
<div class="eyebrow">Daily totals</div>
<strong style="font-family:Georgia,serif;font-size:17px">Water & work ledger</strong>
</div>
</div>
<div class="stats">
<div class="stat">
<div class="stat-label">Field delivery</div>
<div class="stat-value" id="fieldWaterStat">0</div>
<div class="stat-note" id="fieldWaterNote"></div>
</div>
<div class="stat">
<div class="stat-label">Mill running</div>
<div class="stat-value" id="millRuntimeStat">0</div>
<div class="stat-note" id="millRuntimeNote"></div>
</div>
<div class="stat">
<div class="stat-label">Source used</div>
<div class="stat-value" id="sourceUsedStat">0</div>
<div class="stat-note" id="sourceUsedNote"></div>
</div>
</div>
<div id="shortfallNote"></div>
</div>
<div class="panel-card">
<div class="section-heading" style="margin-bottom:5px">
<strong style="font-size:12px">Asset outcomes</strong>
</div>
<table class="ledger">
<thead>
<tr>
<th>Asset</th>
<th>Outcome</th>
<th>Met</th>
</tr>
</thead>
<tbody id="ledgerBody"></tbody>
</table>
</div>
<details open>
<summary>Simplified simulation rules</summary>
<ol>
<li>The fictional day runs from 00:00 to 24:00 in 5-minute steps.</li>
<li>The stream supplies 10.5 m³/min, except from 13:00 to 16:00 when drought reduces it to 6.0 m³/min.</li>
<li>Active mills receive water first, in the fixed order West Wheel, Millbrook, then East Mill.</li>
<li>Remaining water is shared proportionally among active fields according to their stated demands. Surplus supply is not stored.</li>
<li>Delivered field water equals the actual allocated rate multiplied by each 5-minute step.</li>
<li>A mill counts as mechanically running only when it receives at least 90% of its demand; otherwise its running time does not advance.</li>
<li>Overlapping windows for one asset count once. Windows cannot cross midnight.</li>
</ol>
</details>
</aside>
</main>
<footer>
<div class="playback">
<button id="playButton" aria-label="Play day">▶</button>
<button id="resetDay" class="secondary" aria-label="Reset day">00:00</button>
<span id="clock">08:00</span>
<input id="timeSlider" type="range" min="0" max="1440" step="5" value="480" aria-label="Time of day">
<span class="speed-note">Playback: 3 simulated hours / second</span>
</div>
<canvas id="timeline" aria-label="Daily allocation timeline"></canvas>
</footer>
</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";
/* -------------------------------------------------------------------------- */
/* Data and scheduling */
/* -------------------------------------------------------------------------- */
const STEP_MINUTES = 5;
const DAY_MINUTES = 24 * 60;
const NORMAL_SOURCE = 10.5;
const DROUGHT_SOURCE = 6.0;
const DROUGHT_START = 13 * 60;
const DROUGHT_END = 16 * 60;
const entities = [
{
id: "west", name: "West Wheel Mill", type: "mill", color: "#b97845",
demand: 3.0, priority: 0, scene: [-8.1, 2.9],
windows: [{ start: 6 * 60, end: 11 * 60 }, { start: 14 * 60, end: 19 * 60 }]
},
{
id: "millbrook", name: "Millbrook Mill", type: "mill", color: "#a86254",
demand: 3.0, priority: 1, scene: [-3.5, 2.9],
windows: [{ start: 7 * 60, end: 15 * 60 }]
},
{
id: "east", name: "East Mill", type: "mill", color: "#c68b43",
demand: 2.5, priority: 2, scene: [1.0, 2.9],
windows: [{ start: 9 * 60, end: 12 * 60 }, { start: 15 * 60, end: 18 * 60 }]
},
{
id: "barley", name: "North Barley", type: "field", color: "#c6a638",
demand: 2.0, scene: [7.1, -7.4],
windows: [{ start: 6 * 60, end: 10 * 60 }]
},
{
id: "hay", name: "South Hay", type: "field", color: "#d08052",
demand: 1.5, scene: [7.1, 7.4],
windows: [{ start: 12 * 60, end: 16 * 60 }]
},
{
id: "orchard", name: "Orchard Rows", type: "field", color: "#668d54",
demand: 2.0, scene: [13.1, 0],
windows: [{ start: 17 * 60, end: 21 * 60 }]
}
];
const presets = {
west: [{ start: 360, end: 660 }, { start: 840, end: 1140 }],
millbrook: [{ start: 420, end: 900 }],
east: [{ start: 540, end: 720 }, { start: 900, end: 1080 }],
barley: [{ start: 360, end: 600 }],
hay: [{ start: 720, end: 960 }],
orchard: [{ start: 1020, end: 1260 }]
};
const entityById = new Map(entities.map(entity => [entity.id, entity]));
const mills = entities.filter(entity => entity.type === "mill");
const fields = entities.filter(entity => entity.type === "field");
let selectedId = "west";
let currentMinute = 8 * 60;
let playing = false;
let lastFrame = performance.now();
let simulation;
let selectionHelper = null;
let toastTimer;
const $ = id => document.getElementById(id);
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
function parseClock(value) {
const match = String(value).trim().match(/^(\d{1,2}):(\d{2})$/);
if (!match) return null;
const hours = Number(match[1]);
const minutes = Number(match[2]);
if (minutes > 59 || hours > 24 || (hours === 24 && minutes !== 0)) return null;
return hours * 60 + minutes;
}
function formatClock(minutes) {
const m = clamp(Math.round(minutes), 0, DAY_MINUTES);
const h = Math.floor(m / 60);
const mm = m % 60;
return `${String(h).padStart(2, "0")}:${String(mm).padStart(2, "0")}`;
}
function formatDuration(minutes) {
const h = Math.floor(minutes / 60);
const m = Math.round(minutes % 60);
return h ? `${h}h ${m}m` : `${m}m`;
}
function formatVolume(value) {
return `${Math.round(value).toLocaleString()} m³`;
}
function sourceRateAt(minute) {
return minute >= DROUGHT_START && minute < DROUGHT_SOURCE ? DROUGHT_SOURCE :
minute >= DROUGHT_START && minute < DROUGHT_END ? DROUGHT_SOURCE : NORMAL_SOURCE;
}
function isActive(entity, minute) {
return entity.windows.some(window => minute >= window.start && minute < window.end);
}
function simulateDay() {
const results = [];
const summary = {
fieldWater: 0,
fieldDemand: 0,
millWater: 0,
millRuntime: 0,
sourceUsed: 0,
sourceCapacity: 0
};
for (let index = 0; index < DAY_MINUTES / STEP_MINUTES; index++) {
const minute = index * STEP_MINUTES;
const source = sourceRateAt(minute);
let remaining = source;
const rates = Object.fromEntries(entities.map(entity => [entity.id, 0]));
const activeMills = mills.filter(entity => isActive(entity, minute));
const activeFields = fields.filter(entity => isActive(entity, minute));
// Mills have fixed priority.
for (const mill of activeMills) {
const allocation = Math.min(mill.demand, remaining);
rates[mill.id] = allocation;
remaining -= allocation;
}
// Remaining source is shared proportionally among active fields.
const totalFieldDemand = activeFields.reduce((sum, field) => sum + field.demand, 0);
if (totalFieldDemand > 0 && remaining > 0) {
const distributable = Math.min(remaining, totalFieldDemand);
for (const field of activeFields) {
rates[field.id] = distributable * field.demand / totalFieldDemand;
}
remaining -= distributable;
}
const running = {};
for (const mill of mills) {
running[mill.id] = rates[mill.id] + 1e-9 >= mill.demand * 0.9;
}
const allocated = Object.values(rates).reduce((sum, value) => sum + value, 0);
results.push({ minute, source, rates, running, spare: Math.max(0, remaining) });
summary.sourceUsed += allocated * STEP_MINUTES;
summary.sourceCapacity += source * STEP_MINUTES;
for (const mill of mills) {
const water = rates[mill.id] * STEP_MINUTES;
summary.millWater += water;
if (running[mill.id]) summary.millRuntime += STEP_MINUTES;
}
for (const field of fields) {
summary.fieldWater += rates[field.id] * STEP_MINUTES;
if (isActive(field, minute)) summary.fieldDemand += field.demand * STEP_MINUTES;
}
}
const perEntity = {};
for (const entity of entities) {
let scheduledMinutes = 0;
let water = 0;
let runtime = 0;
let requested = 0;
for (const result of results) {
const active = isActive(entity, result.minute);
if (active) {
scheduledMinutes += STEP_MINUTES;
requested += entity.demand * STEP_MINUTES;
}
water += result.rates[entity.id] * STEP_MINUTES;
if (entity.type === "mill" && result.running[entity.id]) runtime += STEP_MINUTES;
}
perEntity[entity.id] = { scheduledMinutes, water, runtime, requested };
}
summary.fieldShortfall = Math.max(0, summary.fieldDemand - summary.fieldWater);
return { results, summary, perEntity };
}
function recompute() {
simulation = simulateDay();
renderSummary();
renderLedger();
drawTimeline();
updateCurrentState();
}
function showToast(message) {
const toast = $("toast");
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("visible"), 2300);
}
function renderEntityButtons() {
$("entityButtons").innerHTML = entities.map(entity => `
<button class="entity-button ${entity.id === selectedId ? "active" : ""}" data-id="${entity.id}">
<i class="swatch" style="background:${entity.color}"></i>
<span>${entity.name}</span>
</button>
`).join("");
document.querySelectorAll(".entity-button").forEach(button => {
button.addEventListener("click", () => selectEntity(button.dataset.id));
});
}
function renderSchedule() {
const entity = entityById.get(selectedId);
$("selectedName").textContent = entity.name;
$("selectedType").textContent = entity.type === "mill" ? "Mill" : "Field";
$("selectedFacts").textContent =
`${entity.demand.toFixed(1)} m³/min demand · ` +
(entity.type === "mill"
? "Mechanical runtime advances only at ≥90% of demand."
: "Delivered water is accumulated from the actual allocation.");
const list = $("windowList");
if (!entity.windows.length) {
list.innerHTML = `<div class="empty-note">No operating windows. Add one below.</div>`;
} else {
list.innerHTML = entity.windows.map((window, index) => `
<div class="window-row" data-index="${index}">
<input class="clock-input" data-part="start" value="${formatClock(window.start)}"
aria-label="Window ${index + 1} start" inputmode="numeric">
<span class="arrow">→</span>
<input class="clock-input" data-part="end" value="${formatClock(window.end)}"
aria-label="Window ${index + 1} end" inputmode="numeric">
<button class="remove-window" title="Remove window" aria-label="Remove window">×</button>
</div>
`).join("");
}
document.querySelectorAll(".window-row").forEach(row => {
const index = Number(row.dataset.index);
row.querySelectorAll("input").forEach(input => {
input.addEventListener("change", () => {
const entity = entityById.get(selectedId);
const start = parseClock(input.value);
const end = parseClock(entity.windows[index].end);
const proposed = parseClock(input.value);
if (proposed === null || start === null || end === null ||
start >= end || start === DAY_MINUTES) {
showToast("Use valid times with the start earlier than the end.");
renderSchedule();
return;
}
if (input.dataset.part === "start") entity.windows[index].start = proposed;
else entity.windows[index].end = proposed;
entity.windows.sort((a, b) => a.start - b.start);
recompute();
renderSchedule();
});
});
row.querySelector(".remove-window").addEventListener("click", () => {
entityById.get(selectedId).windows.splice(index, 1);
recompute();
renderSchedule();
});
});
}
function renderSummary() {
const { summary } = simulation;
$("fieldWaterStat").textContent = formatVolume(summary.fieldWater);
$("fieldWaterNote").textContent =
`${Math.round(summary.fieldDemand ? summary.fieldWater / summary.fieldDemand * 100 : 0)}% of scheduled field demand`;
$("millRuntimeStat").textContent = formatDuration(summary.millRuntime);
$("millRuntimeNote").textContent = `${formatVolume(summary.millWater)} delivered to wheels`;
$("sourceUsedStat").textContent = formatVolume(summary.sourceUsed);
$("sourceUsedNote").textContent =
`of ${formatVolume(summary.sourceCapacity)} available`;
$("shortfallNote").textContent = summary.fieldShortfall > 0.05
? `Scheduled irrigation shortfall: ${formatVolume(summary.fieldShortfall)}. Move field windows away from busy mill hours or shorten mill shifts.`
: "All scheduled field demand is met. Any unused source water is not stored for later.";
}
function renderLedger() {
$("ledgerBody").innerHTML = entities.map(entity => {
const outcome = simulation.perEntity[entity.id];
const ratio = outcome.requested > 0
? Math.min(1, entity.type === "mill"
? outcome.runtime / outcome.scheduledMinutes
: outcome.water / outcome.requested)
: 0;
const main = entity.type === "mill"
? `${formatDuration(outcome.runtime)} running`
: `${formatVolume(outcome.water)} delivered`;
const sub = entity.type === "mill"
? `${formatVolume(outcome.water)} at wheel`
: `${formatVolume(outcome.requested)} requested`;
return `
<tr class="${entity.id === selectedId ? "selected" : ""}" data-id="${entity.id}">
<td>
<div class="ledger-name">
<i class="swatch" style="background:${entity.color}"></i>
${entity.name.replace(" Mill", "")}
</div>
</td>
<td class="ledger-outcome">${main}<small>${sub}</small></td>
<td>
<div class="mini-track"><i style="width:${ratio * 100}%"></i></div>
</td>
</tr>
`;
}).join("");
document.querySelectorAll("#ledgerBody tr").forEach(row => {
row.style.cursor = "pointer";
row.addEventListener("click", () => selectEntity(row.dataset.id));
});
}
function updateCurrentState() {
const entity = entityById.get(selectedId);
if (!entity || !simulation) return;
const index = clamp(Math.floor(currentMinute / STEP_MINUTES), 0, simulation.results.length - 1);
const result = simulation.results[index];
const rate = result.rates[entity.id];
const active = isActive(entity, result.minute);
if (!active) {
$("nowState").textContent = `Now: off schedule · ${formatClock(currentMinute)}`;
} else if (entity.type === "mill") {
const status = result.running[entity.id] ? "mechanically running" : "below the 90% running threshold";
$("nowState").textContent =
`Now: ${rate.toFixed(2)} m³/min · ${status} · ${formatClock(currentMinute)}`;
} else {
$("nowState").textContent =
`Now: ${rate.toFixed(2)} m³/min irrigation · ${formatClock(currentMinute)}`;
}
}
function selectEntity(id) {
if (!entityById.has(id)) return;
selectedId = id;
renderEntityButtons();
renderSchedule();
renderLedger();
updateCurrentState();
updateSelectionHelper();
updateLabelSelection();
}
/* -------------------------------------------------------------------------- */
/* Timeline */
/* -------------------------------------------------------------------------- */
const timeline = $("timeline");
const timelineContext = timeline.getContext("2d");
function drawTimeline() {
if (!simulation) return;
const rect = timeline.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.max(320, rect.width);
const height = Math.max(130, rect.height);
timeline.width = Math.round(width * dpr);
timeline.height = Math.round(height * dpr);
timelineContext.setTransform(dpr, 0, 0, dpr, 0, 0);
timelineContext.clearRect(0, 0, width, height);
const labelWidth = width < 600 ? 100 : 138;
const right = width - 12;
const chartTop = 7;
const rowsTop = 39;
const rowHeight = Math.min(18, (height - rowsTop - 5) / entities.length);
const timeX = minute => labelWidth + (right - labelWidth) * minute / DAY_MINUTES;
timelineContext.fillStyle = "#f8f4e9";
timelineContext.fillRect(0, 0, width, height);
// Source-rate mini chart.
timelineContext.fillStyle = "#e5ecdf";
timelineContext.fillRect(labelWidth, chartTop, right - labelWidth, 18);
timelineContext.strokeStyle = "#3f8098";
timelineContext.lineWidth = 1.5;
timelineContext.beginPath();
simulation.results.forEach((result, index) => {
const x = timeX(result.minute);
const y = chartTop + 16 - (result.source - 5) / 6 * 14;
if (index === 0) timelineContext.moveTo(x, y);
else timelineContext.lineTo(x, y);
});
timelineContext.stroke();
timelineContext.fillStyle = "#637067";
timelineContext.font = "700 9px system-ui";
timelineContext.fillText("SOURCE", 7, 18);
// Drought band.
timelineContext.fillStyle = "rgba(211,155,66,.20)";
timelineContext.fillRect(timeX(DROUGHT_START), rowsTop - 6, timeX(DROUGHT_END) - timeX(DROUGHT_START), height - rowsTop);
// Hour grid.
timelineContext.font = "9px system-ui";
for (let hour = 0; hour <= 24; hour++) {
const x = timeX(hour * 60);
timelineContext.strokeStyle = hour % 6 === 0 ? "#b7b3a5" : "#e0dbcd";
timelineContext.beginPath();
timelineContext.moveTo(x, rowsTop - 8);
timelineContext.lineTo(x, height);
timelineContext.stroke();
if (hour % 3 === 0) {
timelineContext.fillStyle = "#7a8179";
timelineContext.textAlign = hour === 24 ? "right" : "center";
timelineContext.fillText(`${String(hour).padStart(2, "0")}:00`, x, 31);
}
}
entities.forEach((entity, index) => {
const y = rowsTop + index * rowHeight;
if (entity.id === selectedId) {
timelineContext.fillStyle = "rgba(64, 106, 73, .10)";
timelineContext.fillRect(0, y - 1, width, rowHeight - 1);
}
timelineContext.fillStyle = "#3d4c43";
timelineContext.font = `${entity.id === selectedId ? "800" : "650"} 9px system-ui`;
timelineContext.textAlign = "left";
const shortName = entity.name.replace(" Wheel", "").replace(" Mill", "");
timelineContext.fillText(shortName, 7, y + rowHeight * .62);
for (const window of entity.windows) {
const x = timeX(window.start);
const w = Math.max(2, timeX(window.end) - x);
timelineContext.fillStyle = entity.color + "bb";
timelineContext.fillRect(x, y + 3, w, Math.max(7, rowHeight - 7));
timelineContext.strokeStyle = entity.color;
timelineContext.strokeRect(x + .5, y + 3.5, Math.max(1, w - 1), Math.max(6, rowHeight - 8));
}
});
// Playhead.
const playX = timeX(currentMinute);
timelineContext.strokeStyle = "#a74437";
timelineContext.lineWidth = 1.5;
timelineContext.beginPath();
timelineContext.moveTo(playX, 4);
timelineContext.lineTo(playX, height);
timelineContext.stroke();
timelineContext.fillStyle = "#a74437";
timelineContext.beginPath();
timelineContext.moveTo(playX - 4, 4);
timelineContext.lineTo(playX + 4, 4);
timelineContext.lineTo(playX, 10);
timelineContext.closePath();
timelineContext.fill();
}
timeline.addEventListener("pointerdown", event => {
const rect = timeline.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const width = rect.width;
const labelWidth = width < 600 ? 100 : 138;
const rowsTop = 39;
const rowHeight = Math.min(18, (rect.height - rowsTop - 5) / entities.length);
const rowIndex = clamp(Math.floor((y - rowsTop) / rowHeight), 0, entities.length - 1);
if (x < labelWidth) {
selectEntity(entities[rowIndex].id);
return;
}
const minute = clamp(Math.round((x - labelWidth) / (width - 12 - labelWidth) * DAY_MINUTES / 5) * 5, 0, DAY_MINUTES);
setCurrentMinute(minute);
});
/* -------------------------------------------------------------------------- */
/* Three.js scene */
/* -------------------------------------------------------------------------- */
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d5cf);
scene.fog = new THREE.Fog(0xb9d5cf, 42, 72);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
$("sceneCanvas").appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-20, 20, 12, -12, 0.1, 120);
const cameraTarget = new THREE.Vector3(0, 0.4, 0);
const cameraState = { yaw: 0.70, pitch: 0.69, radius: 35, zoom: 0.92 };
const hemi = new THREE.HemisphereLight(0xe8f4ef, 0x5c533d, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffedc6, 3.0);
sun.position.set(-13, 25, 15);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.00035;
scene.add(sun);
const materialCache = new Map();
function getMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(color, new THREE.MeshStandardMaterial({
color,
roughness: 0.9,
metalness: 0,
flatShading: true
}));
}
return materialCache.get(color);
}
function box(parent, width, height, depth, color, x, y, z, options = {}) {
const material = options.material || (color?.isMaterial ? color : getMaterial(color));
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;
}
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x46a4c2,
roughness: 0.32,
metalness: 0.05,
transparent: true,
opacity: 0.78,
depthWrite: false
});
const flowMaterial = new THREE.MeshBasicMaterial({
color: 0xd9f7f2,
transparent: true,
opacity: 0.8
});
const fieldVisuals = new Map();
const millVisuals = new Map();
const pickMeshes = [];
const labelItems = [];
const flowParticles = [];
// Terrain.
box(scene, 36, 1.45, 26, 0x654936, 0, -0.72, 0);
box(scene, 36, 0.28, 26, 0x86a65c, 0, 0.14, 0);
// River and banks.
box(scene, 4.1, 0.18, 26, waterMaterial, -13.6, 0.32, 0, { castShadow: false });
box(scene, 0.8, 0.45, 26, 0x7d745d, -15.75, 0.36, 0);
box(scene, 0.8, 0.45, 26, 0x7d745d, -11.45, 0.36, 0);
// Shared headrace and stone edging.
box(scene, 22.3, 0.16, 1.55, waterMaterial, -0.45, 0.36, 0, { castShadow: false });
box(scene, 22.3, 0.28, 0.45, 0x8a826a, -0.45, 0.36, 1.05);
box(scene, 22.3, 0.28, 0.45, 0x8a826a, -0.45, 0.36, -1.05);
// Irrigation branches.
box(scene, 0.68, 0.14, 7.5, waterMaterial, 3.35, 0.36, -3.75, { castShadow: false });
box(scene, 0.68, 0.14, 7.5, waterMaterial, 3.35, 0.36, 3.75, { castShadow: false });
box(scene, 0.8, 0.14, 1.2, waterMaterial, 10.8, 0.36, 0, { castShadow: false });
// Gravel paths.
box(scene, 17.5, 0.08, 1.2, 0xb7a783, -3.8, 0.34, -4.6, { castShadow: false });
box(scene, 1.1, 0.08, 12.2, 0xb7a783, 1.9, 0.34, 2.6, { castShadow: false });
function seededRandom(seed) {
let value = seed >>> 0;
return () => {
value = (value * 1664525 + 1013904223) >>> 0;
return value / 4294967296;
};
}
const random = seededRandom(7719);
function makeTree(parent, x, z, scale = 1, fruit = false) {
const group = new THREE.Group();
group.position.set(x, 0.3, z);
group.scale.setScalar(scale);
parent.add(group);
box(group, 0.45, 2.5, 0.45, 0x6c4930, 0, 1.25, 0);
box(group, 2.5, 1.65, 2.25, fruit ? 0x4f7d46 : 0x567c46, 0, 3.05, 0);
box(group, 1.85, 1.25, 1.75, 0x668d50, 0.55, 4.05, -0.15);
box(group, 1.35, 1.0, 1.4, 0x739756, -0.65, 3.9, 0.4);
if (fruit) {
for (let i = 0; i < 5; i++) {
box(group, 0.22, 0.22, 0.22, 0xc7753e,
-0.85 + random() * 1.7, 2.6 + random() * 1.5, -0.75 + random() * 1.5);
}
}
return group;
}
function makeHouse(parent, x, z, width = 3, depth = 2.6, wallColor = 0xd7c99e) {
const group = new THREE.Group();
group.position.set(x, 0.3, z);
parent.add(group);
box(group, width + 0.35, 0.35, depth + 0.35, 0x7b7160, 0, 0.18, 0);
box(group, width, 2.05, depth, wallColor, 0, 1.35, 0);
box(group, width + 0.35, 0.28, depth + 0.35, 0x6b3f2f, 0, 2.48, 0);
box(group, width - 0.45, 0.28, depth - 0.4, 0x774331, 0, 2.78, 0);
box(group, width - 1.35, 0.28, depth - 0.9, 0x7c4934, 0, 3.08, 0);
box(group, 0.72, 1.25, 0.12, 0x4f3928, 0, 0.95, depth / 2 + 0.07);
box(group, 0.58, 0.62, 0.13, 0xe3b65d, width * 0.27, 1.55, depth / 2 + 0.08);
box(group, 0.58, 0.62, 0.13, 0xe3b65d, -width * 0.27, 1.55, depth / 2 + 0.08);
box(group, 0.12, 1.4, 0.14, 0x4f3928, width * 0.27, 1.55, depth / 2 + 0.15);
box(group, 0.12, 1.4, 0.14, 0x4f3928, -width * 0.27, 1.55, depth / 2 + 0.15);
return group;
}
// Village backdrop.
makeHouse(scene, -8.3, -8.1, 3.4, 2.6, 0xd9cba2);
makeHouse(scene, -3.7, -8.4, 3.0, 2.4, 0xcbb98d);
makeHouse(scene, -9.2, 8.0, 3.1, 2.5, 0xcfbd91);
makeHouse(scene, -4.2, 8.2, 3.5, 2.8, 0xd9c99c);
const tower = new THREE.Group();
tower.position.set(-12.0, 0.3, -6.3);
scene.add(tower);
box(tower, 2.4, 5.7, 2.4, 0xa9a38b, 0, 2.85, 0);
box(tower, 2.9, 0.35, 2.9, 0x726d5c, 0, 5.8, 0);
box(tower, 1.55, 1.25, 1.55, 0x766b55, 0, 6.55, 0);
box(tower, 0.35, 1.4, 0.35, 0x5e5140, 0, 7.65, 0);
for (const tree of [
[-14.6, -8.5, 1.1], [-14.7, 7.4, 1.0], [-6.8, -10.0, .8],
[-1.8, -9.8, .85], [1.2, -10.2, .8], [-10.0, 10.1, .9],
[-6.0, 10.2, .8], [1.6, 9.9, .75], [15.7, -8.7, .9],
[15.8, 8.8, .85]
]) makeTree(scene, ...tree);
// Fence sections.
function fence(x, z, length, alongX = true) {
const group = new THREE.Group();
group.position.set(x, 0.3, z);
scene.add(group);
const count = Math.max(2, Math.round(length / 1.4));
for (let i = 0; i <= count; i++) {
const offset = -length / 2 + length * i / count;
box(group, 0.16, 1.1, 0.16, 0x73583a, alongX ? offset : 0, 0.55, alongX ? 0 : offset);
}
box(group, alongX ? length : 0.12, 0.12, alongX ? 0.12 : length,
0x806342, 0, 0.82, 0);
box(group, alongX ? length : 0.12, 0.12, alongX ? 0.12 : length,
0x806342, 0, 0.45, 0);
}
fence(7.1, -10.0, 8.0, true);
fence(7.1, 10.0, 8.0, true);
fence(15.7, 0, 7.5, false);
function createMill(entity) {
const group = new THREE.Group();
group.position.set(entity.scene[0], 0.3, entity.scene[1]);
scene.add(group);
const bodyColor = entity.id === "west" ? 0xd5c397 :
entity.id === "millbrook" ? 0xc9b78c : 0xd8c39b;
box(group, 3.8, 0.42, 3.1, 0x777262, 0, 0.25, 0);
box(group, 3.1, 2.55, 2.55, bodyColor, 0, 1.72, 0);
// Timber framing.
for (const x of [-1.42, 0, 1.42]) {
box(group, 0.16, 2.55, 0.15, 0x67472f, x, 1.72, 1.34);
}
box(group, 3.15, 0.18, 0.15, 0x67472f, 0, 1.15, 1.34);
box(group, 3.15, 0.18, 0.15, 0x67472f, 0, 2.35, 1.34);
// Stepped voxel roof.
box(group, 3.7, 0.34, 3.15, 0x654033, 0, 3.14, 0);
box(group, 3.0, 0.34, 2.6, 0x714739, 0, 3.47, 0);
box(group, 2.25, 0.34, 2.0, 0x7b4b3b, 0, 3.80, 0);
box(group, 0.9, 1.4, 0.14, 0x4f3827, 0, 0.98, 1.34);
box(group, 0.68, 0.65, 0.14, 0xe3b65d, 0.88, 1.95, 1.35);
box(group, 0.12, 0.65, 0.15, 0x5b402b, 0.88, 1.95, 1.44);
// Waterwheel in a vertical XY plane.
const wheel = new THREE.Group();
wheel.position.set(-1.72, 1.15, -2.10);
wheel.rotation.z = entity.priority * 0.4;
group.add(wheel);
box(wheel, 0.42, 0.42, 0.5, 0x6c482c, 0, 0, 0);
for (let i = 0; i < 8; i++) {
const angle = i * Math.PI / 4;
const spoke = box(wheel, 2.35, 0.13, 0.16, 0x805536, 0, 0, 0);
spoke.rotation.z = angle;
box(wheel, 0.48, 0.18, 0.72, 0x93613c,
Math.cos(angle) * 1.16, Math.sin(angle) * 1.16, 0).rotation.z = angle;
}
box(wheel, 0.2, 2.5, 0.7, 0x70492e, 0, 0, 0);
// Sluice and support.
box(group, 0.42, 1.35, 0.6, 0x654b32, -1.75, 0.8, -1.8);
box(group, 2.6, 0.18, 0.3, 0x674832, -1.0, 1.05, -1.25);
const anchor = new THREE.Object3D();
anchor.position.set(0, 4.35, 0);
group.add(anchor);
millVisuals.set(entity.id, { group, wheel, anchor });
return group;
}
function createField(entity) {
const group = new THREE.Group();
group.position.set(entity.scene[0], 0.3, entity.scene[1]);
scene.add(group);
let width = 7.0;
let depth = 4.2;
if (entity.id === "orchard") {
width = 4.4;
depth = 6.0;
}
box(group, width + 0.35, 0.26, depth + 0.35, 0x72503a, 0, 0.13, 0);
box(group, width, 0.18, depth, entity.id === "hay" ? 0x8b673d : 0x7e5938, 0, 0.32, 0);
const overlayMaterial = new THREE.MeshBasicMaterial({
color: 0x48a9c3,
transparent: true,
opacity: 0,
depthWrite: false
});
const overlay = box(group, width - 0.2, 0.045, depth - 0.2,
overlayMaterial, 0, 0.44, 0, { castShadow: false });
if (entity.id === "orchard") {
for (let ix = 0; ix < 2; ix++) {
for (let iz = 0; iz < 4; iz++) {
const x = -1.0 + ix * 2.0;
const z = -2.15 + iz * 1.42;
makeTree(group, x, z, 0.58, true);
}
}
} else {
const rows = entity.id === "hay" ? 8 : 7;
const cropColor = entity.id === "hay" ? 0xc69a4d : 0xb8aa45;
for (let row = 0; row < rows; row++) {
const z = -depth / 2 + 0.45 + row * (depth - 0.9) / (rows - 1);
for (let col = 0; col < 11; col++) {
const x = -width / 2 + 0.45 + col * (width - 0.9) / 10;
const crop = box(group, 0.28, 0.34 + random() * 0.13, 0.25,
cropColor, x, 0.57, z);
crop.rotation.y = (random() - 0.5) * 0.15;
}
}
}
const anchor = new THREE.Object3D();
anchor.position.set(0, entity.id === "orchard" ? 2.7 : 1.1, 0);
group.add(anchor);
fieldVisuals.set(entity.id, { group, overlay, anchor });
return group;
}
for (const mill of mills) createMill(mill);
for (const field of fields) createField(field);
// Register clickable meshes and labels.
for (const entity of entities) {
const group = entity.type === "mill"
? millVisuals.get(entity.id).group
: fieldVisuals.get(entity.id).group;
group.traverse(object => {
if (object.isMesh) {
object.userData.entityId = entity.id;
pickMeshes.push(object);
}
});
const anchor = entity.type === "mill"
? millVisuals.get(entity.id).anchor
: fieldVisuals.get(entity.id).anchor;
const label = document.createElement("button");
label.className = "scene-label";
label.innerHTML = `<i class="dot" style="background:${entity.color}"></i><span>${entity.name}</span>`;
label.addEventListener("click", () => selectEntity(entity.id));
$("labels").appendChild(label);
labelItems.push({ entity, anchor, element: label });
}
// Flowing water highlights.
for (let i = 0; i < 24; i++) {
const mesh = box(scene, 0.25, 0.08, 0.18, flowMaterial,
-12 + i * 0.95, 0.48, (random() - 0.5) * 0.72, { castShadow: false });
flowParticles.push({ mesh, kind: "canal", offset: random() * 0.9 });
}
for (let i = 0; i < 11; i++) {
const mesh = box(scene, 0.20, 0.08, 0.15, flowMaterial,
-13.5, 0.48, -12 + i * 2.35, { castShadow: false });
flowParticles.push({ mesh, kind: "river", offset: random() * 0.9 });
}
function updateSelectionHelper() {
if (selectionHelper) {
scene.remove(selectionHelper);
selectionHelper.geometry.dispose();
selectionHelper.material.dispose();
}
const entity = entityById.get(selectedId);
const group = entity.type === "mill"
? millVisuals.get(entity.id).group
: fieldVisuals.get(entity.id).group;
selectionHelper = new THREE.BoxHelper(group, 0xf4c85f);
selectionHelper.material.transparent = true;
selectionHelper.material.opacity = 0.9;
selectionHelper.material.depthTest = false;
selectionHelper.renderOrder = 20;
scene.add(selectionHelper);
}
function updateLabelSelection() {
for (const item of labelItems) {
item.element.classList.toggle("selected", item.entity.id === selectedId);
}
}
/* -------------------------------------------------------------------------- */
/* Direct camera controls */
/* -------------------------------------------------------------------------- */
let dragging = false;
let dragDistance = 0;
let previousPointer = { x: 0, y: 0 };
function updateCamera() {
const { yaw, pitch, radius } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(yaw) * Math.cos(pitch),
cameraTarget.y + radius * Math.sin(pitch),
cameraTarget.z + radius * Math.cos(yaw) * Math.cos(pitch)
);
camera.lookAt(cameraTarget);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.yaw = 0.70;
cameraState.pitch = 0.69;
cameraState.radius = 35;
cameraState.zoom = 0.92;
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
dragDistance = 0;
previousPointer = { x: event.clientX, y: event.clientY };
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
dragDistance += Math.abs(dx) + Math.abs(dy);
cameraState.yaw -= dx * 0.006;
cameraState.pitch = clamp(cameraState.pitch + dy * 0.004, 0.28, 1.28);
previousPointer = { x: event.clientX, y: event.clientY };
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (dragDistance < 5) selectAt(event.clientX, event.clientY);
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
renderer.domElement.classList.remove("dragging");
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.zoom = clamp(cameraState.zoom * Math.exp(-event.deltaY * 0.001), 0.62, 2.25);
updateCamera();
}, { passive: false });
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function selectAt(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = (clientX - rect.left) / rect.width * 2 - 1;
pointer.y = -(clientY - rect.top) / rect.height * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickMeshes, false);
if (hits.length) selectEntity(hits[0].object.userData.entityId);
}
$("zoomIn").addEventListener("click", () => {
cameraState.zoom = clamp(cameraState.zoom * 1.14, 0.62, 2.25);
updateCamera();
});
$("zoomOut").addEventListener("click", () => {
cameraState.zoom = clamp(cameraState.zoom / 1.14, 0.62, 2.25);
updateCamera();
});
$("resetView").addEventListener("click", resetCamera);
/* -------------------------------------------------------------------------- */
/* UI controls and playback */
/* -------------------------------------------------------------------------- */
$("addWindow").addEventListener("click", () => {
const entity = entityById.get(selectedId);
const start = parseClock($("newStart").value);
const end = parseClock($("newEnd").value);
if (start === null || end === null || start >= end || start === DAY_MINUTES) {
showToast("Enter a valid start and a later end time.");
return;
}
entity.windows.push({ start, end });
entity.windows.sort((a, b) => a.start - b.start);
recompute();
renderSchedule();
showToast(`${entity.name}: ${formatClock(start)}–${formatClock(end)} added.`);
});
$("clearSchedule").addEventListener("click", () => {
const entity = entityById.get(selectedId);
entity.windows = [];
recompute();
renderSchedule();
showToast(`${entity.name} schedule cleared.`);
});
$("loadPreset").addEventListener("click", () => {
const entity = entityById.get(selectedId);
entity.windows = presets[entity.id].map(window => ({ ...window }));
recompute();
renderSchedule();
showToast(`Suggested shift loaded for ${entity.name}.`);
});
function setCurrentMinute(minute) {
currentMinute = clamp(Math.round(minute / 5) * 5, 0, DAY_MINUTES);
$("timeSlider").value = currentMinute;
$("clock").textContent = formatClock(currentMinute);
updateCurrentState();
drawTimeline();
}
$("timeSlider").addEventListener("input", event => setCurrentMinute(Number(event.target.value)));
$("playButton").addEventListener("click", () => {
if (currentMinute >= DAY_MINUTES) currentMinute = 0;
playing = !playing;
$("playButton").textContent = playing ? "❚❚" : "▶";
$("playButton").setAttribute("aria-label", playing ? "Pause day" : "Play day");
});
$("resetDay").addEventListener("click", () => {
playing = false;
$("playButton").textContent = "▶";
setCurrentMinute(0);
});
function resizeRenderer() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
const aspect = width / Math.max(1, height);
const viewHeight = Math.max(23, 30 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
updateCamera();
drawTimeline();
}
new ResizeObserver(resizeRenderer).observe(viewport);
new ResizeObserver(drawTimeline).observe(timeline);
/* -------------------------------------------------------------------------- */
/* Animation */
/* -------------------------------------------------------------------------- */
const projected = new THREE.Vector3();
const worldPosition = new THREE.Vector3();
function updateLabels() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
for (const item of labelItems) {
item.anchor.getWorldPosition(worldPosition);
projected.copy(worldPosition).project(camera);
if (projected.z < -1 || projected.z > 1 || Math.abs(projected.x) > 1.15 || Math.abs(projected.y) > 1.15) {
item.element.style.display = "none";
continue;
}
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
item.element.style.display = "flex";
item.element.style.left = `${x}px`;
item.element.style.top = `${y}px`;
}
}
function updateSceneState(delta) {
const index = clamp(Math.floor(currentMinute / STEP_MINUTES), 0, simulation.results.length - 1);
const result = simulation.results[index];
for (const mill of mills) {
const visual = millVisuals.get(mill.id);
if (result.running[mill.id]) visual.wheel.rotation.z -= delta * 2.35;
}
for (const field of fields) {
const visual = fieldVisuals.get(field.id);
const rate = result.rates[field.id];
const ratio = clamp(rate / field.demand, 0, 1);
visual.overlay.material.opacity = ratio * 0.34;
}
const drought = result.source < NORMAL_SOURCE;
const targetColor = new THREE.Color(drought ? 0x67a7a3 : 0x46a4c2);
waterMaterial.color.lerp(targetColor, 0.06);
const speed = result.source * 0.34;
for (const particle of flowParticles) {
if (particle.kind === "canal") {
particle.mesh.position.x += delta * speed;
if (particle.mesh.position.x > 10.5) particle.mesh.position.x = -12.1;
} else {
particle.mesh.position.z += delta * speed * 0.85;
if (particle.mesh.position.z > 12.4) particle.mesh.position.z = -12.4;
}
}
}
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min((now - lastFrame) / 1000, 0.05);
lastFrame = now;
if (playing) {
currentMinute += delta * 180;
if (currentMinute >= DAY_MINUTES) {
currentMinute = DAY_MINUTES;
playing = false;
$("playButton").textContent = "▶";
}
const snapped = Math.round(currentMinute / 5) * 5;
$("timeSlider").value = snapped;
$("clock").textContent = formatClock(currentMinute);
updateCurrentState();
drawTimeline();
}
updateSceneState(delta);
if (selectionHelper) selectionHelper.update();
scene.updateMatrixWorld();
updateLabels();
renderer.render(scene, camera);
}
// Initialize.
renderEntityButtons();
renderSchedule();
recompute();
setCurrentMinute(8 * 60);
selectEntity("west");
resetCamera();
resizeRenderer();
requestAnimationFrame(animate);
</script>
</body>
</html>
```