Prompt specification
Build or customize the Three.js 3D scene "Village Worker Simulation" 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: Village Worker Simulation
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/village-worker-simulation-x3523
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring agent states, priorities, and task transitions. Build an original miniature village with workers following visible finite-state rules. Keep resource ownership, routes, and task priorities consistent as jobs appear and finish. Voxel style.
Working Three.js Starter (village-worker-simulation-x3523):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Pebble & Pine — Voxel Work Queue</title>
<style>
:root {
--ink: #183234;
--panel: rgba(21, 43, 43, 0.93);
--panel-2: rgba(32, 57, 56, 0.92);
--cream: #f5e9cc;
--muted: #a9bbb0;
--line: rgba(224, 237, 217, 0.13);
--high: #ff786a;
--normal: #ffc768;
--low: #70b9e8;
--wood: #e7aa68;
--grain: #f2d36b;
--stone: #a9b5b1;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #173033;
color: var(--cream);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select,
input {
font: inherit;
}
button,
select {
color: var(--cream);
}
#scene-wrap,
#scene-wrap canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#scene-wrap canvas {
display: block;
touch-action: none;
cursor: grab;
}
#scene-wrap canvas:active {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 20px;
display: flex;
align-items: center;
gap: 18px;
pointer-events: none;
text-shadow: 0 2px 14px rgba(0, 0, 0, 0.45);
}
.brand {
display: flex;
align-items: center;
gap: 11px;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(2, 8px);
grid-template-rows: repeat(2, 8px);
gap: 3px;
transform: rotate(-8deg);
}
.brand-mark i {
display: block;
background: #f2d36b;
border-radius: 1px;
}
.brand-mark i:nth-child(2) {
background: #e7aa68;
}
.brand-mark i:nth-child(3) {
background: #81b88c;
}
.brand-mark i:nth-child(4) {
background: #f5e9cc;
}
h1 {
margin: 0;
font-size: clamp(18px, 2vw, 27px);
letter-spacing: -0.03em;
font-weight: 780;
}
.subtitle {
margin-top: 2px;
color: #d7dfcd;
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.cycle-pill {
padding: 8px 12px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 999px;
background: rgba(14, 37, 38, 0.58);
backdrop-filter: blur(8px);
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#panel {
position: fixed;
z-index: 20;
top: 16px;
right: 16px;
bottom: 16px;
width: 338px;
overflow: auto;
border: 1px solid rgba(231, 241, 224, 0.15);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: #5e766b transparent;
}
.panel-section {
padding: 16px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child {
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 12px;
color: #e9eddf;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 13px;
}
.stat {
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
text-align: center;
}
.stat strong {
display: block;
font-size: 20px;
line-height: 1;
}
.stat span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.recipe-bar {
display: grid;
grid-template-columns: 1fr repeat(3, auto);
gap: 6px;
margin-bottom: 12px;
}
.recipe-bar select {
min-width: 0;
border: 1px solid var(--line);
border-radius: 8px;
outline: 0;
background: #284746;
padding: 0 8px;
font-size: 11px;
}
.add-task {
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 8px;
padding: 8px 9px;
background: rgba(255, 255, 255, 0.06);
cursor: pointer;
font-size: 10px;
font-weight: 800;
transition: transform 0.15s, background 0.15s;
}
.add-task:hover {
transform: translateY(-1px);
background: rgba(255, 255, 255, 0.12);
}
.add-task.wood {
color: var(--wood);
}
.add-task.grain {
color: var(--grain);
}
.add-task.stone {
color: var(--stone);
}
#jobs-list {
display: grid;
gap: 8px;
}
.job {
position: relative;
overflow: hidden;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.04);
}
.job::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--task-color);
}
.job-top,
.job-meta,
.job-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.job-name {
color: #f5edda;
font-size: 12px;
font-weight: 780;
}
.job-id {
margin-left: 5px;
color: #809a90;
font-size: 9px;
font-weight: 700;
}
.priority-select {
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 6px;
outline: 0;
background: rgba(0, 0, 0, 0.16);
padding: 4px 5px;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
cursor: pointer;
}
.job-meta {
margin-top: 7px;
color: var(--muted);
font-size: 9px;
}
.state-badge {
display: inline-flex;
align-items: center;
gap: 5px;
width: fit-content;
padding: 3px 6px;
border-radius: 5px;
background: rgba(255, 255, 255, 0.06);
color: #dce6d5;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.09em;
}
.state-badge::before {
content: "";
width: 5px;
height: 5px;
border-radius: 50%;
background: currentColor;
}
.state-badge.high {
color: var(--high);
}
.state-badge.normal {
color: var(--normal);
}
.state-badge.low {
color: var(--low);
}
.state-badge.done {
color: #8fce9d;
}
.job-bottom {
margin-top: 8px;
}
.job-worker {
color: #b9c8bb;
font-size: 9px;
}
.progress {
position: relative;
height: 3px;
margin-top: 8px;
overflow: hidden;
border-radius: 3px;
background: rgba(255, 255, 255, 0.07);
}
.progress i {
display: block;
height: 100%;
border-radius: inherit;
background: var(--task-color);
transition: width 0.25s;
}
.worker-list,
.resource-list {
display: grid;
gap: 7px;
}
.worker-row {
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: 9px;
padding: 7px 8px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
}
.worker-dot {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--worker-color);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--worker-color) 16%, transparent);
}
.worker-name {
color: #e8eadc;
font-size: 10px;
font-weight: 750;
}
.worker-detail {
margin-top: 2px;
color: #8fa69b;
font-size: 8px;
}
.worker-state {
color: #b5c7ba;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.06em;
text-align: right;
}
.resource-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 7px 8px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 8px;
color: #bac8bb;
font-size: 9px;
}
.resource-row strong {
color: #f0e6ce;
font-size: 9px;
}
.inventory {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.inventory-item {
padding: 9px 7px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
text-align: center;
}
.inventory-item strong {
display: block;
font-size: 18px;
}
.inventory-item span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.rules {
color: #9eb1a6;
font-size: 9px;
line-height: 1.7;
}
.rule-chain {
margin: 8px 0;
padding: 9px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(0, 0, 0, 0.11);
color: #e2e4d5;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 8px;
line-height: 1.8;
}
.rule-chain b {
color: var(--normal);
}
#bottom-controls {
position: fixed;
z-index: 15;
left: 50%;
bottom: 18px;
display: flex;
align-items: center;
gap: 9px;
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 13px;
background: rgba(18, 42, 42, 0.87);
box-shadow: 0 15px 45px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(15px);
transform: translateX(-50%);
}
.control-button {
min-width: 76px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 8px;
padding: 8px 10px;
background: rgba(255, 255, 255, 0.07);
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.control-button:hover {
background: rgba(255, 255, 255, 0.13);
}
.speed-control {
display: flex;
align-items: center;
gap: 8px;
padding: 0 8px;
color: #b9c9bd;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
input[type="range"] {
width: 84px;
accent-color: #f2d36b;
}
.toggle {
display: flex;
align-items: center;
gap: 7px;
padding: 0 8px;
color: #b9c9bd;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
}
.toggle input {
accent-color: #8fce9d;
}
#help {
position: fixed;
z-index: 10;
left: 20px;
bottom: 20px;
max-width: 320px;
color: rgba(239, 239, 218, 0.66);
font-size: 9px;
line-height: 1.6;
pointer-events: none;
text-shadow: 0 1px 5px #102526;
}
#help b {
color: rgba(255, 248, 220, 0.9);
}
#labels {
position: fixed;
z-index: 8;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.agent-label {
position: absolute;
min-width: 92px;
padding: 5px 7px;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 7px;
background: rgba(19, 42, 42, 0.9);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.18);
color: #f1ecd9;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.05em;
text-align: center;
transform: translate(-50%, -100%);
transition: opacity 0.15s;
white-space: nowrap;
}
.agent-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -4px;
width: 7px;
height: 7px;
border-right: 1px solid rgba(255, 255, 255, 0.18);
border-bottom: 1px solid rgba(255, 255, 255, 0.18);
background: #173132;
transform: translateX(-50%) rotate(45deg);
}
.agent-label .agent-state {
display: block;
margin-top: 2px;
color: #a8c3b5;
font-size: 7px;
letter-spacing: 0.1em;
}
#toast {
position: fixed;
z-index: 40;
top: 90px;
left: 50%;
padding: 10px 15px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 9px;
background: rgba(20, 46, 45, 0.94);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.25);
color: #edf0dd;
font-size: 10px;
font-weight: 750;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition: opacity 0.2s, transform 0.2s;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 850px) {
#panel {
width: 300px;
}
.cycle-pill {
display: none;
}
#help {
max-width: 240px;
}
}
@media (max-width: 650px) {
.topbar {
top: 12px;
left: 12px;
}
.subtitle {
display: none;
}
#panel {
top: auto;
right: 8px;
bottom: 78px;
left: 8px;
width: auto;
max-height: 42vh;
}
#bottom-controls {
right: 8px;
bottom: 9px;
left: 8px;
justify-content: center;
transform: none;
}
#help {
display: none;
}
.speed-control {
padding: 0 2px;
}
.speed-control input {
width: 56px;
}
.toggle {
padding: 0 2px;
}
}
</style>
</head>
<body>
<div id="scene-wrap"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div>
<h1>Pebble & Pine</h1>
<div class="subtitle">A very small working village</div>
</div>
</div>
<div class="cycle-pill" id="cycle-label">Cycle 1 · 00:00</div>
</header>
<aside id="panel">
<section class="panel-section">
<div class="section-title">
Work queue
<small>Highest feasible priority first</small>
</div>
<div class="stats">
<div class="stat"><strong id="queued-count">0</strong><span>Queued</span></div>
<div class="stat"><strong id="active-count">0</strong><span>Active</span></div>
<div class="stat"><strong id="done-count">0</strong><span>Delivered</span></div>
</div>
<div class="recipe-bar">
<select id="new-priority" aria-label="New task priority">
<option value="high">HIGH PRIORITY</option>
<option value="normal" selected>NORMAL</option>
<option value="low">LOW</option>
</select>
<button class="add-task wood" data-add="wood">+ Timber</button>
<button class="add-task grain" data-add="grain">+ Grain</button>
<button class="add-task stone" data-add="stone">+ Stone</button>
</div>
<div id="jobs-list"></div>
</section>
<section class="panel-section">
<div class="section-title">
Village crew
<small>Finite-state workers</small>
</div>
<div class="worker-list" id="worker-list"></div>
</section>
<section class="panel-section">
<div class="section-title">
Resource ledger
<small>Exclusive ownership</small>
</div>
<div class="resource-list" id="resource-list"></div>
</section>
<section class="panel-section">
<div class="section-title">Village stores</div>
<div class="inventory">
<div class="inventory-item"><strong id="inventory-planks">0</strong><span>Planks</span></div>
<div class="inventory-item"><strong id="inventory-bread">0</strong><span>Bread</span></div>
<div class="inventory-item"><strong id="inventory-blocks">0</strong><span>Blocks</span></div>
</div>
</section>
<section class="panel-section">
<div class="section-title">Operating rules</div>
<div class="rules">
<div class="rule-chain">
<b>JOB</b> QUEUED → RESERVED → LOADING<br />
→ HAULING → UNLOADING → DONE<br /><br />
<b>WORKER</b> IDLE → TO SOURCE → LOADING<br />
→ TO DEST → UNLOADING → IDLE<br /><br />
<b>RESOURCE</b> FREE → RESERVED → CARRIED → CONSUMED
</div>
A job is claimed only when an eligible idle worker and an unowned resource
both exist. High priority never preempts an active task.
</div>
</section>
</aside>
<div id="labels"></div>
<div id="bottom-controls">
<button class="control-button" id="pause-button">Pause</button>
<button class="control-button" id="reset-view">Reset view</button>
<label class="speed-control">
Speed
<input id="speed" type="range" min="0.5" max="3" step="0.5" value="1" />
<span id="speed-value">1×</span>
</label>
<label class="toggle">
<input id="auto-tasks" type="checkbox" checked />
New work
</label>
</div>
<div id="help">
<b>Drag</b> orbit · <b>Shift/right-drag</b> pan · <b>Wheel</b> zoom<br />
Colored dashed lines are the currently reserved routes.
</div>
<div id="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Configuration and model
// ------------------------------------------------------------
const COLS = 18;
const ROWS = 14;
const CELL = 1;
const GROUND_Y = 0.12;
const PRIORITY = {
high: { rank: 3, label: "HIGH", color: 0xff786a, css: "#ff786a" },
normal: { rank: 2, label: "NORMAL", color: 0xffc768, css: "#ffc768" },
low: { rank: 1, label: "LOW", color: 0x70b9e8, css: "#70b9e8" }
};
const TASK_DEFS = {
wood: {
name: "Split logs",
short: "Timber",
skill: "timber",
source: "forest",
dest: "sawmill",
resource: "log",
output: "planks",
outputLabel: "Planks",
color: 0xe7aa68,
css: "#e7aa68"
},
grain: {
name: "Bake loaves",
short: "Grain",
skill: "grain",
source: "field",
dest: "bakery",
resource: "wheat",
output: "bread",
outputLabel: "Bread",
color: 0xf2d36b,
css: "#f2d36b"
},
stone: {
name: "Raise wall",
short: "Stone",
skill: "masonry",
source: "quarry",
dest: "site",
resource: "stone",
output: "blocks",
outputLabel: "Blocks",
color: 0xa9b5b1,
css: "#a9b5b1"
}
};
const LOCATIONS = {
forest: { anchor: [15, 9], access: [15, 10] },
field: { anchor: [2, 5], access: [2, 6] },
quarry: { anchor: [16, 3], access: [16, 4] },
sawmill: { anchor: [4, 7.5], access: [4, 9] },
bakery: { anchor: [8, 2.5], access: [8, 4] },
site: { anchor: [3, 2.5], access: [3, 4] }
};
const JOB_STATES = {
open: "QUEUED",
reserved: "RESERVED",
loading: "LOADING",
hauling: "HAULING",
unloading: "UNLOADING",
done: "DONE"
};
const WORKER_STATES = {
idle: "IDLE",
to_source: "TO SOURCE",
loading: "LOADING",
to_dest: "TO DEST",
unloading: "UNLOADING"
};
const ALLOWED_WORKER_TRANSITIONS = {
idle: ["to_source"],
to_source: ["loading"],
loading: ["to_dest"],
to_dest: ["unloading"],
unloading: ["idle"]
};
const jobs = [];
const workers = [];
const resources = [];
const inventory = { planks: 0, bread: 0, blocks: 0 };
const buildBlocks = [];
const treeCrowns = [];
const pondMeshes = [];
const smokePuffs = [];
const blocked = new Set();
const roadCells = new Set();
let jobSerial = 100;
let resourceSerial = 0;
let simTime = 0;
let realTime = 0;
let paused = false;
let speed = 1;
let schedulerTimer = 0;
let autoTimer = 6;
let completedCount = 0;
let uiTimer = 0;
// ------------------------------------------------------------
// Renderer, camera, lighting
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x183235);
scene.fog = new THREE.Fog(0x183235, 23, 48);
const camera = new THREE.PerspectiveCamera(
38,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.querySelector("#scene-wrap").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xffe8bd, 0x2b5352, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedcf, 3.0);
sun.position.set(-8, 15, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0007;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x7ec6c3, 0.85);
rim.position.set(10, 7, -12);
scene.add(rim);
const cameraRig = {
target: new THREE.Vector3(0, 0.25, 0),
radius: 22,
theta: Math.PI * 0.25,
phi: 0.86
};
function updateCamera() {
const spherical = new THREE.Spherical(
cameraRig.radius,
cameraRig.phi,
cameraRig.theta
);
const offset = new THREE.Vector3().setFromSpherical(spherical);
camera.position.copy(cameraRig.target).add(offset);
camera.lookAt(cameraRig.target);
}
updateCamera();
// ------------------------------------------------------------
// Small geometry and material helpers
// ------------------------------------------------------------
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.88,
metalness: options.metalness ?? 0,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
});
}
function box(
width,
height,
depth,
color,
x = 0,
y = 0,
z = 0,
parent = scene,
options = {}
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
typeof color === "number" ? material(color, options) : color
);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function cellToWorld(col, row) {
return new THREE.Vector3(
(col - (COLS - 1) / 2) * CELL,
GROUND_Y,
(row - (ROWS - 1) / 2) * CELL
);
}
function worldToCell(position) {
return {
c: Math.round(position.x / CELL + (COLS - 1) / 2),
r: Math.round(position.z / CELL + (ROWS - 1) / 2)
};
}
function blockRect(c, r, width, depth) {
for (let dc = 0; dc < width; dc++) {
for (let dr = 0; dr < depth; dr++) {
blocked.add(`${c + dc},${r + dr}`);
}
}
}
function roadRow(r, c0, c1) {
for (let c = Math.min(c0, c1); c <= Math.max(c0, c1); c++) {
roadCells.add(`${c},${r}`);
}
}
function roadCol(c, r0, r1) {
for (let r = Math.min(r0, r1); r <= Math.max(r0, r1); r++) {
roadCells.add(`${c},${r}`);
}
}
function textSprite(text, color = "#f6edcf", background = "#173332") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 96;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0,0,0,0.22)";
ctx.fillRect(7, 9, 498, 78);
ctx.fillStyle = background;
ctx.fillRect(0, 0, 505, 86);
ctx.strokeStyle = "rgba(255,255,255,0.18)";
ctx.lineWidth = 3;
ctx.strokeRect(2, 2, 501, 82);
ctx.fillStyle = color;
ctx.font = "700 31px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text.toUpperCase(), 252, 44);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(3.25, 0.61, 1);
sprite.renderOrder = 20;
return sprite;
}
function addLocationLabel(text, col, row, y, color) {
const sprite = textSprite(text, color);
sprite.position.copy(cellToWorld(col, row));
sprite.position.y = y;
scene.add(sprite);
return sprite;
}
// ------------------------------------------------------------
// Terrain, paths, and navigation grid
// ------------------------------------------------------------
blockRect(3, 7, 3, 2); // Sawmill
blockRect(7, 2, 3, 2); // Bakery
blockRect(12, 7, 2, 2); // East cottage
blockRect(12, 2, 2, 2); // North cottage
blockRect(2, 2, 3, 2); // Construction site
blockRect(9, 6, 2, 1); // Well
blockRect(1, 9, 2, 2); // Pond
blockRect(14, 8, 3, 2); // Forest trunks, leaving the pickup center open
blockRect(15, 2, 3, 2); // Quarry, leaving the pickup center open
roadRow(4, 3, 16);
roadRow(6, 2, 10);
roadRow(9, 4, 15);
roadRow(10, 9, 15);
roadCol(3, 4, 6);
roadCol(9, 4, 10);
roadCol(8, 4, 7);
roadCol(13, 4, 10);
roadCol(15, 4, 10);
roadCol(16, 4, 10);
const base = box(18, 0.8, 14, 0x6f563d, 0, -0.48, 0);
base.receiveShadow = true;
const lowerBase = box(17.2, 0.42, 13.2, 0x4e5147, 0, -1.02, 0);
lowerBase.receiveShadow = true;
const tileGeometry = new THREE.BoxGeometry(0.96, 0.13, 0.96);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
});
const tileCount = COLS * ROWS;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
tiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let tileIndex = 0;
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const key = `${c},${r}`;
const p = cellToWorld(c, r);
dummy.position.set(p.x, 0, p.z);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
if (roadCells.has(key)) {
color.setHex(0xb59a6d);
color.multiplyScalar(0.9 + Math.random() * 0.12);
} else if (c >= 8 && c <= 10 && r >= 6 && r <= 8) {
color.setHex(0xc9b786);
} else {
const greens = [0x78a46f, 0x7fa873, 0x729a69, 0x86ad78];
color.setHex(greens[(c * 7 + r * 3) % greens.length]);
color.multiplyScalar(0.92 + Math.random() * 0.12);
}
tiles.setColorAt(tileIndex, color);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
for (const [c, r] of [[1, 9], [2, 9], [1, 10], [2, 10]]) {
const water = box(
0.98,
0.04,
0.98,
new THREE.MeshStandardMaterial({
color: 0x5f9fa0,
roughness: 0.25,
metalness: 0.08,
transparent: true,
opacity: 0.9
}),
...(() => {
const p = cellToWorld(c, r);
return [p.x, 0.095, p.z];
})(),
scene,
{ castShadow: false }
);
pondMeshes.push(water);
}
// Small flowers and grass tufts.
for (let i = 0; i < 45; i++) {
const c = Math.floor(Math.random() * COLS);
const r = Math.floor(Math.random() * ROWS);
const key = `${c},${r}`;
if (roadCells.has(key) || blocked.has(key)) continue;
const p = cellToWorld(c, r);
const tuft = box(
0.08,
0.16,
0.08,
Math.random() > 0.65 ? 0xf1d36b : 0x9ac675,
p.x + Math.random() * 0.55 - 0.28,
0.14,
p.z + Math.random() * 0.55 - 0.28
);
tuft.rotation.y = Math.random() * Math.PI;
}
// ------------------------------------------------------------
// Buildings and scenery
// ------------------------------------------------------------
function addBuilding({
name,
col,
row,
width,
depth,
height,
wall,
roof,
labelColor = "#f6edcf"
}) {
const group = new THREE.Group();
const p = cellToWorld(col, row);
group.position.set(p.x, GROUND_Y, p.z);
scene.add(group);
box(width + 0.22, 0.18, depth + 0.22, 0x7c7768, 0, 0.09, 0, group);
box(width, height, depth, wall, 0, 0.18 + height / 2, 0, group);
for (let i = 0; i < 3; i++) {
box(
width + 0.32 - i * 0.52,
0.25,
depth + 0.32 - i * 0.28,
roof,
0,
height + 0.3 + i * 0.25,
0,
group
);
}
box(0.48, 0.78, 0.08, 0x4c5145, 0, 0.57, depth / 2 + 0.045, group);
const windowMaterial = material(0xffd889, {
emissive: 0xffa83e,
emissiveIntensity: 0.55,
roughness: 0.5
});
box(0.42, 0.38, 0.07, windowMaterial, -width * 0.28, 0.83, depth / 2 + 0.04, group);
box(0.42, 0.38, 0.07, windowMaterial, width * 0.28, 0.83, depth / 2 + 0.04, group);
box(0.07, 0.38, depth * 0.48, windowMaterial, width / 2 + 0.04, 0.84, 0, group);
box(0.25, 0.55, 0.25, 0x6d6255, width * 0.28, height + 0.88, -depth * 0.16, group);
const label = textSprite(name, labelColor);
label.position.set(p.x, GROUND_Y + height + 1.25, p.z);
scene.add(label);
return group;
}
addBuilding({
name: "Timber Shed",
col: 4,
row: 7.5,
width: 2.6,
depth: 1.65,
height: 1.35,
wall: 0x9b7048,
roof: 0x4e6652,
labelColor: "#edbd7e"
});
const bakery = addBuilding({
name: "Little bakery",
col: 8,
row: 2.5,
width: 2.65,
depth: 1.7,
height: 1.55,
wall: 0xe6c79b,
roof: 0xa95d45,
labelColor: "#f3d587"
});
addBuilding({
name: "Cedar Cottage",
col: 12.5,
row: 7.5,
width: 1.8,
depth: 1.7,
height: 1.3,
wall: 0xc9b586,
roof: 0x587367
});
addBuilding({
name: "Pine Cottage",
col: 12.5,
row: 2.5,
width: 1.8,
depth: 1.7,
height: 1.3,
wall: 0xb9c3a0,
roof: 0x3f6970
});
// Construction site and scaffold.
const site = cellToWorld(3, 2.5);
box(2.65, 0.13, 1.75, 0x95836b, site.x, 0.08, site.z);
for (const x of [-1.05, 1.05]) {
for (const z of [-0.65, 0.65]) {
box(0.11, 1.7, 0.11, 0xa27a4e, site.x + x, 0.94, site.z + z);
}
}
box(2.35, 0.1, 0.12, 0xb08a56, site.x, 1.65, site.z - 0.65);
box(2.35, 0.1, 0.12, 0xb08a56, site.x, 1.65, site.z + 0.65);
addLocationLabel("Build site", 3, 2.5, 2.45, "#d7dfce");
// Central well and market stalls.
const well = cellToWorld(9.5, 6.5);
box(0.72, 0.44, 0.72, 0x777667, well.x, 0.3, well.z);
box(0.58, 0.04, 0.58, 0x315f62, well.x, 0.54, well.z);
box(0.1, 1.1, 0.1, 0x72513c, well.x - 0.45, 0.62, well.z);
box(0.1, 1.1, 0.1, 0x72513c, well.x + 0.45, 0.62, well.z);
box(1.2, 0.16, 0.55, 0x9d664f, well.x, 1.17, well.z);
const stallA = cellToWorld(10.5, 7.5);
const stallB = cellToWorld(7.5, 6.5);
for (const [stall, color] of [[stallA, 0xd7a95f], [stallB, 0x6e9b77]]) {
box(0.85, 0.55, 0.65, 0x876d4c, stall.x, 0.38, stall.z);
for (const dx of [-0.5, 0.5]) {
box(0.08, 1.15, 0.08, 0x69513d, stall.x + dx, 0.66, stall.z - 0.35);
box(0.08, 1.15, 0.08, 0x69513d, stall.x + dx, 0.66, stall.z + 0.35);
}
box(1.3, 0.14, 0.95, color, stall.x, 1.23, stall.z);
}
// Bakery chimney smoke.
bakery.updateMatrixWorld(true);
const smokeOrigin = bakery.localToWorld(new THREE.Vector3(0.65, 2.2, -0.2));
for (let i = 0; i < 5; i++) {
const puff = box(
0.16,
0.16,
0.16,
new THREE.MeshStandardMaterial({
color: 0xe5dfca,
transparent: true,
opacity: 0.35,
roughness: 1,
depthWrite: false
}),
smokeOrigin.x,
smokeOrigin.y,
smokeOrigin.z,
scene,
{ castShadow: false, receiveShadow: false }
);
smokePuffs.push({ mesh: puff, offset: i * 0.48 });
}
function addTree(col, row, scale = 1) {
const p = cellToWorld(col, row);
const group = new THREE.Group();
group.position.set(p.x, GROUND_Y, p.z);
group.scale.setScalar(scale);
scene.add(group);
box(0.28, 1.15, 0.28, 0x70503a, 0, 0.57, 0, group);
const crown = new THREE.Group();
crown.position.y = 1.0;
group.add(crown);
box(1.18, 0.7, 1.05, 0x3f7959, 0, 0.35, 0, crown);
box(0.9, 0.65, 0.85, 0x4e8b62, 0.08, 0.85, 0.03, crown);
box(0.62, 0.55, 0.62, 0x60996a, -0.08, 1.28, -0.03, crown);
treeCrowns.push({ crown, phase: Math.random() * Math.PI * 2 });
}
[
[14, 8, 1.0], [16, 8, 1.05], [14, 9, 0.9], [16, 9, 1.0],
[1, 1, 0.9], [17, 0, 1.1], [16, 11, 0.85], [4, 11, 0.78],
[1, 6, 0.78], [17, 10, 0.95]
].forEach(([c, r, s]) => addTree(c, r, s));
// Wheat field.
const field = cellToWorld(2, 5);
for (let i = 0; i < 12; i++) {
const x = field.x - 0.75 + (i % 4) * 0.48;
const z = field.z - 0.45 + Math.floor(i / 4) * 0.42;
box(0.12, 0.42, 0.12, 0x9a7741, x, 0.3, z);
box(0.25, 0.18, 0.22, 0xe6bd58, x, 0.56, z);
}
addLocationLabel("Wheat plot", 2, 5, 1.15, "#f0d36f");
// Quarry rocks.
const quarry = cellToWorld(16, 3);
for (const [dx, dz, size] of [
[-0.75, -0.55, 0.65], [0.65, -0.6, 0.8], [-0.8, 0.55, 0.72],
[0.7, 0.55, 0.6], [0, -0.9, 0.5]
]) {
const rock = box(size, size * 0.65, size * 0.8, 0x7f8882, quarry.x + dx, size * 0.34, quarry.z + dz);
rock.rotation.y = Math.random() * 0.35;
}
addLocationLabel("Stone quarry", 16, 3, 1.25, "#c1cbc7");
addLocationLabel("Timber grove", 15, 9, 2.65, "#b9d3a3");
// ------------------------------------------------------------
// A* pathfinding on the walkable village grid
// ------------------------------------------------------------
function cellKey(c, r) {
return `${c},${r}`;
}
function isWalkable(c, r) {
return (
c >= 0 && c < COLS &&
r >= 0 && r < ROWS &&
!blocked.has(cellKey(c, r))
);
}
function nearestWalkable(c, r) {
if (isWalkable(c, r)) return { c, r };
let best = null;
let bestDistance = Infinity;
for (let dc = -3; dc <= 3; dc++) {
for (let dr = -3; dr <= 3; dr++) {
if (!isWalkable(c + dc, r + dr)) continue;
const distance = dc * dc + dr * dr;
if (distance < bestDistance) {
bestDistance = distance;
best = { c: c + dc, r: r + dr };
}
}
}
return best || { c: 8, r: 7 };
}
function findCellPath(start, end) {
start = nearestWalkable(start.c, start.r);
end = nearestWalkable(end.c, end.r);
const open = [{ ...start, f: 0 }];
const cameFrom = new Map();
const gScore = new Map([[cellKey(start.c, start.r), 0]]);
const closed = new Set();
const heuristic = (a, b) => Math.abs(a.c - b.c) + Math.abs(a.r - b.r);
while (open.length) {
open.sort((a, b) => a.f - b.f);
const current = open.shift();
const currentKey = cellKey(current.c, current.r);
if (current.c === end.c && current.r === end.r) {
const cells = [{ c: current.c, r: current.r }];
let key = currentKey;
while (cameFrom.has(key)) {
const previous = cameFrom.get(key);
cells.push({ c: previous.c, r: previous.r });
key = cellKey(previous.c, previous.r);
}
cells.reverse();
return cells;
}
closed.add(currentKey);
const neighbors = [
{ c: current.c + 1, r: current.r },
{ c: current.c - 1, r: current.r },
{ c: current.c, r: current.r + 1 },
{ c: current.c, r: current.r - 1 }
];
for (const next of neighbors) {
if (!isWalkable(next.c, next.r)) continue;
const nextKey = cellKey(next.c, next.r);
if (closed.has(nextKey)) continue;
const tentative = (gScore.get(currentKey) ?? Infinity) + 1;
if (tentative < (gScore.get(nextKey) ?? Infinity)) {
cameFrom.set(nextKey, { c: current.c, r: current.r });
gScore.set(nextKey, tentative);
open.push({
...next,
f: tentative + heuristic(next, end)
});
}
}
}
return [start];
}
function makePath(fromPosition, access) {
const start = worldToCell(fromPosition);
const end = { c: access[0], r: access[1] };
const cells = findCellPath(start, end);
const points = cells.map((cell) => cellToWorld(cell.c, cell.r));
if (points.length) {
points[0] = fromPosition.clone();
points[0].y = GROUND_Y;
}
return points;
}
// ------------------------------------------------------------
// Resources: free, reserved, carried, or consumed
// ------------------------------------------------------------
function spawnResource(type) {
const id = `R-${String(++resourceSerial).padStart(2, "0")}`;
const location = LOCATIONS[TASK_DEFS[type].source];
const siblings = resources.filter((resource) => resource.type === type && !resource.done);
const slot = siblings.length % 5;
const offsets = [
[-0.48, -0.32], [0.42, -0.28], [-0.22, 0.36],
[0.38, 0.32], [0, -0.72]
];
const group = new THREE.Group();
const p = cellToWorld(location.anchor[0], location.anchor[1]);
group.position.set(
p.x + offsets[slot][0],
GROUND_Y,
p.z + offsets[slot][1]
);
scene.add(group);
let mesh;
if (type === "wood") {
mesh = box(0.58, 0.22, 0.24, 0x98623d, 0, 0.22, 0, group);
box(0.16, 0.22, 0.25, 0xc18a52, -0.22, 0.22, 0, group);
} else if (type === "grain") {
mesh = box(0.3, 0.36, 0.28, 0xe4bd5d, 0, 0.24, 0, group);
box(0.15, 0.09, 0.15, 0xf2d776, 0, 0.45, 0, group);
} else {
mesh = box(0.4, 0.32, 0.36, 0x929c96, 0, 0.2, 0, group);
}
const ownerBadge = box(
0.12,
0.12,
0.12,
0xffc768,
0,
0.65,
0,
group,
{ emissive: 0xa86916, emissiveIntensity: 0.7 }
);
ownerBadge.visible = false;
const resource = {
id,
type,
owner: null,
status: "free",
group,
mesh,
ownerBadge,
done: false
};
resources.push(resource);
return resource;
}
for (let i = 0; i < 5; i++) spawnResource("wood");
for (let i = 0; i < 4; i++) spawnResource("grain");
for (let i = 0; i < 4; i++) spawnResource("stone");
// ------------------------------------------------------------
// Worker agents
// ------------------------------------------------------------
function createWorker({
id,
name,
skills,
color,
start
}) {
const root = new THREE.Group();
const rig = new THREE.Group();
root.add(rig);
scene.add(root);
const p = cellToWorld(start[0], start[1]);
root.position.copy(p);
const leftLeg = box(0.16, 0.34, 0.17, 0x394a46, -0.11, 0.2, 0, rig);
const rightLeg = box(0.16, 0.34, 0.17, 0x394a46, 0.11, 0.2, 0, rig);
const body = box(0.4, 0.46, 0.27, color, 0, 0.61, 0, rig);
const head = box(0.31, 0.31, 0.29, 0xe4b58d, 0, 0.98, 0.01, rig);
const hat = box(0.37, 0.12, 0.34, color, 0, 1.18, 0, rig);
box(0.39, 0.06, 0.38, color, 0, 1.12, 0, rig);
const leftArm = box(0.13, 0.39, 0.14, color, -0.28, 0.62, 0, rig);
const rightArm = box(0.13, 0.39, 0.14, color, 0.28, 0.62, 0, rig);
const cargo = new THREE.Group();
cargo.position.set(0, 0.68, -0.3);
rig.add(cargo);
const cargoMesh = box(0.35, 0.28, 0.3, 0xb57b47, 0, 0, 0, cargo);
cargo.visible = false;
const label = document.createElement("div");
label.className = "agent-label";
label.innerHTML = `${name}<span class="agent-state">IDLE</span>`;
document.querySelector("#labels").appendChild(label);
const worker = {
id,
name,
skills,
color,
root,
rig,
leftLeg,
rightLeg,
leftArm,
rightArm,
cargo,
cargoMesh,
label,
state: "idle",
stateSince: simTime,
jobId: null,
cargoResourceId: null,
path: [],
pathIndex: 0,
timer: 0,
walkPhase: Math.random() * Math.PI * 2,
routeGroup: null
};
workers.push(worker);
return worker;
}
createWorker({
id: "W1",
name: "Moss",
skills: ["timber"],
color: 0x5b9a69,
start: [8, 8]
});
createWorker({
id: "W2",
name: "Pip",
skills: ["grain"],
color: 0xd39a52,
start: [9, 8]
});
createWorker({
id: "W3",
name: "Flint",
skills: ["masonry"],
color: 0x778f96,
start: [10, 8]
});
createWorker({
id: "W4",
name: "Rell",
skills: ["timber", "grain", "masonry"],
color: 0x9c6b9a,
start: [8, 9]
});
createWorker({
id: "W5",
name: "Juno",
skills: ["grain", "timber"],
color: 0xb55e58,
start: [10, 9]
});
// ------------------------------------------------------------
// Jobs, scheduling, and worker state transitions
// ------------------------------------------------------------
function createJobMarker(job) {
const group = new THREE.Group();
const core = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.25, 0.25),
material(PRIORITY[job.priority].color, {
emissive: PRIORITY[job.priority].color,
emissiveIntensity: 0.65,
roughness: 0.35
})
);
group.add(core);
const halo = new THREE.Mesh(
new THREE.BoxGeometry(0.43, 0.43, 0.43),
new THREE.MeshBasicMaterial({
color: PRIORITY[job.priority].color,
wireframe: true,
transparent: true,
opacity: 0.45,
depthTest: false
})
);
group.add(halo);
scene.add(group);
job.marker = group;
job.markerCore = core;
job.markerHalo = halo;
}
function addJob(type, priority = "normal") {
const job = {
id: `J-${++jobSerial}`,
serial: jobSerial,
type,
priority,
status: "open",
workerId: null,
resourceId: null,
createdAt: simTime,
doneAt: null,
marker: null
};
jobs.push(job);
createJobMarker(job);
// Keep a useful history without allowing the queue to grow forever.
const completed = jobs.filter((item) => item.status === "done");
if (completed.length > 6) {
const old = completed.shift();
if (old.marker) {
scene.remove(old.marker);
}
jobs.splice(jobs.indexOf(old), 1);
}
renderUI();
return job;
}
function setWorkerState(worker, nextState) {
if (!ALLOWED_WORKER_TRANSITIONS[worker.state]?.includes(nextState)) {
console.warn(
`Invalid worker transition: ${worker.state} -> ${nextState}`
);
return false;
}
worker.state = nextState;
worker.stateSince = simTime;
updateWorkerLabel(worker);
return true;
}
function updateWorkerLabel(worker) {
worker.label.querySelector(".agent-state").textContent =
WORKER_STATES[worker.state];
}
function claimJob(job, worker, resource) {
// This is the atomic reservation step. JavaScript executes it as one
// uninterrupted transaction, so a resource cannot have two owners.
resource.owner = worker.id;
resource.status = "reserved";
resource.ownerBadge.visible = true;
job.workerId = worker.id;
job.resourceId = resource.id;
job.status = "reserved";
worker.jobId = job.id;
worker.cargoResourceId = null;
const source = LOCATIONS[TASK_DEFS[job.type].source];
worker.path = makePath(worker.root.position, source.access);
worker.pathIndex = 1;
setWorkerState(worker, "to_source");
rebuildRoute(worker);
}
function scheduleJobs() {
const openJobs = jobs
.filter((job) => job.status === "open")
.sort((a, b) => {
const priorityDifference =
PRIORITY[b.priority].rank - PRIORITY[a.priority].rank;
return priorityDifference || a.serial - b.serial;
});
for (const job of openJobs) {
const definition = TASK_DEFS[job.type];
const resource = resources.find(
(item) =>
item.type === job.type &&
!item.done &&
item.owner === null
);
const eligibleWorkers = workers.filter(
(worker) =>
worker.state === "idle" &&
worker.skills.includes(definition.skill)
);
if (resource && eligibleWorkers.length) {
// Prefer the least recently idle worker, keeping specialists stable.
eligibleWorkers.sort(
(a, b) => a.stateSince - b.stateSince || a.id.localeCompare(b.id)
);
claimJob(job, eligibleWorkers[0], resource);
}
}
}
function removeRoute(worker) {
if (!worker.routeGroup) return;
worker.routeGroup.traverse((object) => {
if (object.isLine && object.geometry) object.geometry.dispose();
});
scene.remove(worker.routeGroup);
worker.routeGroup = null;
}
const routeArrowGeometry = new THREE.BoxGeometry(0.11, 0.11, 0.11);
function rebuildRoute(worker) {
removeRoute(worker);
if (!worker.jobId) return;
const job = jobs.find((item) => item.id === worker.jobId);
if (!job) return;
const definition = TASK_DEFS[job.type];
const source = LOCATIONS[definition.source];
const destination = LOCATIONS[definition.dest];
const sourcePath = makePath(
worker.root.position,
source.access
);
const destinationPath = makePath(
cellToWorld(source.access[0], source.access[1]),
destination.access
);
const points = [];
const appendUnique = (point) => {
if (
!points.length ||
point.distanceToSquared(points[points.length - 1]) > 0.001
) {
points.push(point.clone());
}
};
sourcePath.forEach(appendUnique);
destinationPath.forEach(appendUnique);
if (points.length < 2) return;
const group = new THREE.Group();
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map((point) => new THREE.Vector3(point.x, 0.19, point.z))
);
const line = new THREE.Line(
geometry,
new THREE.LineDashedMaterial({
color: definition.color,
dashSize: 0.24,
gapSize: 0.14,
transparent: true,
opacity: 0.8,
depthTest: false,
depthWrite: false
})
);
line.computeLineDistances();
line.renderOrder = 10;
group.add(line);
const arrowMaterial = new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
});
const stride = Math.max(3, Math.floor(points.length / 7));
for (let i = 1; i < points.length; i += stride) {
const arrow = new THREE.Mesh(routeArrowGeometry, arrowMaterial);
arrow.position.set(points[i].x, 0.23, points[i].z);
arrow.renderOrder = 11;
group.add(arrow);
}
scene.add(group);
worker.routeGroup = group;
}
function beginLoading(worker) {
const job = jobs.find((item) => item.id === worker.jobId);
if (!job) return;
job.status = "loading";
worker.timer = 1.15;
setWorkerState(worker, "loading");
rebuildRoute(worker);
}
function finishLoading(worker) {
const job = jobs.find((item) => item.id === worker.jobId);
if (!job) return;
const resource = resources.find((item) => item.id === job.resourceId);
if (!resource) return;
resource.status = "carried";
resource.mesh.visible = false;
resource.ownerBadge.visible = false;
worker.cargoResourceId = resource.id;
worker.cargo.visible = true;
worker.cargoMesh.material.color.setHex(
job.type === "wood" ? 0xb77b45 :
job.type === "grain" ? 0xe1bd58 : 0x929d97
);
const destination = LOCATIONS[TASK_DEFS[job.type].dest];
worker.path = makePath(worker.root.position, destination.access);
worker.pathIndex = 1;
job.status = "hauling";
setWorkerState(worker, "to_dest");
rebuildRoute(worker);
}
function beginUnloading(worker) {
const job = jobs.find((item) => item.id === worker.jobId);
if (!job) return;
job.status = "unloading";
worker.timer = 0.95;
setWorkerState(worker, "unloading");
rebuildRoute(worker);
}
function addConstructionBlock() {
const index = buildBlocks.length;
const site = LOCATIONS.site.anchor;
const p = cellToWorld(site[0], site[1]);
const block = box(
0.42,
0.28,
0.42,
0x9aa49e,
p.x - 0.55 + (index % 3) * 0.55,
0.27 + Math.floor(index / 3) * 0.29,
p.z + (index % 2 ? 0.25 : -0.25)
);
block.rotation.y = (index % 3 - 1) * 0.08;
buildBlocks.push(block);
}
function completeJob(worker) {
const job = jobs.find((item) => item.id === worker.jobId);
if (!job) return;
const definition = TASK_DEFS[job.type];
const resource = resources.find((item) => item.id === job.resourceId);
if (resource) {
resource.status = "consumed";
resource.done = true;
resource.owner = null;
resource.mesh.visible = false;
resource.ownerBadge.visible = false;
}
inventory[definition.output] += 1;
completedCount += 1;
if (job.type === "stone") addConstructionBlock();
job.status = "done";
job.doneAt = simTime;
worker.cargo.visible = false;
worker.cargoResourceId = null;
worker.jobId = null;
setWorkerState(worker, "idle");
removeRoute(worker);
// A replacement raw item arrives at the source after delivery.
spawnResource(job.type);
showToast(
`${definition.outputLabel} delivered — ${worker.name} finished ${job.id}.`
);
renderUI();
}
function updateWorkers(dt) {
for (const worker of workers) {
const movingState =
worker.state === "to_source" || worker.state === "to_dest";
if (movingState) {
if (worker.pathIndex >= worker.path.length) {
if (worker.state === "to_source") beginLoading(worker);
else beginUnloading(worker);
} else {
const target = worker.path[worker.pathIndex];
const delta = new THREE.Vector3(
target.x - worker.root.position.x,
0,
target.z - worker.root.position.z
);
const distance = delta.length();
const step = 2.25 * dt;
if (distance <= step) {
worker.root.position.x = target.x;
worker.root.position.z = target.z;
worker.pathIndex++;
if (worker.pathIndex >= worker.path.length) {
if (worker.state === "to_source") beginLoading(worker);
else beginUnloading(worker);
}
} else {
delta.normalize();
worker.root.position.x += delta.x * step;
worker.root.position.z += delta.z * step;
const desiredAngle = Math.atan2(delta.x, delta.z);
let angleDifference =
desiredAngle - worker.root.rotation.y;
angleDifference = Math.atan2(
Math.sin(angleDifference),
Math.cos(angleDifference)
);
worker.root.rotation.y += angleDifference * Math.min(1, dt * 12);
}
}
} else if (
worker.state === "loading" ||
worker.state === "unloading"
) {
worker.timer -= dt;
if (worker.timer <= 0) {
if (worker.state === "loading") finishLoading(worker);
else completeJob(worker);
}
}
const isWalking = movingState && worker.pathIndex < worker.path.length;
worker.walkPhase += dt * (isWalking ? 9 : 1.5);
const stride = isWalking
? Math.sin(worker.walkPhase) * 0.55
: Math.sin(worker.walkPhase) * 0.04;
worker.leftLeg.rotation.x = stride;
worker.rightLeg.rotation.x = -stride;
worker.leftArm.rotation.x = -stride * 0.75;
worker.rightArm.rotation.x = stride * 0.75;
worker.rig.position.y = isWalking
? Math.abs(Math.sin(worker.walkPhase)) * 0.035
: 0;
}
}
// ------------------------------------------------------------
// UI
// ------------------------------------------------------------
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remainder = Math.floor(seconds % 60);
return `${String(minutes).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
function jobProgress(job) {
switch (job.status) {
case "open": return 0.04;
case "reserved": return 0.16;
case "loading": return 0.34;
case "hauling": return 0.64;
case "unloading": return 0.9;
case "done": return 1;
default: return 0;
}
}
function renderUI() {
const queued = jobs.filter((job) => job.status === "open").length;
const active = jobs.filter((job) =>
["reserved", "loading", "hauling", "unloading"].includes(job.status)
).length;
document.querySelector("#queued-count").textContent = queued;
document.querySelector("#active-count").textContent = active;
document.querySelector("#done-count").textContent = completedCount;
document.querySelector("#inventory-planks").textContent = inventory.planks;
document.querySelector("#inventory-bread").textContent = inventory.bread;
document.querySelector("#inventory-blocks").textContent = inventory.blocks;
const minute = Math.floor(simTime / 60) + 1;
document.querySelector("#cycle-label").textContent =
`Cycle ${minute} · ${formatTime(simTime)}`;
const sortedJobs = [...jobs].sort((a, b) => {
const activeA = a.status !== "open" && a.status !== "done";
const activeB = b.status !== "open" && b.status !== "done";
if (activeA !== activeB) return activeA ? -1 : 1;
if (a.status === "done" && b.status !== "done") return 1;
if (a.status !== "done" && b.status === "done") return -1;
return PRIORITY[b.priority].rank - PRIORITY[a.priority].rank;
});
document.querySelector("#jobs-list").innerHTML = sortedJobs
.map((job) => {
const definition = TASK_DEFS[job.type];
const worker = workers.find((item) => item.id === job.workerId);
const resource = resources.find((item) => item.id === job.resourceId);
const ownerText = worker
? `${worker.name}${resource ? ` · ${resource.id}` : ""}`
: "Awaiting eligible crew";
const priorityDisabled =
job.status !== "open" ? "disabled" : "";
return `
<article class="job" style="--task-color:${definition.css}">
<div class="job-top">
<div>
<span class="job-name">${definition.name}</span>
<span class="job-id">${job.id}</span>
</div>
<select
class="priority-select"
data-job="${job.id}"
style="color:${PRIORITY[job.priority].css}"
${priorityDisabled}
>
<option value="high" ${job.priority === "high" ? "selected" : ""}>HIGH</option>
<option value="normal" ${job.priority === "normal" ? "selected" : ""}>NORMAL</option>
<option value="low" ${job.priority === "low" ? "selected" : ""}>LOW</option>
</select>
</div>
<div class="job-meta">
<span class="state-badge ${job.priority}">${JOB_STATES[job.status]}</span>
<span>${definition.short} → ${definition.dest === "site" ? "build site" : definition.dest}</span>
</div>
<div class="job-bottom">
<span class="job-worker">${ownerText}</span>
<span class="job-worker">${definition.outputLabel}</span>
</div>
<div class="progress"><i style="width:${jobProgress(job) * 100}%"></i></div>
</article>
`;
})
.join("");
document.querySelector("#worker-list").innerHTML = workers
.map((worker) => {
const job = jobs.find((item) => item.id === worker.jobId);
const cargo = worker.cargoResourceId
? ` · carrying ${worker.cargoResourceId}`
: "";
return `
<div class="worker-row" style="--worker-color:#${worker.color.toString(16).padStart(6, "0")}">
<span class="worker-dot"></span>
<div>
<div class="worker-name">${worker.name}</div>
<div class="worker-detail">
${job ? `${job.id}${cargo}` : "Available for work"}
</div>
</div>
<div class="worker-state">${WORKER_STATES[worker.state]}</div>
</div>
`;
})
.join("");
const held = resources.filter(
(resource) => resource.owner && !resource.done
);
const heldHtml = held.length
? held.map((resource) => {
const owner = workers.find((worker) => worker.id === resource.owner);
return `
<div class="resource-row">
<span><strong>${resource.id}</strong> · ${resource.type}</span>
<span>${owner?.name || resource.owner}</span>
</div>
`;
}).join("")
: `<div class="resource-row"><span>No resources held</span><span>all free</span></div>`;
const counts = {};
for (const type of ["wood", "grain", "stone"]) {
const all = resources.filter((resource) => resource.type === type && !resource.done);
const free = all.filter((resource) => !resource.owner).length;
counts[type] = `${free} free / ${all.length - free} held`;
}
document.querySelector("#resource-list").innerHTML =
heldHtml +
`
<div class="resource-row">
<span><strong>Wood</strong></span><span>${counts.wood}</span>
</div>
<div class="resource-row">
<span><strong>Grain</strong></span><span>${counts.grain}</span>
</div>
<div class="resource-row">
<span><strong>Stone</strong></span><span>${counts.stone}</span>
</div>
`;
}
let toastTimeout;
function showToast(message) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => toast.classList.remove("show"), 2600);
}
document.querySelector("#jobs-list").addEventListener("change", (event) => {
const select = event.target.closest("select[data-job]");
if (!select) return;
const job = jobs.find((item) => item.id === select.dataset.job);
if (!job || job.status !== "open") return;
job.priority = select.value;
showToast(`${job.id} priority changed to ${PRIORITY[job.priority].label}.`);
renderUI();
});
document.querySelectorAll("[data-add]").forEach((button) => {
button.addEventListener("click", () => {
const priority = document.querySelector("#new-priority").value;
const job = addJob(button.dataset.add, priority);
showToast(`${job.id} added to the ${PRIORITY[priority].label.toLowerCase()} queue.`);
scheduleJobs();
renderUI();
});
});
document.querySelector("#pause-button").addEventListener("click", (event) => {
paused = !paused;
event.currentTarget.textContent = paused ? "Resume" : "Pause";
showToast(paused ? "Village simulation paused." : "Village simulation resumed.");
});
document.querySelector("#speed").addEventListener("input", (event) => {
speed = Number(event.target.value);
document.querySelector("#speed-value").textContent = `${speed}×`;
});
document.querySelector("#reset-view").addEventListener("click", () => {
cameraRig.target.set(0, 0.25, 0);
cameraRig.radius = 22;
cameraRig.theta = Math.PI * 0.25;
cameraRig.phi = 0.86;
updateCamera();
});
// ------------------------------------------------------------
// Direct camera controls: no addons
// ------------------------------------------------------------
const canvas = renderer.domElement;
const pointers = new Map();
let dragging = false;
let previousPointer = { x: 0, y: 0 };
let previousPinchDistance = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
dragging = true;
previousPointer = { x: event.clientX, y: event.clientY };
if (pointers.size === 2) {
const values = [...pointers.values()];
previousPinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (previousPinchDistance) {
cameraRig.radius = THREE.MathUtils.clamp(
cameraRig.radius * (previousPinchDistance / distance),
10,
34
);
}
previousPinchDistance = distance;
return;
}
if (!dragging) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
previousPointer = { x: event.clientX, y: event.clientY };
const wantsPan =
event.shiftKey || event.buttons === 2 || event.buttons === 4;
if (wantsPan) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = cameraRig.target.clone().sub(camera.position);
forward.y = 0;
forward.normalize();
const panScale = cameraRig.radius * 0.0011;
cameraRig.target.addScaledVector(right, -dx * panScale);
cameraRig.target.addScaledVector(forward, -dy * panScale);
cameraRig.target.x = THREE.MathUtils.clamp(cameraRig.target.x, -6, 6);
cameraRig.target.z = THREE.MathUtils.clamp(cameraRig.target.z, -5, 5);
} else {
cameraRig.theta -= dx * 0.006;
cameraRig.phi = THREE.MathUtils.clamp(
cameraRig.phi + dy * 0.005,
0.45,
1.28
);
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
dragging = pointers.size > 0;
previousPinchDistance = 0;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraRig.radius = THREE.MathUtils.clamp(
cameraRig.radius * Math.exp(event.deltaY * 0.001),
10,
34
);
}, { passive: false });
// ------------------------------------------------------------
// Animation and simulation loop
// ------------------------------------------------------------
function updateMarkers(delta) {
for (const job of jobs) {
if (!job.marker) continue;
const worker = workers.find((item) => item.id === job.workerId);
const destination = LOCATIONS[TASK_DEFS[job.type].dest];
if (job.status === "open") {
const p = cellToWorld(destination.anchor[0], destination.anchor[1]);
job.marker.position.set(p.x, 2.6 + Math.sin(realTime * 2.5 + job.serial) * 0.12, p.z);
} else if (worker) {
job.marker.position.set(
worker.root.position.x,
1.65 + Math.sin(realTime * 3 + job.serial) * 0.08,
worker.root.position.z
);
}
job.markerCore.rotation.x += delta * 1.4;
job.markerCore.rotation.y += delta * 1.8;
job.markerHalo.rotation.y -= delta * 0.8;
if (job.status === "done" && simTime - job.doneAt > 3) {
job.marker.visible = false;
} else {
job.marker.visible = true;
}
}
}
function updateScenery(delta) {
for (const tree of treeCrowns) {
tree.crown.rotation.z = Math.sin(realTime * 0.75 + tree.phase) * 0.018;
}
for (let i = 0; i < pondMeshes.length; i++) {
pondMeshes[i].position.y =
0.095 + Math.sin(realTime * 1.3 + i) * 0.008;
}
for (const puff of smokePuffs) {
const cycle = (realTime * 0.34 + puff.offset) % 2.4;
puff.mesh.position.y = smokeOrigin.y + cycle;
puff.mesh.position.x = smokeOrigin.x + Math.sin(cycle * 2.2) * 0.12;
puff.mesh.material.opacity = 0.38 * (1 - cycle / 2.4);
const scale = 0.75 + cycle * 0.6;
puff.mesh.scale.setScalar(scale);
}
}
const projected = new THREE.Vector3();
function updateAgentLabels() {
for (const worker of workers) {
projected.copy(worker.root.position);
projected.y += 1.55;
projected.project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
worker.label.style.opacity = visible ? "1" : "0";
if (visible) {
worker.label.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
worker.label.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
}
}
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", resize);
// Seed the queue so the village begins working immediately.
addJob("wood", "high");
addJob("grain", "normal");
addJob("stone", "low");
scheduleJobs();
renderUI();
let lastTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const rawDelta = Math.min((now - lastTime) / 1000, 0.05);
lastTime = now;
realTime += rawDelta;
if (!paused) {
const delta = rawDelta * speed;
simTime += delta;
schedulerTimer -= delta;
if (schedulerTimer <= 0) {
scheduleJobs();
schedulerTimer = 0.35;
}
autoTimer -= delta;
if (autoTimer <= 0) {
if (document.querySelector("#auto-tasks").checked) {
const types = ["wood", "grain", "stone"];
const type = types[Math.floor(Math.random() * types.length)];
const priority = Math.random() > 0.72 ? "high" :
Math.random() > 0.5 ? "normal" : "low";
addJob(type, priority);
scheduleJobs();
}
autoTimer = 8 + Math.random() * 4;
}
updateWorkers(delta);
}
updateScenery(rawDelta);
updateMarkers(rawDelta);
updateCamera();
updateAgentLabels();
uiTimer += rawDelta;
if (uiTimer > 0.2) {
renderUI();
uiTimer = 0;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```