Prompt specification
Build or customize the Three.js 3D scene "Broken Trust in a Toy Payment 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: Broken Trust in a Toy Payment Network
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/broken-trust-in-a-toy-payment-network-x3164
Scene Description Prompt:
A low-poly fictional market reroutes trades when one shop stops accepting a token type; show stalled exchanges and inventory changes. Three.js from cdnjs, one HTML file.
Working Three.js Starter (broken-trust-in-a-toy-payment-network-x3164):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Token Turn — A Reactive Low-Poly Market</title>
<style>
:root {
--ink: #122a2e;
--panel: rgba(17, 39, 43, 0.94);
--panel-soft: rgba(27, 53, 57, 0.9);
--line: rgba(255, 255, 255, 0.13);
--paper: #f2eddf;
--muted: #aabbb8;
--copper: #e99155;
--amber: #f5c84c;
--jade: #58c69e;
--danger: #ff786d;
--cyan: #71c9d1;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cddbd2;
color: var(--paper);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
cursor: pointer;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 5;
}
.interactive {
pointer-events: auto;
}
.title-block {
position: absolute;
top: 22px;
left: 24px;
max-width: 490px;
color: var(--ink);
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.35);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #2aa879;
box-shadow: 0 0 0 4px rgba(42, 168, 121, 0.16);
animation: pulse 1.8s infinite;
}
@keyframes pulse {
50% {
box-shadow: 0 0 0 8px rgba(42, 168, 121, 0);
}
}
h1 {
margin: 0;
font-size: clamp(31px, 4vw, 54px);
line-height: 0.92;
letter-spacing: -0.055em;
font-weight: 900;
}
.subtitle {
max-width: 410px;
margin: 12px 0 0;
color: rgba(18, 42, 46, 0.75);
font-size: 13px;
line-height: 1.5;
font-weight: 600;
}
.top-pill {
position: absolute;
top: 24px;
right: 24px;
display: flex;
gap: 8px;
align-items: center;
padding: 9px 13px;
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 999px;
background: rgba(244, 240, 224, 0.76);
color: var(--ink);
box-shadow: 0 7px 30px rgba(29, 51, 50, 0.12);
backdrop-filter: blur(10px);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.top-pill .mini-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--amber);
}
.control-panel {
position: absolute;
top: 82px;
right: 24px;
width: 306px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 55px rgba(18, 37, 39, 0.2);
backdrop-filter: blur(14px);
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.panel-heading strong {
font-size: 12px;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.panel-heading span {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.policy-button {
width: 100%;
padding: 13px 14px;
border: 0;
border-radius: 12px;
background: linear-gradient(135deg, #f6c84d, #e9a844);
color: #30280e;
box-shadow: 0 8px 22px rgba(245, 200, 76, 0.16);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.025em;
text-align: left;
transition: transform 0.15s, filter 0.15s;
}
.policy-button:hover {
transform: translateY(-1px);
filter: brightness(1.04);
}
.policy-button.reverted {
background: linear-gradient(135deg, #63c9a0, #43aa88);
color: #102d29;
}
.policy-button small {
display: block;
margin-top: 4px;
opacity: 0.68;
font-size: 10px;
font-weight: 750;
letter-spacing: 0;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 9px;
}
.small-button {
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
color: var(--paper);
font-size: 10px;
font-weight: 800;
transition: background 0.15s;
}
.small-button:hover {
background: rgba(255, 255, 255, 0.11);
}
.speed-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.speed-row input {
flex: 1;
accent-color: var(--amber);
}
#speed-value {
width: 34px;
color: var(--paper);
text-align: right;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 13px;
}
.metric {
padding: 9px 7px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
text-align: center;
}
.metric strong {
display: block;
color: var(--paper);
font-size: 18px;
line-height: 1;
}
.metric span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.log-heading {
margin: 14px 0 7px;
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#event-log {
height: 137px;
overflow: hidden;
padding-right: 3px;
}
.log-entry {
display: grid;
grid-template-columns: 33px 1fr;
gap: 8px;
padding: 7px 0;
border-top: 1px solid rgba(255, 255, 255, 0.075);
font-size: 10px;
line-height: 1.35;
}
.log-entry:first-child {
border-top: 0;
}
.log-time {
color: #78928e;
font-variant-numeric: tabular-nums;
}
.log-entry.policy {
color: var(--amber);
}
.log-entry.reroute {
color: var(--cyan);
}
.log-entry.stall {
color: var(--danger);
}
.log-entry.trade {
color: #b7c9c3;
}
.inventory {
position: absolute;
right: 346px;
bottom: 20px;
left: 20px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 18px 45px rgba(18, 37, 39, 0.18);
backdrop-filter: blur(14px);
}
.inventory-heading {
display: flex;
justify-content: space-between;
align-items: center;
margin: 0 2px 10px;
}
.inventory-heading strong {
font-size: 10px;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.inventory-heading span {
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
#inventory-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 9px;
}
.shop-card {
min-width: 0;
padding: 11px;
border: 1px solid rgba(255, 255, 255, 0.085);
border-radius: 12px;
background: rgba(255, 255, 255, 0.035);
}
.shop-card-title {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 8px;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.035em;
white-space: nowrap;
}
.shop-swatch {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 3px;
}
.accepted {
display: flex;
gap: 4px;
margin-bottom: 9px;
}
.token-chip {
display: flex;
align-items: center;
gap: 4px;
padding: 3px 6px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
color: #b7c7c4;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.05em;
text-transform: uppercase;
opacity: 0.48;
}
.token-chip::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--chip);
}
.token-chip.accepted {
opacity: 1;
background: rgba(255, 255, 255, 0.045);
}
.products {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
}
.product-cell {
min-width: 0;
}
.product-label {
display: flex;
justify-content: space-between;
gap: 3px;
margin-bottom: 4px;
color: #a6b9b5;
font-size: 7px;
font-weight: 850;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.product-label b {
color: var(--paper);
font-size: 9px;
}
.stock-bar {
height: 4px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
.stock-fill {
height: 100%;
width: 0;
border-radius: inherit;
background: var(--shop-color);
transition: width 0.35s ease;
}
.shop-tokens {
display: flex;
flex-wrap: wrap;
gap: 5px 10px;
margin-top: 9px;
padding-top: 8px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
color: #a9bbb7;
font-size: 8px;
font-weight: 750;
}
.shop-tokens span {
display: flex;
align-items: center;
gap: 4px;
}
.shop-tokens i {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--chip);
}
.shop-tokens b {
color: var(--paper);
}
.flash {
animation: flash 0.65s ease;
}
@keyframes flash {
0%,
100% {
color: inherit;
}
35% {
color: #fff4ad;
text-shadow: 0 0 12px rgba(255, 229, 116, 0.65);
}
}
.camera-hint {
position: absolute;
bottom: 227px;
left: 24px;
padding: 8px 11px;
border-radius: 999px;
background: rgba(18, 42, 46, 0.76);
color: rgba(255, 255, 255, 0.83);
box-shadow: 0 8px 25px rgba(18, 42, 46, 0.14);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.legend {
display: flex;
gap: 12px;
margin-top: 9px;
}
.legend span {
display: flex;
align-items: center;
gap: 5px;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.legend i {
width: 8px;
height: 8px;
border-radius: 50%;
}
@media (max-width: 1050px) {
.control-panel {
width: 276px;
}
.inventory {
right: 20px;
}
.camera-hint {
bottom: 227px;
}
}
@media (max-width: 780px) {
.title-block {
top: 16px;
left: 16px;
max-width: 300px;
}
.subtitle,
.top-pill,
.camera-hint {
display: none;
}
.control-panel {
top: 100px;
right: 12px;
width: 242px;
padding: 12px;
}
#event-log {
height: 86px;
}
.inventory {
right: 12px;
bottom: 12px;
left: 12px;
padding: 10px;
}
#inventory-grid {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.shop-card {
min-width: 255px;
scroll-snap-align: start;
}
}
@media (max-width: 520px) {
h1 {
font-size: 34px;
}
.control-panel {
top: auto;
right: 10px;
bottom: 188px;
width: 218px;
}
.metrics,
.log-heading,
#event-log,
.speed-row {
display: none;
}
.inventory-heading span {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<div class="title-block">
<div class="eyebrow">
<span class="live-dot"></span>
Reactive trade simulation
</div>
<h1>TOKEN<br />TURN</h1>
<p class="subtitle">
One shop changes what it accepts. Watch routes split, exchanges stall,
and shop inventories rebalance in real time.
</p>
</div>
<div class="top-pill">
<span class="mini-dot"></span>
<span id="market-status">Market open</span>
</div>
<section class="control-panel interactive" aria-label="Market controls">
<div class="panel-heading">
<strong>Route disruption</strong>
<span id="policy-state">Amber accepted</span>
</div>
<button id="policy-button" class="policy-button">
Make Moss stop accepting Amber
<small>Existing trades will recalculate their destination.</small>
</button>
<div class="button-row">
<button id="batch-button" class="small-button">Inject test trades</button>
<button id="pause-button" class="small-button">Pause market</button>
<button id="reset-button" class="small-button">Reset simulation</button>
<button id="view-button" class="small-button">Reset camera</button>
</div>
<div class="speed-row">
<span>Speed</span>
<input id="speed" type="range" min="0.5" max="2.5" step="0.1" value="1" />
<span id="speed-value">1.0×</span>
</div>
<div class="metrics">
<div class="metric">
<strong id="trade-count">0</strong>
<span>Trades</span>
</div>
<div class="metric">
<strong id="reroute-count">0</strong>
<span>Rerouted</span>
</div>
<div class="metric">
<strong id="stall-count">0</strong>
<span>Stalled</span>
</div>
</div>
<div class="log-heading">Live dispatch log</div>
<div id="event-log" aria-live="polite"></div>
</section>
<div class="camera-hint">
Drag to orbit · Scroll to zoom
<div class="legend">
<span><i style="background:#e99155"></i>Copper</span>
<span><i style="background:#f5c84c"></i>Amber</span>
<span><i style="background:#58c69e"></i>Jade</span>
</div>
</div>
<section class="inventory interactive" aria-label="Shop inventories">
<div class="inventory-heading">
<strong>Live shop inventory</strong>
<span>Stock levels and accepted-token balances update after each exchange</span>
</div>
<div id="inventory-grid"></div>
</section>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const container = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xcbdad1);
scene.fog = new THREE.Fog(0xcbdad1, 20, 42);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(0xe9f4ed, 0x7f755f, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe7b5, 3.2);
sun.position.set(-9, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -16;
sun.shadow.camera.right = 16;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 42;
sun.shadow.bias = -0.0008;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x8dc9db, 0.7);
rim.position.set(11, 7, -10);
scene.add(rim);
const clock = new THREE.Clock();
// -------------------------------------------------------------------------
// Custom camera controls — no addons
// -------------------------------------------------------------------------
const defaultCamera = {
theta: 0.46,
phi: 1.02,
radius: 18.4
};
const orbit = {
theta: defaultCamera.theta,
phi: defaultCamera.phi,
radius: defaultCamera.radius,
target: new THREE.Vector3(0, 1.05, 0)
};
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.005, 0.56, 1.38);
});
function stopDragging() {
dragging = false;
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.012,
11,
28
);
},
{ passive: false }
);
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
// -------------------------------------------------------------------------
// Palette and helpers
// -------------------------------------------------------------------------
const TOKENS = {
copper: {
label: "Copper",
short: "COP",
color: 0xe99155,
css: "#e99155"
},
amber: {
label: "Amber",
short: "AMB",
color: 0xf5c84c,
css: "#f5c84c"
},
jade: {
label: "Jade",
short: "JAD",
color: 0x58c69e,
css: "#58c69e"
}
};
const PRODUCTS = {
tea: {
label: "Tea",
short: "TEA",
color: 0xd78945
},
herbs: {
label: "Herbs",
short: "HRB",
color: 0x68a968
},
charm: {
label: "Charms",
short: "CHM",
color: 0x669bc8
},
key: {
label: "Moon Keys",
short: "KEY",
color: 0xb29ad3
}
};
const TOKEN_ORDER = ["copper", "amber", "jade"];
const PRODUCT_ORDER = ["tea", "herbs", "charm", "key"];
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.8,
metalness: 0.02,
flatShading: true,
...options
});
const tokenMaterials = Object.fromEntries(
TOKEN_ORDER.map((token) => [
token,
material(TOKENS[token].color, { roughness: 0.58 })
])
);
const productMaterials = Object.fromEntries(
PRODUCT_ORDER.map((product) => [
product,
material(PRODUCTS[product].color)
])
);
function addBox(parent, width, height, depth, color, x, y, z, 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 = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(
parent,
topRadius,
bottomRadius,
height,
color,
x,
y,
z,
sides = 8,
options = {}
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(topRadius, bottomRadius, height, sides),
typeof color === "number"
? material(color, options)
: color
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCone(parent, radius, height, color, x, y, z, sides = 7) {
const mesh = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, sides),
material(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addSphere(parent, radius, color, x, y, z, detail = 0) {
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(radius, 8, 6),
material(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
parent.add(mesh);
return mesh;
}
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function createTextSprite(width = 3.2, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = options.canvasWidth || 640;
canvas.height = options.canvasHeight || 180;
const context = canvas.getContext("2d");
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(width, width / (canvas.width / canvas.height), 1);
sprite.renderOrder = 20;
sprite.userData.set = (
title,
subtitle = "",
accent = "#ffffff",
background = "rgba(16,39,43,0.92)"
) => {
const w = canvas.width;
const h = canvas.height;
context.clearRect(0, 0, w, h);
roundedRect(context, 4, 4, w - 8, h - 8, 24);
context.fillStyle = background;
context.fill();
context.strokeStyle = accent;
context.globalAlpha = 0.65;
context.lineWidth = 4;
context.stroke();
context.globalAlpha = 1;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = accent;
if (subtitle) {
context.font = "900 45px system-ui, sans-serif";
context.fillText(title, w / 2, h * 0.39, w - 54);
context.fillStyle = "rgba(241,239,226,0.78)";
context.font = "800 27px system-ui, sans-serif";
context.fillText(subtitle, w / 2, h * 0.71, w - 50);
} else {
context.font = "900 49px system-ui, sans-serif";
context.fillText(title, w / 2, h / 2, w - 45);
}
texture.needsUpdate = true;
};
sprite.userData.set(
options.title || "",
options.subtitle || "",
options.accent || "#ffffff",
options.background
);
return sprite;
}
// -------------------------------------------------------------------------
// Ground and environmental dressing
// -------------------------------------------------------------------------
const world = new THREE.Group();
scene.add(world);
const plaza = addCylinder(
world,
13.5,
13.8,
0.38,
0xd8c79f,
0,
-0.28,
0,
40
);
plaza.receiveShadow = true;
const plazaInset = addCylinder(
world,
10.6,
10.6,
0.08,
0xe3d3ad,
0,
-0.055,
0,
40
);
plazaInset.receiveShadow = true;
const groundRing = new THREE.Mesh(
new THREE.TorusGeometry(10.8, 0.09, 6, 48),
material(0xbca97f)
);
groundRing.rotation.x = Math.PI / 2;
groundRing.position.y = 0.015;
world.add(groundRing);
// Irregular paving stones.
const pavingMaterial = material(0xcbb991);
for (let i = 0; i < 34; i++) {
const angle = (i / 34) * Math.PI * 2;
const radius = 5.3 + (i % 3) * 1.12;
const stone = addBox(
world,
0.55 + (i % 2) * 0.12,
0.035,
0.75 + (i % 4) * 0.06,
pavingMaterial,
Math.sin(angle) * radius,
0.015,
Math.cos(angle) * radius
);
stone.rotation.y = angle + Math.PI / 2 + (i % 2) * 0.12;
stone.castShadow = false;
}
// Central route board.
const board = new THREE.Group();
board.position.set(0, 0, 0.2);
world.add(board);
addBox(board, 2.2, 1.35, 0.16, 0x234e50, 0, 1.35, 0);
addBox(board, 0.16, 1.55, 0.16, 0x72583a, -0.75, 0.75, 0);
addBox(board, 0.16, 1.55, 0.16, 0x72583a, 0.75, 0.75, 0);
const boardSign = createTextSprite(2.5, {
title: "TOKEN EXCHANGE",
subtitle: "LIVE ROUTING BOARD",
accent: "#f5c84c"
});
boardSign.position.set(0, 2.16, 0.02);
board.add(boardSign);
// Entrance arch.
const gate = new THREE.Group();
gate.position.set(0, 0, 9.35);
world.add(gate);
addBox(gate, 0.24, 3.3, 0.24, 0x6c5942, -2.35, 1.65, 0);
addBox(gate, 0.24, 3.3, 0.24, 0x6c5942, 2.35, 1.65, 0);
addBox(gate, 5, 0.24, 0.24, 0x6c5942, 0, 3.15, 0);
const gateSign = createTextSprite(3.2, {
title: "MARKET GATE",
accent: "#f2eddf",
background: "rgba(75,64,47,0.93)"
});
gateSign.position.set(0, 3.45, 0);
gate.add(gateSign);
const flags = [];
function addFlag(parent, x, y, z, color, phase) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(
[0, 0, 0, 0.72, -0.18, 0, 0, -0.72, 0],
3
)
);
geometry.computeVertexNormals();
const flag = new THREE.Mesh(
geometry,
material(color, { side: THREE.DoubleSide })
);
flag.position.set(x, y, z);
parent.add(flag);
flags.push({ mesh: flag, phase });
}
addFlag(gate, -2.25, 3.1, 0, 0xe99155, 0.2);
addFlag(gate, -0.75, 3.1, 0, 0xf5c84c, 1.1);
addFlag(gate, 0.75, 3.1, 0, 0x58c69e, 2.1);
addFlag(gate, 2.25, 3.1, 0, 0x669bc8, 3.2);
function addTree(x, z, scale = 1, color = 0x668d63) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
world.add(tree);
addCylinder(tree, 0.18, 0.25, 2.2, 0x75563c, 0, 1.1, 0, 7);
addCone(tree, 1.12, 2.4, color, 0, 2.45, 0, 7);
addCone(tree, 0.85, 1.9, color, 0, 3.45, 0, 7);
return tree;
}
[
[-10.4, 3.8, 1.05, 0x5e8864],
[-9.1, -6.8, 0.92, 0x789864],
[9.7, 4.8, 1.02, 0x5d8064],
[10.5, -5.3, 0.86, 0x789b69],
[-5.8, 8.3, 0.78, 0x6d9367],
[5.7, 8.4, 0.85, 0x567f61],
[-11.8, -1.8, 0.75, 0x6d9367],
[11.7, -0.8, 0.78, 0x789b69]
].forEach((entry) => addTree(...entry));
// -------------------------------------------------------------------------
// Shop definitions
// -------------------------------------------------------------------------
const shopDefinitions = [
{
id: "ember",
name: "EMBER TEA",
short: "Ember",
color: 0xe48648,
css: "#e48648",
position: [-6.1, 0, 1.55],
accepted: { copper: true, amber: false, jade: true },
products: { tea: 9, herbs: 7, charm: 3, key: 0 },
tokens: { copper: 2, amber: 0, jade: 1 }
},
{
id: "moss",
name: "MOSS & ROOT",
short: "Moss",
color: 0x66a66e,
css: "#66a66e",
position: [0, 0, -5.15],
accepted: { copper: true, amber: true, jade: false },
products: { tea: 3, herbs: 10, charm: 5, key: 5 },
tokens: { copper: 2, amber: 2, jade: 0 }
},
{
id: "sky",
name: "SKY RELIC",
short: "Sky",
color: 0x5e91ca,
css: "#5e91ca",
position: [6.1, 0, 1.55],
accepted: { copper: false, amber: true, jade: true },
products: { tea: 6, herbs: 4, charm: 9, key: 0 },
tokens: { copper: 0, amber: 2, jade: 2 }
}
];
const shops = [];
const shopsById = new Map();
function createShop(definition) {
const group = new THREE.Group();
group.position.fromArray(definition.position);
group.lookAt(0, 0, 0);
world.add(group);
const shop = {
...definition,
group,
acceptedDots: {},
stockBlocks: {},
tokenCoins: {},
customerCounter: 0
};
addBox(group, 4.65, 0.18, 3.05, 0x9b8060, 0, 0.02, 0);
addBox(group, 4.5, 0.12, 2.9, 0xe5d7b8, 0, 0.16, 0);
// Counter.
addBox(group, 4.05, 0.83, 0.75, definition.color, 0, 0.64, 0.88);
addBox(group, 4.28, 0.16, 0.93, 0xf0dfb8, 0, 1.1, 0.88);
// Stall frame.
addBox(group, 0.15, 3.05, 0.15, 0x72583c, -2.03, 1.5, -1.12);
addBox(group, 0.15, 3.05, 0.15, 0x72583c, 2.03, 1.5, -1.12);
// Awning panels.
for (let i = 0; i < 6; i++) {
const panelColor = i % 2 === 0 ? definition.color : 0xf0e6c9;
const panel = addBox(
group,
0.75,
0.14,
2.65,
panelColor,
-1.9 + i * 0.76,
3.02,
-0.05
);
panel.rotation.x = -0.08;
}
addBox(group, 4.65, 0.12, 0.15, 0x654c35, 0, 2.94, 1.2);
// Shelf.
addBox(group, 3.95, 0.15, 0.58, 0x7e5f42, 0, 1.36, -0.77);
// Product pedestals and individual stock blocks.
PRODUCT_ORDER.forEach((product, index) => {
const x = -1.42 + index * 0.95;
addBox(group, 0.72, 0.27, 0.68, 0xb4976f, x, 0.29, -0.78);
const blocks = [];
for (let i = 0; i < 10; i++) {
const block = addBox(
group,
0.47,
0.27,
0.47,
productMaterials[product],
x,
0.57 + i * 0.27,
-0.78
);
block.visible = false;
blocks.push(block);
}
shop.stockBlocks[product] = blocks;
});
// Accepted-token chips on the counter face.
TOKEN_ORDER.forEach((token, index) => {
const chip = addCylinder(
group,
0.13,
0.13,
0.07,
tokenMaterials[token],
-0.78 + index * 0.78,
0.74,
1.28,
10
);
chip.rotation.x = Math.PI / 2;
shop.acceptedDots[token] = chip;
});
// Token balances held by the shop.
TOKEN_ORDER.forEach((token, index) => {
const coins = [];
for (let i = 0; i < 8; i++) {
const coin = addCylinder(
group,
0.15,
0.15,
0.08,
tokenMaterials[token],
-0.72 + index * 0.72,
1.23 + i * 0.08,
0.68,
10
);
coin.visible = false;
coins.push(coin);
}
shop.tokenCoins[token] = coins;
});
// Crates and sacks.
addBox(group, 0.7, 0.56, 0.62, 0x9a754b, -2.55, 0.44, 0.65);
addBox(group, 0.62, 0.48, 0.58, 0xb58b59, -2.5, 0.98, 0.62);
addSphere(group, 0.34, 0xc9b78c, 2.55, 0.4, 0.64);
const nameSign = createTextSprite(3.45, {
title: definition.name,
accent: "#ffffff",
background: "rgba(18,42,46,0.94)"
});
nameSign.position.set(0, 3.62, -0.12);
group.add(nameSign);
const policySign = createTextSprite(3.05, {
title: "ROUTE POLICY",
accent: "#79d2ad",
background: "rgba(18,42,46,0.94)"
});
policySign.position.set(0, 4.27, -0.12);
group.add(policySign);
shop.nameSign = nameSign;
shop.policySign = policySign;
group.updateMatrixWorld(true);
shops.push(shop);
shopsById.set(shop.id, shop);
updateShopVisuals(shop);
return shop;
}
shopDefinitions.forEach(createShop);
function acceptedTokensText(shop) {
return TOKEN_ORDER.filter((token) => shop.accepted[token])
.map((token) => TOKENS[token].label.toUpperCase())
.join(" + ");
}
function updateShopVisuals(shop) {
TOKEN_ORDER.forEach((token) => {
shop.acceptedDots[token].visible = shop.accepted[token];
shop.tokenCoins[token].forEach((coin, index) => {
coin.visible = index < Math.min(8, shop.tokens[token]);
});
});
PRODUCT_ORDER.forEach((product) => {
shop.stockBlocks[product].forEach((block, index) => {
block.visible = index < shop.products[product];
});
});
const rejectsAmber = shop.id === "moss" && !shop.accepted.amber;
shop.policySign.userData.set(
rejectsAmber ? "AMBER REJECTED" : "ROUTE POLICY",
rejectsAmber
? "AMBERS WILL REROUTE"
: `ACCEPTS: ${acceptedTokensText(shop)}`,
rejectsAmber ? "#ff8a7e" : "#79d2ad",
"rgba(18,42,46,0.94)"
);
}
function customerPoint(shop) {
const offset = ((shop.customerCounter++ % 5) - 2) * 0.48;
const local = new THREE.Vector3(offset, 0, 2.62);
shop.group.updateMatrixWorld(true);
return shop.group.localToWorld(local);
}
// -------------------------------------------------------------------------
// Simulation state
// -------------------------------------------------------------------------
const traders = [];
const routes = [];
const floaters = [];
const eventEntries = [];
const stats = {
trades: 0,
rerouted: 0,
stalls: 0,
volume: 0
};
let paused = false;
let speed = 1;
let simulationTime = 0;
let nextTraderId = 1;
let spawnTimer = 0;
let spawnIndex = 0;
let policyTouched = false;
const spawnSequence = [
{ token: "copper", product: "herbs" },
{ token: "amber", product: "charm" },
{ token: "jade", product: "tea" },
{ token: "copper", product: "tea" },
{ token: "amber", product: "herbs" },
{ token: "jade", product: "charm" },
{ token: "copper", product: "key" },
{ token: "amber", product: "key" },
{ token: "jade", product: "herbs" },
{ token: "amber", product: "tea" },
{ token: "copper", product: "charm" },
{ token: "jade", product: "key" }
];
const productPreference = {
tea: ["ember", "sky", "moss"],
herbs: ["moss", "ember", "sky"],
charm: ["sky", "moss", "ember"],
key: ["moss", "ember", "sky"]
};
function findRoute(token, product) {
const preferred = productPreference[product];
for (const id of preferred) {
const shop = shopsById.get(id);
if (
shop.accepted[token] &&
shop.products[product] > 0
) {
return shop;
}
}
return null;
}
function createTrader(spec, delay = 0) {
const trader = {
id: nextTraderId++,
token: spec.token,
product: spec.product,
group: new THREE.Group(),
state: delay > 0 ? "queued" : "travel",
timer: 0,
progress: 0,
route: null,
targetId: null,
queueDelay: delay,
retryTimer: 0,
recovery: false
};
const palette = [
0x4f7480,
0x9c6655,
0x6d8360,
0x796b8e,
0x8f7350,
0x4c7c78
];
const bodyColor = palette[trader.id % palette.length];
addBox(trader.group, 0.18, 0.45, 0.2, 0x33434a, -0.13, 0.25, 0);
addBox(trader.group, 0.18, 0.45, 0.2, 0x33434a, 0.13, 0.25, 0);
addCylinder(
trader.group,
0.24,
0.31,
0.67,
bodyColor,
0,
0.76,
0,
6
);
addSphere(trader.group, 0.2, 0xd8a77d, 0, 1.22, 0);
addCone(trader.group, 0.22, 0.19, 0x493d35, 0, 1.39, 0, 7);
const tokenMesh = addCylinder(
trader.group,
0.14,
0.14,
0.12,
tokenMaterials[trader.token],
0.36,
0.79,
0.15,
8
);
tokenMesh.rotation.z = Math.PI / 2;
const productMesh = addBox(
trader.group,
0.3,
0.3,
0.3,
productMaterials[trader.product],
-0.34,
0.83,
0.17
);
productMesh.visible = false;
const bubble = createTextSprite(2.25, {
title: `${TOKENS[trader.token].short} / ${PRODUCTS[trader.product].short}`,
accent: TOKENS[trader.token].css
});
bubble.position.set(0, 1.84, 0);
trader.group.add(bubble);
trader.bubble = bubble;
trader.tokenMesh = tokenMesh;
trader.productMesh = productMesh;
const entryOffset = ((trader.id * 0.37) % 1.4) - 0.7;
trader.group.position.set(entryOffset, 0.04, 9.05);
trader.group.rotation.y = Math.PI;
scene.add(trader.group);
traders.push(trader);
if (delay <= 0) {
assignRoute(trader);
}
return trader;
}
function setBubble(trader, text, color = TOKENS[trader.token].css) {
trader.bubble.userData.set(
text,
"",
color,
"rgba(16,39,43,0.94)"
);
}
function makeRoute(trader, shop) {
removeRoute(trader);
const start = trader.group.position.clone();
start.y = 0.065;
const end = customerPoint(shop);
end.y = 0.065;
const control = start.clone().lerp(end, 0.5);
control.y = 0.065;
const curve = new THREE.QuadraticBezierCurve3(start, control, end);
const geometry = new THREE.BufferGeometry().setFromPoints(
curve.getPoints(36)
);
const line = new THREE.Line(
geometry,
new THREE.LineDashedMaterial({
color: shop.color,
dashSize: 0.28,
gapSize: 0.2,
transparent: true,
opacity: 0.72
})
);
line.computeLineDistances();
line.userData.traderId = trader.id;
scene.add(line);
routes.push(line);
trader.route = { curve, line, shop };
}
function removeRoute(trader) {
if (!trader.route) return;
const index = routes.indexOf(trader.route.line);
if (index >= 0) routes.splice(index, 1);
scene.remove(trader.route.line);
trader.route.line.geometry.dispose();
trader.route.line.material.dispose();
trader.route = null;
}
function assignRoute(trader, recovery = false) {
const shop = findRoute(trader.token, trader.product);
if (!shop) {
enterStall(trader);
return;
}
trader.targetId = shop.id;
trader.state = "travel";
trader.progress = 0;
trader.recovery = recovery;
makeRoute(trader, shop);
setBubble(
trader,
recovery
? `ROUTE FOUND → ${shop.short.toUpperCase()}`
: `${TOKENS[trader.token].short} → ${shop.short.toUpperCase()}`,
recovery ? "#79d2ad" : TOKENS[trader.token].css
);
}
function enterStall(trader) {
if (trader.state !== "stalled") {
stats.stalls++;
}
removeRoute(trader);
trader.state = "stalled";
trader.targetId = null;
trader.timer = 0;
trader.retryTimer = 0;
const stallIndex = traders.filter((item) => item.state === "stalled").length - 1;
trader.group.position.set(
-3.0 + (stallIndex % 4) * 1.05,
0.04,
2.05 + Math.floor(stallIndex / 4) * 0.8
);
trader.group.rotation.y = Math.PI;
setBubble(trader, "STALLED • NO ROUTE", "#ff786d");
addEvent(
"stall",
`${TOKENS[trader.token].label} / ${PRODUCTS[trader.product].label} has no valid shop.`
);
}
function beginReroute(trader, reason = "POLICY CHANGED") {
if (!trader.route && trader.state === "stalled") return;
removeRoute(trader);
trader.state = "reroute";
trader.timer = 0;
trader.recovery = false;
trader.targetId = null;
setBubble(trader, `${reason} • ROUTING`, "#71c9d1");
}
function performTrade(trader, shop) {
if (!shop.accepted[trader.token] || shop.products[trader.product] <= 0) {
beginReroute(trader, "REJECTED");
return;
}
shop.products[trader.product] -= 1;
shop.tokens[trader.token] += 1;
trader.tokenMesh.visible = false;
trader.productMesh.visible = true;
removeRoute(trader);
trader.state = "leaving";
trader.timer = 0;
trader.exitStart = trader.group.position.clone();
trader.exitEnd = new THREE.Vector3(
-2.8 + Math.random() * 5.6,
0.04,
10.4
);
stats.trades++;
stats.volume++;
setBubble(trader, "TRADED ✓", "#79d2ad");
addEvent(
"trade",
`${TOKENS[trader.token].label} → ${PRODUCTS[trader.product].label} at ${shop.name}.`
);
addFloater(
shop,
`+1 ${TOKENS[trader.token].short} / −1 ${PRODUCTS[trader.product].short}`,
TOKENS[trader.token].css
);
updateShopVisuals(shop);
updateInventoryUI(true);
}
function addFloater(shop, text, color) {
const sprite = createTextSprite(3.3, {
title: text,
accent: color
});
const point = customerPoint(shop);
sprite.position.set(point.x, 2.0, point.z);
scene.add(sprite);
floaters.push({
sprite,
life: 0,
duration: 1.55
});
}
function updateTraders(dt) {
for (let index = traders.length - 1; index >= 0; index--) {
const trader = traders[index];
if (trader.state === "queued") {
trader.queueDelay -= dt;
if (trader.queueDelay <= 0) {
assignRoute(trader);
}
continue;
}
if (trader.state === "travel" && trader.route) {
trader.progress = Math.min(1, trader.progress + dt * 0.19);
const point = trader.route.curve.getPoint(trader.progress);
trader.group.position.x = point.x;
trader.group.position.z = point.z;
trader.group.position.y =
0.04 + Math.abs(Math.sin(simulationTime * 9 + trader.id)) * 0.045;
const tangent = trader.route.curve.getTangent(trader.progress);
trader.group.rotation.y = Math.atan2(tangent.x, tangent.z);
if (trader.progress >= 1) {
trader.state = "negotiate";
trader.timer = 0;
setBubble(trader, "CHECKING STOCK", "#f2eddf");
}
} else if (trader.state === "negotiate") {
trader.timer += dt;
if (trader.timer >= 0.65) {
const shop = shopsById.get(trader.targetId);
performTrade(trader, shop);
}
} else if (trader.state === "reroute") {
trader.timer += dt;
if (trader.timer >= 1.05) {
const shop = findRoute(trader.token, trader.product);
if (shop) {
trader.targetId = shop.id;
trader.state = "travel";
trader.progress = 0;
makeRoute(trader, shop);
if (trader.recovery) {
setBubble(
trader,
`ROUTE FOUND → ${shop.short.toUpperCase()}`,
"#79d2ad"
);
} else {
stats.rerouted++;
setBubble(
trader,
`REROUTED → ${shop.short.toUpperCase()}`,
"#71c9d1"
);
addEvent(
"reroute",
`${TOKENS[trader.token].label} trade redirected to ${shop.name}.`
);
}
} else {
enterStall(trader);
}
}
} else if (trader.state === "stalled") {
trader.retryTimer += dt;
if (trader.retryTimer >= 1.4) {
trader.retryTimer = 0;
const shop = findRoute(trader.token, trader.product);
if (shop) {
trader.state = "reroute";
trader.timer = 0;
trader.recovery = true;
setBubble(trader, "POLICY RECHECK", "#f5c84c");
}
}
} else if (trader.state === "leaving") {
trader.timer += dt;
const t = Math.min(1, trader.timer * 0.56);
trader.group.position.lerpVectors(
trader.exitStart,
trader.exitEnd,
t
);
trader.group.rotation.y = Math.PI;
if (trader.timer > 1.8) {
scene.remove(trader.group);
traders.splice(index, 1);
}
}
}
}
function updateFloaters(dt) {
for (let index = floaters.length - 1; index >= 0; index--) {
const floater = floaters[index];
floater.life += dt;
floater.sprite.position.y += dt * 0.72;
floater.sprite.material.opacity = Math.max(
0,
1 - floater.life / floater.duration
);
if (floater.life >= floater.duration) {
scene.remove(floater.sprite);
floater.sprite.material.map.dispose();
floater.sprite.material.dispose();
floaters.splice(index, 1);
}
}
}
// -------------------------------------------------------------------------
// Policy disruption and test batches
// -------------------------------------------------------------------------
function injectBatch() {
const batch = [
{ token: "amber", product: "herbs", delay: 0 },
{ token: "amber", product: "charm", delay: 0.42 },
{ token: "amber", product: "key", delay: 0.85 }
];
batch.forEach((spec) => createTrader(spec, spec.delay));
addEvent(
"policy",
"Three Amber exchanges entered the market: herbs, charms, and a Moon Key."
);
}
function togglePolicy() {
const moss = shopsById.get("moss");
policyTouched = true;
moss.accepted.amber = !moss.accepted.amber;
if (!moss.accepted.amber) {
addEvent(
"policy",
"Moss & Root stopped accepting Amber."
);
traders.forEach((trader) => {
if (
trader.token === "amber" &&
trader.targetId === "moss" &&
(trader.state === "travel" || trader.state === "negotiate")
) {
beginReroute(trader, "AMBER REJECTED");
}
});
injectBatch();
} else {
addEvent(
"policy",
"Moss & Root accepts Amber again. Stalled trades will retry."
);
}
updateShopVisuals(moss);
updatePolicyUI();
updateInventoryUI(true);
}
function updatePolicyUI() {
const button = document.querySelector("#policy-button");
const state = document.querySelector("#policy-state");
const moss = shopsById.get("moss");
if (moss.accepted.amber) {
button.classList.remove("reverted");
button.innerHTML = `
Make Moss stop accepting Amber
<small>Existing trades will recalculate their destination.</small>
`;
state.textContent = "Amber accepted";
} else {
button.classList.add("reverted");
button.innerHTML = `
Restore Amber at Moss & Root
<small>Stalled exchanges will automatically retry.</small>
`;
state.textContent = "Amber rejected";
}
}
// -------------------------------------------------------------------------
// Inventory UI
// -------------------------------------------------------------------------
const inventoryGrid = document.querySelector("#inventory-grid");
const shopUI = new Map();
function buildInventoryUI() {
inventoryGrid.innerHTML = shops
.map(
(shop) => `
<article class="shop-card" data-shop="${shop.id}">
<div class="shop-card-title">
<span class="shop-swatch" style="background:${shop.css}"></span>
${shop.name}
</div>
<div class="accepted">
${TOKEN_ORDER.map(
(token) => `
<span
class="token-chip"
data-accepted="${token}"
style="--chip:${TOKENS[token].css}"
>${TOKENS[token].short}</span>
`
).join("")}
</div>
<div class="products">
${PRODUCT_ORDER.map(
(product) => `
<div class="product-cell">
<div class="product-label">
<span>${PRODUCTS[product].short}</span>
<b data-product="${product}">0</b>
</div>
<div class="stock-bar">
<div
class="stock-fill"
data-fill="${product}"
style="--shop-color:${shop.css}"
></div>
</div>
</div>
`
).join("")}
</div>
<div class="shop-tokens">
${TOKEN_ORDER.map(
(token) => `
<span style="--chip:${TOKENS[token].css}">
<i></i>${TOKENS[token].short}
<b data-token="${token}">0</b>
</span>
`
).join("")}
</div>
</article>
`
)
.join("");
shops.forEach((shop) => {
const root = inventoryGrid.querySelector(
`[data-shop="${shop.id}"]`
);
shopUI.set(shop.id, {
root,
products: Object.fromEntries(
PRODUCT_ORDER.map((product) => [
product,
{
value: root.querySelector(`[data-product="${product}"]`),
fill: root.querySelector(`[data-fill="${product}"]`)
}
])
),
tokens: Object.fromEntries(
TOKEN_ORDER.map((token) => [
token,
root.querySelector(`[data-token="${token}"]`)
])
),
accepted: Object.fromEntries(
TOKEN_ORDER.map((token) => [
token,
root.querySelector(`[data-accepted="${token}"]`)
])
)
});
});
updateInventoryUI(false);
}
function updateInventoryUI(animate = false) {
shops.forEach((shop) => {
const ui = shopUI.get(shop.id);
if (!ui) return;
PRODUCT_ORDER.forEach((product) => {
const cell = ui.products[product];
const oldValue = Number(cell.value.textContent);
const value = shop.products[product];
if (oldValue !== value) {
cell.value.textContent = value;
cell.value.classList.remove("flash");
void cell.value.offsetWidth;
if (animate) cell.value.classList.add("flash");
}
cell.fill.style.width = `${Math.min(100, value * 10)}%`;
});
TOKEN_ORDER.forEach((token) => {
const cell = ui.tokens[token];
const oldValue = Number(cell.textContent);
const value = shop.tokens[token];
if (oldValue !== value) {
cell.textContent = value;
cell.classList.remove("flash");
void cell.offsetWidth;
if (animate) cell.classList.add("flash");
}
ui.accepted[token].classList.toggle(
"accepted",
shop.accepted[token]
);
});
});
}
function updateMetrics() {
document.querySelector("#trade-count").textContent = stats.trades;
document.querySelector("#reroute-count").textContent = stats.rerouted;
document.querySelector("#stall-count").textContent = stats.stalls;
}
// -------------------------------------------------------------------------
// Event log
// -------------------------------------------------------------------------
const eventLog = document.querySelector("#event-log");
function formatSimulationTime(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 addEvent(type, message) {
eventEntries.unshift({
type,
message,
time: formatSimulationTime(simulationTime)
});
if (eventEntries.length > 9) eventEntries.pop();
eventLog.innerHTML = eventEntries
.map(
(entry) => `
<div class="log-entry ${entry.type}">
<span class="log-time">${entry.time}</span>
<span>${entry.message}</span>
</div>
`
)
.join("");
}
// -------------------------------------------------------------------------
// Reset and controls
// -------------------------------------------------------------------------
function resetSimulation() {
traders.forEach((trader) => {
removeRoute(trader);
scene.remove(trader.group);
});
traders.length = 0;
routes.forEach((route) => {
scene.remove(route);
route.geometry.dispose();
route.material.dispose();
});
routes.length = 0;
floaters.forEach((floater) => {
scene.remove(floater.sprite);
floater.sprite.material.map.dispose();
floater.sprite.material.dispose();
});
floaters.length = 0;
shopDefinitions.forEach((definition) => {
const shop = shopsById.get(definition.id);
Object.keys(shop.accepted).forEach((token) => {
shop.accepted[token] = definition.accepted[token];
});
PRODUCT_ORDER.forEach((product) => {
shop.products[product] = definition.products[product];
});
TOKEN_ORDER.forEach((token) => {
shop.tokens[token] = definition.tokens[token];
});
updateShopVisuals(shop);
});
stats.trades = 0;
stats.rerouted = 0;
stats.stalls = 0;
stats.volume = 0;
simulationTime = 0;
spawnTimer = 0;
spawnIndex = 0;
nextTraderId = 1;
policyTouched = false;
eventEntries.length = 0;
eventLog.innerHTML = "";
addEvent(
"policy",
"Market reopened. Moss & Root currently accepts Amber."
);
updatePolicyUI();
updateInventoryUI(false);
updateMetrics();
createTrader({ token: "copper", product: "herbs" });
createTrader({ token: "amber", product: "charm" });
}
document.querySelector("#policy-button").addEventListener("click", togglePolicy);
document.querySelector("#batch-button").addEventListener("click", injectBatch);
document.querySelector("#pause-button").addEventListener("click", (event) => {
paused = !paused;
event.currentTarget.textContent = paused ? "Resume market" : "Pause market";
document.querySelector("#market-status").textContent = paused
? "Market paused"
: "Market open";
});
document.querySelector("#reset-button").addEventListener("click", resetSimulation);
document.querySelector("#view-button").addEventListener("click", () => {
orbit.theta = defaultCamera.theta;
orbit.phi = defaultCamera.phi;
orbit.radius = defaultCamera.radius;
orbit.target.set(0, 1.05, 0);
});
document.querySelector("#speed").addEventListener("input", (event) => {
speed = Number(event.target.value);
document.querySelector("#speed-value").textContent = `${speed.toFixed(1)}×`;
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
buildInventoryUI();
updatePolicyUI();
updateMetrics();
addEvent(
"policy",
"Market opened. Amber exchanges are currently routed normally."
);
createTrader({ token: "copper", product: "herbs" });
createTrader({ token: "amber", product: "charm" });
let uiTimer = 0;
function animate() {
requestAnimationFrame(animate);
const realDt = Math.min(clock.getDelta(), 0.05);
const dt = paused ? 0 : realDt * speed;
simulationTime += dt;
if (!paused) {
spawnTimer += dt;
if (spawnTimer >= 1.42) {
spawnTimer = 0;
const spec = spawnSequence[spawnIndex % spawnSequence.length];
spawnIndex++;
createTrader(spec);
}
updateTraders(dt);
updateFloaters(dt);
}
// Gentle environmental motion continues even while trading is paused.
flags.forEach((flag) => {
flag.mesh.rotation.y = Math.sin(realDt * 2.2 + flag.phase) * 0.22;
flag.mesh.rotation.z = Math.sin(realDt * 1.8 + flag.phase) * 0.05;
});
uiTimer += realDt;
if (uiTimer >= 0.14) {
uiTimer = 0;
updateMetrics();
updateInventoryUI(false);
}
updateCamera();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
animate();
</script>
</body>
</html>
```