Prompt specification
Build or customize the Three.js 3D scene "Settlement Crafting Network" 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: Settlement Crafting Network
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/settlement-crafting-network-x3567
Scene Description Prompt:
A voxel settlement crafting game with explicit recipes and inventory moving between connected workshops and stores. Three.js from cdnjs, one HTML file.
Working Three.js Starter (settlement-crafting-network-x3567):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timberwick — Voxel Settlement</title>
<style>
:root {
--ink: #26332d;
--muted: #6f786f;
--paper: rgba(250, 247, 235, 0.94);
--paper-solid: #faf7eb;
--line: rgba(63, 76, 66, 0.15);
--green: #426b4b;
--green-dark: #294c35;
--gold: #d69b3d;
--danger: #a84e3f;
--shadow: 0 16px 45px rgba(35, 48, 40, 0.18);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d8d7;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, select { font: inherit; }
button {
border: 0;
cursor: pointer;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.glass {
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.62);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#topbar {
position: fixed;
z-index: 20;
top: 14px;
left: 16px;
right: 16px;
height: 58px;
border-radius: 17px;
display: flex;
align-items: center;
padding: 0 12px 0 18px;
gap: 16px;
}
.brand {
min-width: 185px;
display: flex;
align-items: center;
gap: 11px;
}
.brand-mark {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border-radius: 9px;
color: #fff7dc;
background: linear-gradient(145deg, #5f845b, #31543a);
box-shadow: inset 0 0 0 1px rgba(255,255,255,.18);
font-size: 19px;
}
.brand h1 {
margin: 0;
font-size: 15px;
letter-spacing: .12em;
line-height: 1;
}
.brand small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
letter-spacing: .05em;
}
#headerStats {
display: flex;
align-items: center;
gap: 7px;
flex: 1;
}
.stat {
padding: 6px 10px;
border-radius: 10px;
background: rgba(255,255,255,.55);
border: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
white-space: nowrap;
}
.stat strong {
color: var(--ink);
font-size: 13px;
margin-right: 3px;
}
.top-actions {
display: flex;
gap: 7px;
}
.icon-button {
width: 36px;
height: 36px;
display: grid;
place-items: center;
border-radius: 10px;
color: var(--ink);
background: rgba(255,255,255,.58);
border: 1px solid var(--line);
transition: transform .15s, background .15s;
}
.icon-button:hover {
transform: translateY(-1px);
background: #fff;
}
#questPanel {
position: fixed;
z-index: 12;
top: 86px;
left: 16px;
width: 284px;
border-radius: 17px;
padding: 15px;
}
.eyebrow {
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: .14em;
text-transform: uppercase;
}
#questPanel h2 {
margin: 5px 0 4px;
font-size: 17px;
}
.quest-subtitle {
margin-bottom: 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.progress-track {
height: 6px;
border-radius: 999px;
background: rgba(54, 75, 60, .12);
overflow: hidden;
margin-bottom: 12px;
}
#questProgress {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #658b5c, #d5a24a);
transition: width .35s ease;
}
#questList {
display: grid;
gap: 8px;
}
.quest {
display: grid;
grid-template-columns: 21px 1fr;
gap: 8px;
align-items: start;
font-size: 11px;
}
.quest-check {
width: 19px;
height: 19px;
border-radius: 50%;
display: grid;
place-items: center;
border: 1px solid rgba(51, 77, 59, .25);
color: #8a958c;
font-size: 10px;
font-weight: 800;
}
.quest.done .quest-check {
color: white;
background: var(--green);
border-color: var(--green);
}
.quest strong {
display: block;
font-size: 11px;
margin-bottom: 2px;
}
.quest span {
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.quest.done strong { color: var(--green); }
#sidePanel {
position: fixed;
z-index: 15;
top: 86px;
right: 16px;
bottom: 91px;
width: 372px;
border-radius: 19px;
overflow: hidden;
display: flex;
flex-direction: column;
}
.panel-scroll {
overflow-y: auto;
padding: 18px;
scrollbar-width: thin;
scrollbar-color: rgba(59, 80, 64, .25) transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
}
.panel-title {
display: flex;
align-items: center;
gap: 10px;
}
.building-icon {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border-radius: 12px;
background: #e8eddd;
border: 1px solid var(--line);
font-size: 21px;
}
.panel-title h2 {
margin: 0;
font-size: 19px;
letter-spacing: -.02em;
}
.panel-title p {
margin: 3px 0 0;
color: var(--muted);
font-size: 10px;
letter-spacing: .06em;
text-transform: uppercase;
}
.connected-pill {
padding: 5px 7px;
border-radius: 999px;
background: rgba(78, 119, 82, .1);
color: var(--green);
font-size: 9px;
font-weight: 800;
white-space: nowrap;
}
.description {
margin: 0 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.section {
padding-top: 15px;
margin-top: 15px;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.section-title h3 {
margin: 0;
font-size: 12px;
letter-spacing: .06em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 10px;
}
.inventory-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 7px;
}
.item {
display: flex;
align-items: center;
min-width: 0;
gap: 8px;
padding: 8px;
border-radius: 10px;
background: rgba(255,255,255,.52);
border: 1px solid rgba(63,76,66,.09);
}
.item-icon {
flex: 0 0 auto;
width: 25px;
height: 25px;
display: grid;
place-items: center;
border-radius: 7px;
font-size: 14px;
background: color-mix(in srgb, var(--item-color) 25%, white);
border: 1px solid color-mix(in srgb, var(--item-color) 35%, transparent);
}
.item-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 10px;
}
.item-count {
font-size: 11px;
font-weight: 800;
}
.empty-note {
padding: 12px;
border-radius: 10px;
background: rgba(255,255,255,.35);
color: var(--muted);
text-align: center;
font-size: 11px;
}
.recipe {
margin-bottom: 9px;
padding: 11px;
border-radius: 12px;
background: rgba(255,255,255,.56);
border: 1px solid rgba(63,76,66,.1);
}
.recipe-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.recipe h4 {
margin: 0;
font-size: 12px;
}
.recipe-blurb {
margin: 5px 0 9px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.recipe-line {
display: flex;
align-items: center;
gap: 5px;
flex-wrap: wrap;
font-size: 10px;
}
.requirement {
padding: 4px 6px;
border-radius: 6px;
background: rgba(85, 95, 83, .07);
color: var(--muted);
}
.requirement.met {
color: var(--green-dark);
background: rgba(77, 121, 82, .13);
}
.requirement.missing {
color: var(--danger);
background: rgba(168,78,63,.09);
}
.recipe-arrow {
color: #92998f;
padding: 0 2px;
}
.craft-button {
width: 100%;
margin-top: 10px;
padding: 8px 10px;
border-radius: 9px;
color: white;
background: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: .05em;
text-transform: uppercase;
transition: transform .15s, background .15s;
}
.craft-button:hover:not(:disabled) {
transform: translateY(-1px);
background: var(--green-dark);
}
.craft-button:disabled {
cursor: not-allowed;
opacity: .35;
}
.route-box {
padding: 10px;
margin-bottom: 9px;
border-radius: 11px;
background: rgba(68, 91, 68, .07);
}
.route-grid {
display: grid;
grid-template-columns: 1fr 31px 1fr;
gap: 6px;
align-items: end;
}
.field-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .07em;
text-transform: uppercase;
}
select {
width: 100%;
height: 34px;
padding: 0 25px 0 8px;
border-radius: 8px;
border: 1px solid rgba(57,74,61,.16);
background: #fffdf5;
color: var(--ink);
font-size: 10px;
outline: none;
}
.swap-button {
width: 31px;
height: 34px;
border-radius: 8px;
background: rgba(255,255,255,.78);
color: var(--green);
border: 1px solid var(--line);
font-weight: 800;
}
.route-note {
margin-top: 8px;
color: var(--muted);
font-size: 9px;
line-height: 1.35;
}
.amount-row {
display: flex;
align-items: center;
gap: 4px;
margin: 8px 0;
}
.amount-row .field-label { margin: 0 5px 0 0; }
.amount-button {
min-width: 29px;
height: 25px;
padding: 0 8px;
border-radius: 7px;
color: var(--muted);
background: rgba(255,255,255,.55);
border: 1px solid var(--line);
font-size: 9px;
font-weight: 800;
}
.amount-button.active {
color: white;
background: var(--green);
border-color: var(--green);
}
.transfer-list {
display: grid;
gap: 5px;
}
.transfer-row {
display: grid;
grid-template-columns: 26px 1fr auto auto;
gap: 7px;
align-items: center;
padding: 6px 7px;
border-radius: 9px;
background: rgba(255,255,255,.4);
}
.transfer-row .item-icon {
width: 24px;
height: 24px;
}
.transfer-row strong {
font-size: 10px;
}
.destination-count {
color: var(--muted);
font-size: 9px;
}
.send-button {
min-width: 55px;
padding: 6px 7px;
border-radius: 7px;
color: var(--green-dark);
background: rgba(77,121,82,.13);
font-size: 9px;
font-weight: 800;
}
.send-button:disabled {
cursor: not-allowed;
opacity: .3;
}
.connections {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.connection {
padding: 5px 7px;
border-radius: 7px;
background: rgba(255,255,255,.52);
border: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
}
#buildBar {
position: fixed;
z-index: 18;
left: 50%;
bottom: 15px;
transform: translateX(-50%);
max-width: calc(100vw - 32px);
display: flex;
gap: 7px;
padding: 8px;
border-radius: 16px;
overflow-x: auto;
scrollbar-width: none;
}
#buildBar::-webkit-scrollbar { display: none; }
.build-chip {
flex: 0 0 auto;
min-width: 112px;
padding: 8px 10px;
border-radius: 11px;
text-align: left;
color: var(--ink);
background: rgba(255,255,255,.53);
border: 1px solid transparent;
transition: transform .15s, background .15s;
}
.build-chip:hover {
transform: translateY(-2px);
background: rgba(255,255,255,.9);
}
.build-chip.active {
background: #fffdf4;
border-color: rgba(64,104,72,.45);
box-shadow: 0 5px 15px rgba(45,66,50,.1);
}
.build-chip .chip-row {
display: flex;
align-items: center;
gap: 7px;
}
.build-chip .chip-icon { font-size: 16px; }
.build-chip strong { font-size: 10px; }
.build-chip small {
display: block;
margin: 4px 0 0 23px;
color: var(--muted);
font-size: 9px;
}
#viewControls {
position: fixed;
z-index: 13;
right: 404px;
bottom: 20px;
display: flex;
gap: 6px;
}
.view-button {
width: 34px;
height: 34px;
border-radius: 10px;
background: rgba(250,247,235,.88);
border: 1px solid rgba(255,255,255,.65);
box-shadow: 0 8px 22px rgba(35,48,40,.13);
color: var(--ink);
font-weight: 800;
}
#toastStack {
position: fixed;
z-index: 50;
top: 84px;
left: 50%;
transform: translateX(-50%);
display: grid;
gap: 7px;
pointer-events: none;
}
.toast {
min-width: 230px;
max-width: 360px;
padding: 10px 14px;
border-radius: 11px;
color: white;
background: rgba(39,61,46,.94);
box-shadow: 0 10px 28px rgba(28,44,33,.25);
font-size: 11px;
text-align: center;
animation: toast-in .25s ease-out;
}
.toast.warn { background: rgba(133,79,47,.95); }
@keyframes toast-in {
from { opacity: 0; transform: translateY(-8px); }
to { opacity: 1; transform: translateY(0); }
}
#hoverTip {
position: fixed;
z-index: 40;
display: none;
pointer-events: none;
padding: 7px 9px;
border-radius: 8px;
color: white;
background: rgba(35,48,40,.9);
font-size: 10px;
box-shadow: 0 7px 18px rgba(25,37,29,.18);
}
#helpModal {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
padding: 20px;
background: rgba(30,45,35,.42);
backdrop-filter: blur(5px);
}
#helpModal.hidden { display: none; }
.help-card {
width: min(480px, 100%);
border-radius: 20px;
padding: 24px;
background: var(--paper-solid);
box-shadow: var(--shadow);
}
.help-card h2 {
margin: 0 0 6px;
font-size: 22px;
}
.help-card p {
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.help-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin: 17px 0;
}
.help-item {
padding: 10px;
border-radius: 10px;
background: #edf0e4;
font-size: 11px;
line-height: 1.4;
}
.help-item strong {
display: block;
margin-bottom: 3px;
}
.primary-button {
width: 100%;
padding: 10px;
border-radius: 10px;
color: white;
background: var(--green);
font-weight: 800;
}
@media (max-width: 980px) {
#questPanel { display: none; }
#viewControls { right: 16px; bottom: 89px; }
}
@media (max-width: 620px) {
#topbar {
top: 8px;
left: 8px;
right: 8px;
height: 52px;
padding-left: 10px;
}
.brand { min-width: 0; }
.brand small, .stat:nth-child(n+2) { display: none; }
.brand h1 { font-size: 12px; }
.brand-mark { width: 30px; height: 30px; }
#sidePanel {
top: auto;
left: 8px;
right: 8px;
bottom: 8px;
width: auto;
height: 47vh;
border-radius: 16px;
}
#buildBar {
left: 8px;
right: 8px;
bottom: calc(47vh + 16px);
transform: none;
max-width: none;
}
.build-chip { min-width: 103px; }
#viewControls { right: 12px; bottom: calc(47vh + 75px); }
#toastStack { top: 68px; }
.help-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div id="scene"></div>
<header id="topbar" class="glass">
<div class="brand">
<div class="brand-mark">⌂</div>
<div>
<h1>TIMBERWICK</h1>
<small>VOXEL SETTLEMENT</small>
</div>
</div>
<div id="headerStats"></div>
<div class="top-actions">
<button id="soundButton" class="icon-button" title="Toggle sound">♫</button>
<button id="helpButton" class="icon-button" title="How to play">?</button>
<button id="resetButton" class="icon-button" title="Reset settlement">↻</button>
</div>
</header>
<aside id="questPanel" class="glass">
<div class="eyebrow">Settlement Orders</div>
<h2>A Useful Tool</h2>
<div class="quest-subtitle">Move supplies along the roads, then craft something the settlement needs.</div>
<div class="progress-track"><div id="questProgress"></div></div>
<div id="questList"></div>
</aside>
<aside id="sidePanel" class="glass">
<div id="panelContent" class="panel-scroll"></div>
</aside>
<nav id="buildBar" class="glass"></nav>
<div id="viewControls">
<button class="view-button" id="rotateLeft" title="Rotate left">↶</button>
<button class="view-button" id="rotateRight" title="Rotate right">↷</button>
<button class="view-button" id="zoomIn" title="Zoom in">+</button>
<button class="view-button" id="zoomOut" title="Zoom out">−</button>
</div>
<div id="toastStack"></div>
<div id="hoverTip"></div>
<div id="helpModal" class="hidden">
<div class="help-card">
<div class="eyebrow">Welcome, Settler</div>
<h2>Build a working village</h2>
<p>Every workshop keeps its own inventory. Recipes consume materials from that workshop and place their output there. Use the logistics panel to move stock between connected buildings.</p>
<div class="help-grid">
<div class="help-item"><strong>Inspect</strong>Click a building or a card in the bottom bar.</div>
<div class="help-item"><strong>Craft</strong>Open a workshop and choose an explicit recipe.</div>
<div class="help-item"><strong>Move stock</strong>Choose a source, destination, amount, then press Move.</div>
<div class="help-item"><strong>Camera</strong>Drag to orbit, Shift-drag to pan, and scroll to zoom.</div>
</div>
<p><strong>First goal:</strong> supply the Sawmill, make planks, move them and stone to the Smithy, forge a tool, and deliver it to the Central Store.</p>
<button id="closeHelp" class="primary-button">Start building</button>
</div>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
const ITEM_DEFS = {
wood: { name: 'Wood', icon: '🪵', color: '#986b42' },
stone: { name: 'Stone', icon: '🪨', color: '#8c9691' },
fiber: { name: 'Fiber', icon: '🌾', color: '#c6a25e' },
plank: { name: 'Plank', icon: '🟫', color: '#b68148' },
beam: { name: 'Beam', icon: '▰', color: '#7b5030' },
cloth: { name: 'Cloth', icon: '🧵', color: '#b96979' },
rope: { name: 'Rope', icon: '🪢', color: '#b69258' },
brick: { name: 'Brick', icon: '🧱', color: '#b65f45' },
block: { name: 'Block', icon: '⬜', color: '#87928c' },
tool: { name: 'Tool', icon: '🔨', color: '#526d79' },
lamp: { name: 'Lamp', icon: '🏮', color: '#d6a441' }
};
const BUILDINGS = {
store: {
name: 'Central Store',
short: 'Central Store',
icon: '🏪',
type: 'store',
grid: [0, 0],
description: 'The settlement’s main supply depot. Keep tools and raw materials here for the whole village.'
},
depot: {
name: 'Supply Depot',
short: 'Supply Depot',
icon: '📦',
type: 'store',
grid: [0, 6],
description: 'A secondary roadside store. It links the northern workshops to the southern production district.'
},
sawmill: {
name: 'Sawmill',
short: 'Sawmill',
icon: '🪚',
type: 'workshop',
grid: [-4, -3],
description: 'Turns rough wood into usable building pieces. The settlement always needs more planks.'
},
weaver: {
name: 'Fiber Hut',
short: 'Fiber Hut',
icon: '🧶',
type: 'workshop',
grid: [4, -3],
description: 'Spins harvested fiber into cloth and sturdy rope for tools and construction.'
},
mason: {
name: 'Stoneworks',
short: 'Stoneworks',
icon: '🧱',
type: 'workshop',
grid: [-4, 3],
description: 'Cuts and fires stone into bricks and solid building blocks.'
},
smithy: {
name: 'Smithy',
short: 'Smithy',
icon: '⚒️',
type: 'workshop',
grid: [4, 3],
description: 'Combines planks and stone into durable tools. A finished tool belongs in the Central Store.'
}
};
const RECIPES = {
sawmill: [
{
id: 'planks',
name: 'Rough Planks',
inputs: { wood: 2 },
output: { plank: 2 },
blurb: 'Split two logs into clean construction planks.'
},
{
id: 'beams',
name: 'Support Beam',
inputs: { wood: 3, plank: 2 },
output: { beam: 1 },
blurb: 'Join rough wood and planks into a load-bearing beam.'
}
],
weaver: [
{
id: 'cloth',
name: 'Woven Cloth',
inputs: { fiber: 2 },
output: { cloth: 1 },
blurb: 'Twist and weave harvested fiber into a useful sheet of cloth.'
},
{
id: 'rope',
name: 'Sturdy Rope',
inputs: { fiber: 3 },
output: { rope: 1 },
blurb: 'Twist three measures of fiber into a strong length of rope.'
}
],
mason: [
{
id: 'bricks',
name: 'Fired Brick',
inputs: { stone: 2 },
output: { brick: 1 },
blurb: 'Shape and fire two rough stones into a durable brick.'
},
{
id: 'blocks',
name: 'Stone Blocks',
inputs: { stone: 3, brick: 1 },
output: { block: 2 },
blurb: 'Combine fresh stone with a fired brick to make two masonry blocks.'
}
],
smithy: [
{
id: 'tool',
name: 'Village Tool',
inputs: { plank: 2, stone: 1 },
output: { tool: 1 },
blurb: 'Fashion a dependable tool from two planks and one stone.'
},
{
id: 'lamp',
name: 'Oil Lantern',
inputs: { cloth: 1, rope: 1, block: 1 },
output: { lamp: 1 },
blurb: 'Build a warm lantern for workshops and village paths.'
}
]
};
const EDGE_DEFS = [
['store', 'sawmill'],
['store', 'weaver'],
['store', 'mason'],
['store', 'smithy'],
['store', 'depot'],
['mason', 'depot'],
['smithy', 'depot']
];
const SAVE_KEY = 'timberwick-settlement-v1';
function initialState() {
return {
selectedId: 'sawmill',
inventories: {
store: { wood: 18, stone: 10, fiber: 14, plank: 0, beam: 0, cloth: 0, rope: 0, brick: 0, block: 0, tool: 0, lamp: 0 },
depot: { wood: 6, stone: 8, fiber: 0, plank: 0, beam: 0, cloth: 0, rope: 0, brick: 0, block: 0, tool: 0, lamp: 0 },
sawmill: { wood: 4, stone: 0, fiber: 0, plank: 0, beam: 0, cloth: 0, rope: 0, brick: 0, block: 0, tool: 0, lamp: 0 },
weaver: { wood: 0, stone: 0, fiber: 6, plank: 0, beam: 0, cloth: 0, rope: 0, brick: 0, block: 0, tool: 0, lamp: 0 },
mason: { wood: 0, stone: 6, fiber: 0, plank: 0, beam: 0, cloth: 0, rope: 0, brick: 0, block: 0, tool: 0, lamp: 0 },
smithy: { wood: 0, stone: 0, fiber: 0, plank: 0, beam: 0, cloth: 0, rope: 0, brick: 0, block: 0, tool: 0, lamp: 0 }
},
stats: {
shipments: 0,
craftedTotal: 0,
craftedBy: {}
},
milestones: {
woodSupplied: false,
planksMade: false,
smithyStocked: false,
toolForged: false,
toolDelivered: false
}
};
}
function loadState() {
const base = initialState();
try {
const raw = localStorage.getItem(SAVE_KEY);
if (!raw) return base;
const saved = JSON.parse(raw);
return {
...base,
...saved,
inventories: { ...base.inventories, ...(saved.inventories || {}) },
stats: { ...base.stats, ...(saved.stats || {}) },
milestones: { ...base.milestones, ...(saved.milestones || {}) }
};
} catch {
return base;
}
}
const state = loadState();
let selectedId = state.selectedId || 'sawmill';
let logisticsSource = selectedId;
let logisticsDest = selectedId === 'store' ? 'sawmill' : 'store';
let transferAmount = 1;
let soundEnabled = true;
let audioContext = null;
const panelContent = document.getElementById('panelContent');
const buildBar = document.getElementById('buildBar');
const headerStats = document.getElementById('headerStats');
const questList = document.getElementById('questList');
const questProgress = document.getElementById('questProgress');
const toastStack = document.getElementById('toastStack');
const hoverTip = document.getElementById('hoverTip');
function saveState() {
state.selectedId = selectedId;
try { localStorage.setItem(SAVE_KEY, JSON.stringify(state)); } catch (error) { if (error.name !== "SecurityError") throw error; }
}
function playTone(frequency = 520, duration = 0.08, type = 'sine') {
if (!soundEnabled) return;
try {
audioContext ||= new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
oscillator.type = type;
oscillator.frequency.value = frequency;
gain.gain.setValueAtTime(0.045, audioContext.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + duration);
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + duration);
} catch {}
}
function showToast(message, type = '') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.textContent = message;
toastStack.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transition = 'opacity .25s';
setTimeout(() => toast.remove(), 250);
}, 2600);
}
function inventoryTotal(id) {
return Object.values(state.inventories[id]).reduce((sum, count) => sum + count, 0);
}
function totalStock() {
return Object.values(state.inventories).reduce(
(sum, inventory) => sum + Object.values(inventory).reduce((n, count) => n + count, 0),
0
);
}
function graphNeighbors(id) {
return EDGE_DEFS
.filter(([a, b]) => a === id || b === id)
.map(([a, b]) => a === id ? b : a);
}
function findRoute(source, destination) {
if (source === destination) return null;
const queue = [source];
const visited = new Set([source]);
const parent = new Map();
while (queue.length) {
const current = queue.shift();
for (const next of graphNeighbors(current)) {
if (visited.has(next)) continue;
visited.add(next);
parent.set(next, current);
if (next === destination) {
const edges = [];
let cursor = destination;
while (cursor !== source) {
const previous = parent.get(cursor);
edges.unshift([previous, cursor]);
cursor = previous;
}
return { edges };
}
queue.push(next);
}
}
return null;
}
function getRecipe(buildingId, recipeId) {
return (RECIPES[buildingId] || []).find(recipe => recipe.id === recipeId);
}
function canCraft(recipe, inventory) {
return Object.entries(recipe.inputs).every(([item, count]) => (inventory[item] || 0) >= count);
}
function updateMilestones(silent = false) {
const inventory = state.inventories;
const checks = {
woodSupplied: inventory.sawmill.wood >= 4,
planksMade: (state.stats.craftedBy.plank || 0) >= 2,
smithyStocked: inventory.smithy.plank >= 1 && inventory.smithy.stone >= 1,
toolForged: (state.stats.craftedBy.tool || 0) >= 1,
toolDelivered: inventory.store.tool >= 1
};
const newlyCompleted = [];
for (const [key, done] of Object.entries(checks)) {
if (done && !state.milestones[key]) newlyCompleted.push(key);
state.milestones[key] = done;
}
if (!silent) {
const labels = {
woodSupplied: 'The Sawmill is supplied.',
planksMade: 'Two planks have been made.',
smithyStocked: 'The Smithy has its materials.',
toolForged: 'A village tool has been forged.',
toolDelivered: 'The tool reached the Central Store!'
};
newlyCompleted.forEach(key => showToast(labels[key]));
}
}
function itemIcon(item) {
const def = ITEM_DEFS[item];
return `<span class="item-icon" style="--item-color:${def.color}">${def.icon}</span>`;
}
function renderHeader() {
const day = Math.floor(state.stats.shipments / 4) + 1;
headerStats.innerHTML = `
<div class="stat"><strong>Day ${day}</strong></div>
<div class="stat"><strong>${totalStock()}</strong> items</div>
<div class="stat"><strong>${state.stats.craftedTotal}</strong> crafted</div>
<div class="stat"><strong>${state.stats.shipments}</strong> shipped</div>
`;
}
function renderQuests() {
const quests = [
['woodSupplied', 'Supply the Sawmill', 'Move at least 4 Wood to the Sawmill.'],
['planksMade', 'Make two planks', 'Craft Rough Planks at the Sawmill.'],
['smithyStocked', 'Stock the Smithy', 'Move 1 Plank and 1 Stone to the Smithy.'],
['toolForged', 'Forge a tool', 'Craft a Village Tool at the Smithy.'],
['toolDelivered', 'Complete the order', 'Move the tool to the Central Store.']
];
const doneCount = quests.filter(([key]) => state.milestones[key]).length;
questProgress.style.width = `${doneCount / quests.length * 100}%`;
questList.innerHTML = quests.map(([key, title, detail], index) => `
<div class="quest ${state.milestones[key] ? 'done' : ''}">
<div class="quest-check">${state.milestones[key] ? '✓' : index + 1}</div>
<div><strong>${title}</strong><span>${detail}</span></div>
</div>
`).join('');
}
function renderBuildBar() {
buildBar.innerHTML = Object.entries(BUILDINGS).map(([id, building]) => `
<button class="build-chip ${selectedId === id ? 'active' : ''}" data-building="${id}">
<div class="chip-row">
<span class="chip-icon">${building.icon}</span>
<strong>${building.short}</strong>
</div>
<small>${inventoryTotal(id)} items in stock</small>
</button>
`).join('');
}
function renderInventory(inventory) {
const entries = Object.entries(ITEM_DEFS).map(([id, def]) => `
<div class="item">
${itemIcon(id)}
<span class="item-name">${def.name}</span>
<span class="item-count">${inventory[id] || 0}</span>
</div>
`).join('');
return `<div class="inventory-grid">${entries}</div>`;
}
function renderRecipes(buildingId, inventory) {
const recipes = RECIPES[buildingId] || [];
if (!recipes.length) {
return `<div class="empty-note">Stores do not craft. Send supplies here, then move them to a workshop.</div>`;
}
return recipes.map(recipe => {
const inputs = Object.entries(recipe.inputs).map(([item, needed]) => {
const have = inventory[item] || 0;
return `<span class="requirement ${have >= needed ? 'met' : 'missing'}">
${have}/${needed} ${ITEM_DEFS[item].name}
</span>`;
}).join('');
const outputs = Object.entries(recipe.output).map(([item, amount]) =>
`<span class="requirement met">${amount} × ${ITEM_DEFS[item].name}</span>`
).join('');
const ready = canCraft(recipe, inventory);
return `
<div class="recipe">
<div class="recipe-top">
<h4>${recipe.name}</h4>
<span class="connected-pill">${ready ? 'Ready' : 'Missing materials'}</span>
</div>
<div class="recipe-blurb">${recipe.blurb}</div>
<div class="recipe-line">
${inputs}
<span class="recipe-arrow">→</span>
${outputs}
</div>
<button class="craft-button" data-craft="${recipe.id}" ${ready ? '' : 'disabled'}>
${ready ? 'Craft recipe' : 'Materials required'}
</button>
</div>
`;
}).join('');
}
function renderLogistics() {
const source = BUILDINGS[logisticsSource];
const destination = BUILDINGS[logisticsDest];
const route = findRoute(logisticsSource, logisticsDest);
const sourceInventory = state.inventories[logisticsSource];
const destinationInventory = state.inventories[logisticsDest];
const sourceOptions = Object.entries(BUILDINGS).map(([id, building]) =>
`<option value="${id}" ${id === logisticsSource ? 'selected' : ''}>${building.short}</option>`
).join('');
const destinationOptions = Object.entries(BUILDINGS)
.filter(([id]) => id !== logisticsSource)
.map(([id, building]) =>
`<option value="${id}" ${id === logisticsDest ? 'selected' : ''}>${building.short}</option>`
).join('');
const routeText = route
? route.edges.length === 1
? 'Direct road connection.'
: `Connected by ${route.edges.length} road segments through ${route.edges.map(edge => BUILDINGS[edge[0]].short).join(' → ')}.`
: 'No road connection.';
const transferRows = Object.entries(ITEM_DEFS).map(([item, def]) => {
const count = sourceInventory[item] || 0;
const atDestination = destinationInventory[item] || 0;
return `
<div class="transfer-row">
${itemIcon(item)}
<strong>${def.name}</strong>
<span class="destination-count">${count} → ${atDestination}</span>
<button class="send-button" data-send="${item}" ${count ? '' : 'disabled'}>Move</button>
</div>
`;
}).join('');
return `
<div class="route-box">
<div class="route-grid">
<label>
<span class="field-label">From</span>
<select data-logistics="source">${sourceOptions}</select>
</label>
<button class="swap-button" data-action="swap" title="Swap source and destination">⇄</button>
<label>
<span class="field-label">To</span>
<select data-logistics="destination">${destinationOptions}</select>
</label>
</div>
<div class="route-note">${routeText}</div>
</div>
<div class="amount-row">
<span class="field-label">Amount</span>
${[1, 5, 'all'].map(amount => `
<button class="amount-button ${transferAmount === amount ? 'active' : ''}" data-amount="${amount}">
${amount === 'all' ? 'All' : amount}
</button>
`).join('')}
</div>
<div class="transfer-list">${transferRows}</div>
`;
}
function renderPanel() {
const building = BUILDINGS[selectedId];
const inventory = state.inventories[selectedId];
const connections = graphNeighbors(selectedId);
panelContent.innerHTML = `
<div class="panel-heading">
<div class="panel-title">
<div class="building-icon">${building.icon}</div>
<div>
<h2>${building.name}</h2>
<p>${building.type === 'store' ? 'Storage building' : 'Production workshop'}</p>
</div>
</div>
<span class="connected-pill">● Online</span>
</div>
<p class="description">${building.description}</p>
<div class="section-title">
<h3>Local Inventory</h3>
<small>${inventoryTotal(selectedId)} total units</small>
</div>
${renderInventory(inventory)}
<div class="section">
<div class="section-title">
<h3>${building.type === 'store' ? 'Store Role' : 'Explicit Recipes'}</h3>
<small>${building.type === 'store' ? 'Local materials' : 'Uses local stock'}</small>
</div>
${renderRecipes(selectedId, inventory)}
</div>
<div class="section">
<div class="section-title">
<h3>Logistics</h3>
<small>Connected road route</small>
</div>
${renderLogistics()}
</div>
<div class="section">
<div class="section-title">
<h3>Road Connections</h3>
<small>${connections.length} nearby</small>
</div>
<div class="connections">
${connections.map(id => `<span class="connection">↔ ${BUILDINGS[id].short}</span>`).join('')}
</div>
</div>
`;
}
function updateInventoryIndicators() {
for (const [id, visual] of Object.entries(buildingVisuals)) {
const inventory = state.inventories[id];
const item = Object.entries(inventory)
.filter(([, count]) => count > 0)
.sort((a, b) => b[1] - a[1])[0]?.[0];
if (item) {
visual.indicator.material.color.set(ITEM_DEFS[item].color);
visual.indicator.material.emissive.set(ITEM_DEFS[item].color);
visual.indicator.material.emissiveIntensity = 0.18;
visual.indicator.visible = true;
} else {
visual.indicator.visible = false;
}
}
}
function renderAll() {
renderHeader();
renderQuests();
renderBuildBar();
renderPanel();
updateInventoryIndicators();
}
function selectBuilding(id) {
selectedId = id;
logisticsSource = id;
if (logisticsDest === id) logisticsDest = id === 'store' ? 'sawmill' : 'store';
renderAll();
playTone(350, .045);
}
function doCraft(recipeId) {
const recipe = getRecipe(selectedId, recipeId);
if (!recipe) return;
const inventory = state.inventories[selectedId];
if (!canCraft(recipe, inventory)) {
showToast('This workshop is missing recipe ingredients.', 'warn');
return;
}
for (const [item, count] of Object.entries(recipe.inputs)) {
inventory[item] -= count;
}
for (const [item, count] of Object.entries(recipe.output)) {
inventory[item] = (inventory[item] || 0) + count;
state.stats.craftedBy[item] = (state.stats.craftedBy[item] || 0) + count;
state.stats.craftedTotal += count;
}
const outputEntry = Object.entries(recipe.output)[0];
spawnCraftEffect(BUILDINGS[selectedId].grid, outputEntry[0]);
updateMilestones();
saveState();
renderAll();
playTone(660, .12, 'triangle');
setTimeout(() => playTone(880, .09, 'triangle'), 75);
showToast(`${recipe.name} crafted at the ${BUILDINGS[selectedId].short}.`);
}
function transferItem(item) {
if (logisticsSource === logisticsDest) return;
const route = findRoute(logisticsSource, logisticsDest);
if (!route) {
showToast('Those buildings are not connected by a road.', 'warn');
return;
}
const sourceInventory = state.inventories[logisticsSource];
const destinationInventory = state.inventories[logisticsDest];
const available = sourceInventory[item] || 0;
const amount = transferAmount === 'all' ? available : Math.min(transferAmount, available);
if (amount <= 0) {
showToast('There is no stock to move.', 'warn');
return;
}
sourceInventory[item] -= amount;
destinationInventory[item] = (destinationInventory[item] || 0) + amount;
state.stats.shipments += amount;
updateMilestones();
saveState();
renderAll();
animateCourier(route, item);
playTone(410, .08, 'triangle');
showToast(`${amount} × ${ITEM_DEFS[item].name} moved to ${BUILDINGS[logisticsDest].short}.`);
}
panelContent.addEventListener('click', event => {
const craftButton = event.target.closest('[data-craft]');
if (craftButton) {
doCraft(craftButton.dataset.craft);
return;
}
const sendButton = event.target.closest('[data-send]');
if (sendButton) {
transferItem(sendButton.dataset.send);
return;
}
const amountButton = event.target.closest('[data-amount]');
if (amountButton) {
const raw = amountButton.dataset.amount;
transferAmount = raw === 'all' ? 'all' : Number(raw);
renderPanel();
return;
}
if (event.target.closest('[data-action="swap"]')) {
const oldSource = logisticsSource;
logisticsSource = logisticsDest;
logisticsDest = oldSource;
renderPanel();
}
});
panelContent.addEventListener('change', event => {
const type = event.target.dataset.logistics;
if (!type) return;
if (type === 'source') {
logisticsSource = event.target.value;
if (logisticsDest === logisticsSource) {
logisticsDest = selectedId !== logisticsSource ? selectedId : 'store';
}
} else {
logisticsDest = event.target.value;
}
renderPanel();
});
buildBar.addEventListener('click', event => {
const button = event.target.closest('[data-building]');
if (button) selectBuilding(button.dataset.building);
});
document.getElementById('helpButton').addEventListener('click', () => {
document.getElementById('helpModal').classList.remove('hidden');
});
document.getElementById('closeHelp').addEventListener('click', () => {
document.getElementById('helpModal').classList.add('hidden');
playTone();
});
document.getElementById('resetButton').addEventListener('click', () => {
if (!confirm('Reset the entire settlement and all inventory?')) return;
try { localStorage.removeItem(SAVE_KEY); } catch (error) { if (error.name !== "SecurityError") throw error; }
location.reload();
});
document.getElementById('soundButton').addEventListener('click', event => {
soundEnabled = !soundEnabled;
event.currentTarget.textContent = soundEnabled ? '♫' : '×';
event.currentTarget.style.opacity = soundEnabled ? '1' : '.55';
if (soundEnabled) playTone();
});
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d8d7);
scene.fog = new THREE.Fog(0xb9d8d7, 35, 78);
const camera = new THREE.PerspectiveCamera(43, innerWidth / innerHeight, 0.1, 150);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
document.getElementById('scene').appendChild(renderer.domElement);
const world = new THREE.Group();
scene.add(world);
const hemi = new THREE.HemisphereLight(0xeaf8ff, 0x65704e, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.2);
sun.position.set(-12, 22, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -25;
sun.shadow.camera.right = 25;
sun.shadow.camera.top = 25;
sun.shadow.camera.bottom = -25;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 60;
sun.shadow.bias = -0.0006;
scene.add(sun);
const materialCache = new Map();
function getMaterial(color, roughness = 0.85, metalness = 0) {
const key = `${color}-${roughness}-${metalness}`;
if (!materialCache.has(key)) {
materialCache.set(key, new THREE.MeshStandardMaterial({
color,
roughness,
metalness,
flatShading: true
}));
}
return materialCache.get(key);
}
function addBox(parent, size, position, color, options = {}) {
const geometry = new THREE.BoxGeometry(size[0], size[1], size[2]);
const material = options.material || getMaterial(color, options.roughness ?? 0.85, options.metalness ?? 0);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(position[0], position[1], position[2]);
if (options.rotation) mesh.rotation.set(...options.rotation);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function gridToWorld(grid) {
return new THREE.Vector3(grid[0] * 1.12, 0, grid[1] * 1.12);
}
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
}
function makeLabel(text, accent = '#426b4b') {
const canvas = document.createElement('canvas');
canvas.width = 512;
canvas.height = 96;
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(context, 6, 10, 500, 72, 18);
context.fillStyle = 'rgba(250,247,235,.94)';
context.fill();
context.strokeStyle = 'rgba(49,67,53,.22)';
context.lineWidth = 3;
context.stroke();
context.fillStyle = accent;
context.font = '700 30px system-ui, sans-serif';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText(text, 256, 47);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(3.6, 0.68, 1);
return sprite;
}
function edgeGridPath(a, b) {
const start = BUILDINGS[a].grid;
const end = BUILDINGS[b].grid;
const points = [[...start]];
if (start[0] !== end[0] && start[1] !== end[1]) {
points.push([end[0], start[1]]);
}
const last = points[points.length - 1];
if (last[0] !== end[0]) {
const step = Math.sign(end[0] - last[0]);
for (let x = last[0] + step; x !== end[0] + step; x += step) points.push([x, last[1]]);
}
if (last[1] !== end[1]) {
const step = Math.sign(end[1] - last[1]);
for (let z = last[1] + step; z !== end[1] + step; z += step) points.push([end[0], z]);
}
return points;
}
const edgePaths = {};
const roadCells = new Set();
for (const [a, b] of EDGE_DEFS) {
const gridPath = edgeGridPath(a, b);
edgePaths[`${a}|${b}`] = gridPath;
edgePaths[`${b}|${a}`] = [...gridPath].reverse();
for (const [x, z] of gridPath) roadCells.add(`${x},${z}`);
}
// Water and raised island base.
const water = new THREE.Mesh(
new THREE.BoxGeometry(100, 0.35, 100),
new THREE.MeshStandardMaterial({ color: 0x74b8bc, roughness: 0.48, metalness: 0.05 })
);
water.position.y = -1.45;
water.receiveShadow = true;
world.add(water);
addBox(world, [25.5, 1.25, 25.5], [0, -0.72, 0], 0x69533d, { castShadow: false });
addBox(world, [25.15, 0.35, 25.15], [0, -0.03, 0], 0x728c54, { castShadow: false });
// Individual voxel ground tiles.
const tileGeometry = new THREE.BoxGeometry(1.08, 0.22, 1.08);
const tileMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1 });
const tileCount = 23 * 23;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
tiles.receiveShadow = true;
tiles.castShadow = false;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let tileIndex = 0;
function randomGenerator(seed) {
let value = seed >>> 0;
return () => {
value = (value * 1664525 + 1013904223) >>> 0;
return value / 4294967296;
};
}
const random = randomGenerator(84271);
for (let x = -11; x <= 11; x++) {
for (let z = -11; z <= 11; z++) {
dummy.position.set(x * 1.12, -0.08, z * 1.12);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const isRoad = roadCells.has(`${x},${z}`);
if (isRoad) {
color.set(random() > .5 ? 0xc5aa78 : 0xb99d6d);
} else {
const shades = [0x789653, 0x7f9b58, 0x829e5b, 0x71904f];
color.set(shades[Math.floor(random() * shades.length)]);
}
tiles.setColorAt(tileIndex, color);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
world.add(tiles);
const buildingVisuals = {};
const buildingMeshes = [];
function registerBuilding(group, id) {
group.traverse(object => {
if (object.isMesh) {
object.userData.buildingId = id;
buildingMeshes.push(object);
}
});
}
function addInventoryIndicator(group, offsetX = 2.05, offsetZ = 1.55) {
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: 0x000000,
emissiveIntensity: .2,
roughness: .55
});
const marker = addBox(group, [.42, .42, .42], [offsetX, .7, offsetZ], 0xffffff, { material });
marker.userData.isIndicator = true;
return marker;
}
function buildStore(id, roofColor, accentColor) {
const group = new THREE.Group();
group.position.copy(gridToWorld(BUILDINGS[id].grid));
addBox(group, [3.6, .35, 3.1], [0, .18, 0], 0x777d72);
addBox(group, [3.1, 1.9, 2.65], [0, 1.25, 0], 0xc8a66d);
addBox(group, [3.25, .18, 2.8], [0, .52, 0], 0x73543c);
for (let layer = 0; layer < 4; layer++) {
addBox(
group,
[3.55 - layer * .48, .25, 2.95 - layer * .48],
[0, 2.34 + layer * .22, 0],
roofColor
);
}
addBox(group, [.68, 1.22, .12], [0, 1.05, 1.38], 0x4d3b2e);
addBox(group, [.11, .11, .1], [.2, 1.05, 1.47], 0xd7b65d);
addBox(group, [.48, .48, .12], [-1.02, 1.5, 1.38], 0x83c2ca, { roughness: .25, metalness: .1 });
addBox(group, [.48, .48, .12], [1.02, 1.5, 1.38], 0x83c2ca, { roughness: .25, metalness: .1 });
addBox(group, [.3, .22, .12], [-1.02, 1.5, 1.46], accentColor);
addBox(group, [.3, .22, .12], [1.02, 1.5, 1.46], accentColor);
for (let i = 0; i < 5; i++) {
addBox(group, [.72, .12, 1.0], [0, 2.03, 1.56 + i * .11], i % 2 ? accentColor : 0xf0ddb6);
}
addBox(group, [.58, .58, .58], [-2.05, .52, .95], 0xa77b48);
addBox(group, [.48, .48, .48], [-2.0, 1.02, .9], 0x84623e);
addBox(group, [.5, .5, .5], [1.95, .45, .85], 0x9d7548);
const indicator = addInventoryIndicator(group, 1.95, 1.65);
const label = makeLabel(BUILDINGS[id].name, '#426b4b');
label.position.set(0, 4.15, 0);
group.add(label);
buildingVisuals[id] = { group, indicator };
registerBuilding(group, id);
world.add(group);
}
function buildSawmill() {
const group = new THREE.Group();
group.position.copy(gridToWorld(BUILDINGS.sawmill.grid));
addBox(group, [3.45, .3, 3.0], [0, .16, 0], 0x7b7669);
addBox(group, [3.1, .2, 2.75], [0, 2.25, 0], 0x755139);
for (let layer = 0; layer < 3; layer++) {
addBox(group, [3.3 - layer * .55, .24, 2.9 - layer * .42], [0, 2.43 + layer * .19, 0], 0x8e6040);
}
for (const x of [-1.25, 1.25]) {
for (const z of [-1.05, 1.05]) {
addBox(group, [.19, 1.9, .19], [x, 1.25, z], 0x6c4930);
}
}
addBox(group, [2.25, .32, .38], [0, 1.15, .15], 0xa77b48);
addBox(group, [.16, 1.18, .72], [.45, 1.45, .15], 0x5e6970, { metalness: .45, roughness: .42 });
addBox(group, [.16, .82, .16], [.45, 1.47, .55], 0x5e6970, { metalness: .45, roughness: .42 });
for (let i = 0; i < 4; i++) {
const log = addBox(group, [1.4, .28, .28], [-.65, .45 + Math.floor(i / 2) * .3, -.9 + (i % 2) * .34], 0x8b5e37);
log.rotation.y = Math.PI / 2;
}
addBox(group, [.65, .55, .65], [1.55, .48, .9], 0xb08750);
const indicator = addInventoryIndicator(group, 1.7, 1.25);
const label = makeLabel(BUILDINGS.sawmill.name, '#8c5e34');
label.position.set(0, 3.65, 0);
group.add(label);
buildingVisuals.sawmill = { group, indicator };
registerBuilding(group, 'sawmill');
world.add(group);
}
function buildWeaver() {
const group = new THREE.Group();
group.position.copy(gridToWorld(BUILDINGS.weaver.grid));
addBox(group, [3.25, .3, 2.9], [0, .16, 0], 0x817b68);
addBox(group, [2.75, 1.65, 2.35], [0, 1.15, -.25], 0xb98274);
addBox(group, [3.05, .18, 2.7], [0, 2.08, -.15], 0x74564d);
for (let layer = 0; layer < 3; layer++) {
addBox(group, [3.15 - layer * .52, .23, 2.7 - layer * .45], [0, 2.24 + layer * .2, -.1], 0x876b66);
}
addBox(group, [.62, 1.2, .1], [0, .98, .99], 0x584139);
addBox(group, [.45, .45, .12], [-.9, 1.4, 1.0], 0xf0c69d);
for (const x of [-1.0, 1.0]) {
addBox(group, [.12, 1.1, .12], [x, .85, 1.35], 0x6c4c38);
}
addBox(group, [2.2, .12, .12], [0, 1.37, 1.35], 0x6c4c38);
const clothColors = [0xcf6d7f, 0x6f9fa5, 0xd3ad61];
clothColors.forEach((clothColor, index) => {
addBox(group, [.48, .78, .06], [-.65 + index * .65, .93, 1.37], clothColor);
});
const indicator = addInventoryIndicator(group, 1.75, 1.18);
const label = makeLabel(BUILDINGS.weaver.name, '#9e5365');
label.position.set(0, 3.55, 0);
group.add(label);
buildingVisuals.weaver = { group, indicator };
registerBuilding(group, 'weaver');
world.add(group);
}
function buildMason() {
const group = new THREE.Group();
group.position.copy(gridToWorld(BUILDINGS.mason.grid));
addBox(group, [3.5, .3, 3.0], [0, .16, 0], 0x777d72);
addBox(group, [2.8, 1.55, 2.4], [-.15, 1.12, -.25], 0x777d76);
for (let layer = 0; layer < 3; layer++) {
addBox(group, [3.1 - layer * .48, .24, 2.75 - layer * .42], [0, 2.05 + layer * .2, -.15], 0x5d6760);
}
addBox(group, [.75, 1.15, .12], [.35, .95, 1.0], 0x4a4540);
addBox(group, [.47, .47, .12], [-.85, 1.35, 1.02], 0x9cc2c1);
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 2; col++) {
addBox(group, [.48, .23, .25], [-1.4 + col * .52 + (row % 2) * .13, .38 + row * .24, 1.1], row % 2 ? 0xa95b44 : 0xb76b50);
}
}
const indicator = addInventoryIndicator(group, 1.75, 1.15);
const label = makeLabel(BUILDINGS.mason.name, '#626c64');
label.position.set(0, 3.4, 0);
group.add(label);
buildingVisuals.mason = { group, indicator };
registerBuilding(group, 'mason');
world.add(group);
}
function buildSmithy() {
const group = new THREE.Group();
group.position.copy(gridToWorld(BUILDINGS.smithy.grid));
addBox(group, [3.45, .3, 3.05], [0, .16, 0], 0x68695f);
addBox(group, [2.75, 1.5, 2.25], [0, 1.08, -.35], 0x5e4a38);
addBox(group, [3.2, .18, 2.85], [0, 2.06, -.15], 0x4d3d31);
for (let layer = 0; layer < 3; layer++) {
addBox(group, [3.25 - layer * .55, .23, 2.9 - layer * .48], [0, 2.24 + layer * .2, -.12], 0x5a493b);
}
addBox(group, [.72, 1.15, .12], [0, .96, .85], 0x3f342c);
addBox(group, [.7, .9, .75], [-.9, .62, .88], 0x50575a);
addBox(group, [.58, .46, .65], [-.9, .77, 1.23], 0xd57539, {
material: new THREE.MeshStandardMaterial({
color: 0xe57c35,
emissive: 0xb33e12,
emissiveIntensity: 1.3,
roughness: .7
})
});
addBox(group, [.22, 1.6, .22], [1.0, 2.05, -.8], 0x6b6960);
addBox(group, [.42, .42, .42], [1.55, .42, 1.05], 0x566978, { metalness: .35, roughness: .45 });
addBox(group, [.12, .75, .12], [1.55, .8, 1.05], 0x765439, { rotation: [0, 0, .45] });
const indicator = addInventoryIndicator(group, 1.8, 1.2);
const label = makeLabel(BUILDINGS.smithy.name, '#8d5636');
label.position.set(0, 3.55, 0);
group.add(label);
buildingVisuals.smithy = { group, indicator };
registerBuilding(group, 'smithy');
world.add(group);
}
buildStore('store', 0xa65f43, 0x507d62);
buildStore('depot', 0x65745e, 0xc1974f);
buildSawmill();
buildWeaver();
buildMason();
buildSmithy();
// Trees, rocks, and small village details.
function isNearBuilding(x, z) {
return Object.values(BUILDINGS).some(building => {
const [bx, bz] = building.grid;
return Math.hypot(x - bx, z - bz) < 2.8;
});
}
function isRoad(x, z) {
return roadCells.has(`${Math.round(x)},${Math.round(z)}`);
}
for (let i = 0; i < 70; i++) {
const x = Math.round(random() * 20 - 10);
const z = Math.round(random() * 20 - 10);
if (isNearBuilding(x, z) || isRoad(x, z)) continue;
const tree = new THREE.Group();
tree.position.set(x * 1.12, 0, z * 1.12);
tree.rotation.y = random() * Math.PI;
const trunkHeight = .65 + random() * .55;
addBox(tree, [.22, trunkHeight, .22], [0, trunkHeight / 2, 0], 0x72513a);
const foliage = random() > .5 ? 0x486f42 : 0x587c46;
addBox(tree, [.82, .65, .82], [0, trunkHeight + .28, 0], foliage);
addBox(tree, [.62, .58, .62], [0, trunkHeight + .7, 0], foliage);
addBox(tree, [.4, .35, .4], [0, trunkHeight + 1.08, 0], 0x638b50);
world.add(tree);
if (i > 44) break;
}
for (let i = 0; i < 18; i++) {
const x = random() * 19 - 9.5;
const z = random() * 19 - 9.5;
if (isNearBuilding(Math.round(x), Math.round(z)) || isRoad(Math.round(x), Math.round(z))) continue;
const rock = addBox(world, [.35 + random() * .4, .3 + random() * .3, .35 + random() * .4], [x * 1.12, .15, z * 1.12], 0x8b9187);
rock.rotation.set(random() * .3, random() * Math.PI, random() * .25);
}
// Road-side posts.
for (const [x, z] of [[-2, 0], [2, 0], [-2, 3], [2, 3], [-2, -3], [2, -3]]) {
addBox(world, [.12, 1.1, .12], [x * 1.12, .55, z * 1.12], 0x5d4634);
addBox(world, [.25, .25, .25], [x * 1.12, 1.15, z * 1.12], 0xe0b95e, {
material: new THREE.MeshStandardMaterial({
color: 0xf1cd70,
emissive: 0xc48a2b,
emissiveIntensity: .65,
roughness: .45
})
});
}
// Floating voxel clouds.
const clouds = [];
for (let i = 0; i < 7; i++) {
const cloud = new THREE.Group();
const x = random() * 36 - 18;
const z = random() * 30 - 15;
const y = 8 + random() * 5;
cloud.position.set(x, y, z);
const pieces = [
[-.8, 0, 0, 1.1], [0, .2, 0, 1.5], [.9, 0, 0, 1.0],
[-.2, -.15, .1, .8], [.5, -.1, .15, .9]
];
pieces.forEach(([px, py, pz, size]) => {
addBox(cloud, [size, .55, .75], [px, py, pz], 0xf1f1e6, { castShadow: false });
});
clouds.push(cloud);
world.add(cloud);
}
// Selection marker.
const selectionMarker = new THREE.Group();
const markerMaterial = new THREE.MeshBasicMaterial({
color: 0xf3c45d,
transparent: true,
opacity: .9,
depthWrite: false
});
addBox(selectionMarker, [1.65, .08, .12], [0, .12, -2], 0xf3c45d, { material: markerMaterial, castShadow: false });
addBox(selectionMarker, [1.65, .08, .12], [0, .12, 2], 0xf3c45d, { material: markerMaterial, castShadow: false });
addBox(selectionMarker, [.12, .08, 3.85], [-2, .12, 0], 0xf3c45d, { material: markerMaterial, castShadow: false });
addBox(selectionMarker, [.12, .08, 3.85], [2, .12, 0], 0xf3c45d, { material: markerMaterial, castShadow: false });
world.add(selectionMarker);
const craftEffects = [];
const couriers = [];
function spawnCraftEffect(grid, item) {
const position = gridToWorld(grid);
const color = ITEM_DEFS[item].color;
const geometry = new THREE.BoxGeometry(.42, .42, .42);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: .25,
roughness: .5
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(position.x, 2.8, position.z);
mesh.castShadow = true;
world.add(mesh);
craftEffects.push({ mesh, age: 0, duration: 1.35 });
for (let i = 0; i < 9; i++) {
const particleGeometry = new THREE.BoxGeometry(.11, .11, .11);
const particleMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 1
});
const particle = new THREE.Mesh(particleGeometry, particleMaterial);
particle.position.set(position.x, 2.4, position.z);
world.add(particle);
craftEffects.push({
mesh: particle,
age: 0,
duration: .85 + Math.random() * .4,
velocity: new THREE.Vector3(
(Math.random() - .5) * 2,
1.6 + Math.random(),
(Math.random() - .5) * 2
)
});
}
const text = makeLabel(`+${item === 'plank' ? 2 : 1} ${ITEM_DEFS[item].name}`, '#426b4b');
text.position.set(position.x, 4.6, position.z);
text.scale.set(2.7, .51, 1);
world.add(text);
craftEffects.push({ mesh: text, age: 0, duration: 1.45, floatingText: true });
}
function routeWorldPoints(route) {
const points = [];
for (const [a, b] of route.edges) {
const path = edgePaths[`${a}|${b}`];
path.forEach((grid, index) => {
if (index === 0 && points.length) return;
points.push(gridToWorld(grid));
});
}
return points;
}
function animateCourier(route, item) {
const points = routeWorldPoints(route);
if (points.length < 2) return;
const group = new THREE.Group();
const shirtColors = [0x557f9a, 0xb35f49, 0x6f8d55, 0x8b6da6];
const shirt = shirtColors[Math.floor(Math.random() * shirtColors.length)];
addBox(group, [.32, .42, .25], [0, .52, 0], shirt);
addBox(group, [.28, .27, .27], [0, .9, 0], 0xe5b88b);
addBox(group, [.38, .12, .32], [0, 1.04, 0], 0x594434);
addBox(group, [.14, .33, .14], [-.1, .16, 0], 0x3f4d47);
addBox(group, [.14, .33, .14], [.1, .16, 0], 0x3f4d47);
const crate = addBox(group, [.48, .4, .42], [.39, .55, 0], ITEM_DEFS[item].color);
crate.rotation.z = -.08;
group.position.copy(points[0]);
group.position.y = .15;
world.add(group);
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points.map(point => new THREE.Vector3(point.x, .16, point.z)));
const lineMaterial = new THREE.LineBasicMaterial({
color: 0xf3c45d,
transparent: true,
opacity: .8,
depthWrite: false
});
const line = new THREE.Line(lineGeometry, lineMaterial);
world.add(line);
const lengths = [];
let totalLength = 0;
for (let i = 1; i < points.length; i++) {
const length = points[i].distanceTo(points[i - 1]);
lengths.push(length);
totalLength += length;
}
couriers.push({
group,
line,
points,
lengths,
totalLength,
speed: Math.max(3.3, totalLength / 2.8),
age: 0
});
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom, keyboard, and picking
// -------------------------------------------------------------------------
const cameraState = {
yaw: .72,
pitch: .72,
distance: 34,
target: new THREE.Vector3(0, .5, .4),
goal: null
};
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerStart = new THREE.Vector2();
const keys = new Set();
let dragging = false;
let dragMode = 'orbit';
let dragDistance = 0;
function updateCamera() {
if (cameraState.goal) {
cameraState.target.lerp(cameraState.goal, .08);
if (cameraState.target.distanceTo(cameraState.goal) < .03) cameraState.goal = null;
}
const horizontal = Math.cos(cameraState.pitch) * cameraState.distance;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y + Math.sin(cameraState.pitch) * cameraState.distance,
cameraState.target.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.target);
}
function panCamera(dx, dy) {
const scale = cameraState.distance * .0017;
const right = new THREE.Vector3(Math.cos(cameraState.yaw), 0, -Math.sin(cameraState.yaw));
const forward = new THREE.Vector3(-Math.sin(cameraState.yaw), 0, -Math.cos(cameraState.yaw));
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -11, 11);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -11, 11);
cameraState.goal = null;
}
function pickBuilding(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(buildingMeshes, false);
return intersections.length ? intersections[0].object.userData.buildingId : null;
}
renderer.domElement.addEventListener('contextmenu', event => event.preventDefault());
renderer.domElement.addEventListener('pointerdown', event => {
dragging = true;
dragMode = event.button === 2 || event.shiftKey ? 'pan' : 'orbit';
dragDistance = 0;
pointerStart.set(event.clientX, event.clientY);
renderer.domElement.setPointerCapture(event.pointerId);
hoverTip.style.display = 'none';
});
renderer.domElement.addEventListener('pointermove', event => {
if (dragging) {
const dx = event.clientX - pointerStart.x;
const dy = event.clientY - pointerStart.y;
dragDistance = Math.max(dragDistance, Math.hypot(dx, dy));
if (dragMode === 'orbit') {
cameraState.yaw -= dx * .006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * .004, .32, 1.25);
cameraState.goal = null;
} else {
panCamera(dx, dy);
}
pointerStart.set(event.clientX, event.clientY);
return;
}
const id = pickBuilding(event);
if (id) {
const inventory = state.inventories[id];
const topItems = Object.entries(inventory)
.filter(([, count]) => count > 0)
.sort((a, b) => b[1] - a[1])
.slice(0, 2)
.map(([item, count]) => `${count} ${ITEM_DEFS[item].name}`)
.join(' · ');
hoverTip.innerHTML = `<strong>${BUILDINGS[id].name}</strong><br>${topItems || 'Inventory empty'}`;
hoverTip.style.display = 'block';
hoverTip.style.left = `${Math.min(event.clientX + 14, innerWidth - 190)}px`;
hoverTip.style.top = `${Math.min(event.clientY + 14, innerHeight - 70)}px`;
renderer.domElement.style.cursor = 'pointer';
} else {
hoverTip.style.display = 'none';
renderer.domElement.style.cursor = 'grab';
}
});
renderer.domElement.addEventListener('pointerup', event => {
if (dragging && dragMode === 'orbit' && dragDistance < 7) {
const id = pickBuilding(event);
if (id) selectBuilding(id);
}
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener('pointercancel', () => { dragging = false; });
renderer.domElement.addEventListener('wheel', event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * .025,
18,
56
);
cameraState.goal = null;
}, { passive: false });
renderer.domElement.addEventListener('dblclick', event => {
const id = pickBuilding(event);
if (id) {
const point = gridToWorld(BUILDINGS[id].grid);
cameraState.goal = new THREE.Vector3(point.x, .5, point.z);
}
});
window.addEventListener('keydown', event => {
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(document.activeElement.tagName)) return;
keys.add(event.key.toLowerCase());
if (event.key === 'Escape') document.getElementById('helpModal').classList.add('hidden');
if (event.key.toLowerCase() === 'q') cameraState.yaw += .25;
if (event.key.toLowerCase() === 'e') cameraState.yaw -= .25;
});
window.addEventListener('keyup', event => keys.delete(event.key.toLowerCase()));
document.getElementById('rotateLeft').addEventListener('click', () => { cameraState.yaw -= .28; });
document.getElementById('rotateRight').addEventListener('click', () => { cameraState.yaw += .28; });
document.getElementById('zoomIn').addEventListener('click', () => { cameraState.distance = Math.max(18, cameraState.distance - 2); });
document.getElementById('zoomOut').addEventListener('click', () => { cameraState.distance = Math.min(56, cameraState.distance + 2); });
function updateKeyboardCamera(delta) {
const forward = new THREE.Vector3(-Math.sin(cameraState.yaw), 0, -Math.cos(cameraState.yaw));
const right = new THREE.Vector3(Math.cos(cameraState.yaw), 0, -Math.sin(cameraState.yaw));
const speed = cameraState.distance * .55 * delta;
if (keys.has('w')) cameraState.target.addScaledVector(forward, speed);
if (keys.has('s')) cameraState.target.addScaledVector(forward, -speed);
if (keys.has('d')) cameraState.target.addScaledVector(right, speed);
if (keys.has('a')) cameraState.target.addScaledVector(right, -speed);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -11, 11);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -11, 11);
}
// -------------------------------------------------------------------------
// Animation and resize
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), .05);
const elapsed = clock.elapsedTime;
updateKeyboardCamera(delta);
updateCamera();
const selectedPosition = gridToWorld(BUILDINGS[selectedId].grid);
selectionMarker.position.set(selectedPosition.x, .08, selectedPosition.z);
selectionMarker.scale.setScalar(1 + Math.sin(elapsed * 3.5) * .025);
markerMaterial.opacity = .68 + Math.sin(elapsed * 3.5) * .18;
for (const visual of Object.values(buildingVisuals)) {
if (visual.indicator.visible) {
visual.indicator.rotation.y += delta * .8;
visual.indicator.position.y = .73 + Math.sin(elapsed * 2.2 + visual.group.position.x) * .08;
}
}
clouds.forEach((cloud, index) => {
cloud.position.x += delta * (.12 + index * .01);
if (cloud.position.x > 24) cloud.position.x = -24;
});
for (let i = craftEffects.length - 1; i >= 0; i--) {
const effect = craftEffects[i];
effect.age += delta;
const progress = effect.age / effect.duration;
if (effect.velocity) {
effect.mesh.position.addScaledVector(effect.velocity, delta);
effect.velocity.y -= delta * 2.4;
effect.mesh.rotation.x += delta * 4;
effect.mesh.rotation.z += delta * 3;
effect.mesh.material.opacity = Math.max(0, 1 - progress);
} else if (effect.floatingText) {
effect.mesh.position.y += delta * .72;
effect.mesh.material.opacity = Math.max(0, 1 - progress);
} else {
effect.mesh.rotation.y += delta * 2.4;
effect.mesh.position.y += delta * .55;
effect.mesh.scale.setScalar(Math.max(0, 1 - progress * .55));
}
if (effect.age >= effect.duration) {
world.remove(effect.mesh);
effect.mesh.geometry?.dispose();
if (effect.mesh.material?.map) effect.mesh.material.map.dispose();
effect.mesh.material?.dispose();
craftEffects.splice(i, 1);
}
}
for (let i = couriers.length - 1; i >= 0; i--) {
const courier = couriers[i];
courier.age += delta;
let distance = courier.age * courier.speed;
let segment = 0;
while (segment < courier.lengths.length - 1 && distance > courier.lengths[segment]) {
distance -= courier.lengths[segment];
segment++;
}
const t = courier.lengths[segment] ? distance / courier.lengths[segment] : 1;
const from = courier.points[segment];
const to = courier.points[segment + 1] || courier.points[segment];
courier.group.position.lerpVectors(from, to, t);
courier.group.position.y = .16 + Math.abs(Math.sin(courier.age * 11)) * .06;
courier.group.rotation.y = Math.atan2(to.x - from.x, to.z - from.z);
courier.line.material.opacity = Math.max(0, .8 - courier.age * .25);
if (courier.age * courier.speed >= courier.totalLength + .25) {
world.remove(courier.group);
world.remove(courier.line);
courier.line.geometry.dispose();
courier.line.material.dispose();
couriers.splice(i, 1);
}
}
renderer.render(scene, camera);
}
window.addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
updateMilestones(true);
renderAll();
updateCamera();
animate();
</script>
</body>
</html>
```