Prompt specification
Build or customize the Three.js 3D scene "Toy Fruit Market Clearing Table" 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: Toy Fruit Market Clearing Table
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/toy-fruit-market-clearing-table-x3142
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring supply and demand schedules in a fictional market. Show sellers and buyers with explicit reservation prices and fixed quantities. Match compatible trades, displaying remaining offers instead of automatically forcing every token to sell. Voxel style.
Working Three.js Starter (toy-fruit-market-clearing-table-x3142):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clockwork Commons — Voxel Supply & Demand Market</title>
<style>
:root {
color-scheme: dark;
--bg: #07131b;
--panel: #0d1b25;
--panel-2: #122531;
--line: #29404b;
--text: #eaf4f3;
--muted: #91a8ad;
--seller: #f09a52;
--seller-soft: rgba(240, 154, 82, 0.13);
--buyer: #55c9d6;
--buyer-soft: rgba(85, 201, 214, 0.13);
--gold: #f4c95d;
--green: #86d29c;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
width: 100%;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button {
font: inherit;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
width: 100vw;
height: 100vh;
}
#stage {
position: relative;
min-width: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, #17313c 0%, #0a1821 48%, #07131b 100%);
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.stage-heading {
position: absolute;
z-index: 5;
top: 24px;
left: 26px;
pointer-events: none;
text-shadow: 0 2px 12px #000;
}
.eyebrow {
color: var(--gold);
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.stage-heading h1 {
margin: 5px 0 3px;
font-size: clamp(1.45rem, 2.5vw, 2.35rem);
line-height: 1;
letter-spacing: -0.035em;
}
.stage-heading p {
margin: 0;
color: #a9bec2;
font-size: 0.8rem;
}
.stage-tools {
position: absolute;
z-index: 7;
bottom: 20px;
left: 24px;
display: flex;
align-items: center;
gap: 12px;
}
.stage-tools button {
border: 1px solid #39515b;
border-radius: 7px;
padding: 8px 11px;
color: #d9e9e9;
background: rgba(9, 25, 33, 0.86);
cursor: pointer;
font-size: 0.75rem;
font-weight: 700;
backdrop-filter: blur(8px);
}
.stage-tools button:hover {
border-color: #66848c;
background: #142d38;
}
.stage-tools span {
color: #91a8ad;
font-size: 0.7rem;
text-shadow: 0 1px 6px #000;
}
#labels {
position: absolute;
inset: 0;
z-index: 4;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
left: 0;
top: 0;
width: max-content;
max-width: 190px;
will-change: transform;
transition: opacity 120ms ease;
}
.world-label > div {
transform: translate(-50%, -100%);
}
.party-label {
border: 1px solid #405660;
border-top: 3px solid var(--party-color);
border-radius: 7px;
padding: 9px 10px;
background: rgba(8, 22, 29, 0.93);
box-shadow: 0 7px 20px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(8px);
}
.party-label.seller {
--party-color: var(--seller);
}
.party-label.buyer {
--party-color: var(--buyer);
}
.label-role {
color: var(--party-color);
font-size: 0.58rem;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.party-label strong {
display: block;
margin: 3px 0 5px;
font-size: 0.78rem;
line-height: 1.1;
}
.label-meta {
display: flex;
justify-content: space-between;
gap: 13px;
color: #91a8ad;
font-size: 0.62rem;
}
.label-meta b {
color: #dce9e8;
font-weight: 750;
}
.court-label {
padding: 7px 11px;
border: 1px solid rgba(244, 201, 93, 0.45);
border-radius: 6px;
color: var(--gold);
background: rgba(8, 22, 29, 0.9);
box-shadow: 0 7px 20px rgba(0, 0, 0, 0.25);
text-align: center;
backdrop-filter: blur(8px);
}
.court-label strong {
display: block;
font-size: 0.67rem;
letter-spacing: 0.11em;
}
.court-label span {
display: block;
margin-top: 2px;
color: #a9bec2;
font-size: 0.58rem;
}
#loading {
position: absolute;
z-index: 10;
inset: 0;
display: grid;
place-items: center;
color: #a9bec2;
background: #07131b;
font-size: 0.85rem;
letter-spacing: 0.08em;
}
#panel {
position: relative;
z-index: 10;
overflow-y: auto;
padding: 24px 22px 30px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(19, 40, 50, 0.65), transparent 220px),
var(--panel);
scrollbar-width: thin;
scrollbar-color: #35505a transparent;
}
#panel h1 {
margin: 6px 0 8px;
font-size: 1.7rem;
letter-spacing: -0.04em;
}
.intro {
margin: 0;
color: var(--muted);
font-size: 0.8rem;
line-height: 1.55;
}
.rule {
margin: 15px 0;
border: 1px solid #2d4651;
border-radius: 8px;
padding: 10px 11px;
color: #c4d4d5;
background: #10232d;
font-size: 0.72rem;
line-height: 1.45;
}
.rule strong {
color: var(--gold);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin: 16px 0;
}
.metric {
min-width: 0;
padding: 10px 8px;
border: 1px solid #2b4550;
border-radius: 8px;
background: #10232d;
text-align: center;
}
.metric strong {
display: block;
color: var(--gold);
font-size: 1.35rem;
line-height: 1;
}
.metric span {
display: block;
margin-top: 6px;
color: var(--muted);
font-size: 0.58rem;
line-height: 1.2;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-bottom: 20px;
}
.primary,
.secondary {
border-radius: 7px;
padding: 11px 12px;
cursor: pointer;
font-size: 0.76rem;
font-weight: 800;
}
.primary {
border: 1px solid #f4ca61;
color: #182128;
background: var(--gold);
box-shadow: 0 5px 16px rgba(244, 201, 93, 0.16);
}
.primary:hover:not(:disabled) {
background: #ffda76;
transform: translateY(-1px);
}
.primary:disabled {
cursor: default;
opacity: 0.52;
}
.secondary {
border: 1px solid #36515c;
color: #c9d8d9;
background: #132a35;
}
.secondary:hover {
border-color: #5a7882;
background: #183440;
}
.section-title {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin: 22px 0 9px;
}
.section-title h2 {
margin: 0;
font-size: 0.82rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-title span {
color: var(--muted);
font-size: 0.65rem;
}
.schedule-group + .schedule-group {
margin-top: 14px;
}
.group-label {
margin-bottom: 6px;
color: var(--muted);
font-size: 0.62rem;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.schedule-row {
margin-bottom: 6px;
padding: 10px 11px;
border: 1px solid #2b424c;
border-left: 3px solid var(--row-color);
border-radius: 7px;
background: #10222b;
}
.schedule-row.seller {
--row-color: var(--seller);
}
.schedule-row.buyer {
--row-color: var(--buyer);
}
.schedule-row.depleted {
opacity: 0.62;
}
.row-top,
.row-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.row-top strong {
font-size: 0.76rem;
}
.price-pill {
flex: 0 0 auto;
border-radius: 4px;
padding: 3px 5px;
color: var(--row-color);
background: rgba(255, 255, 255, 0.06);
font-size: 0.58rem;
font-weight: 850;
letter-spacing: 0.06em;
}
.row-bottom {
margin-top: 5px;
color: var(--muted);
font-size: 0.64rem;
}
.row-status {
color: #dce9e8;
font-weight: 700;
}
.trade-list {
display: grid;
gap: 7px;
}
.trade-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 7px;
padding: 10px;
border: 1px solid #2b424c;
border-radius: 7px;
background: #10222b;
}
.trade-route {
font-size: 0.72rem;
font-weight: 750;
line-height: 1.35;
}
.trade-route em {
margin: 0 4px;
color: var(--gold);
font-style: normal;
}
.trade-detail {
margin-top: 4px;
color: var(--muted);
font-size: 0.62rem;
}
.trade-price {
align-self: center;
color: var(--gold);
font-size: 0.76rem;
font-weight: 850;
}
.empty {
padding: 16px;
border: 1px dashed #35505b;
border-radius: 8px;
color: var(--muted);
background: rgba(16, 35, 45, 0.5);
font-size: 0.72rem;
line-height: 1.5;
text-align: center;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px 15px;
margin-top: 20px;
padding-top: 14px;
border-top: 1px solid #29404b;
color: var(--muted);
font-size: 0.64rem;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
background: var(--swatch);
}
.allocation-note {
margin-top: 14px;
color: #748e94;
font-size: 0.63rem;
line-height: 1.5;
}
@media (max-width: 900px) {
body {
overflow: auto;
}
#app {
display: block;
width: 100%;
height: auto;
}
#stage {
height: 65vh;
min-height: 500px;
}
#panel {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.stage-heading {
top: 18px;
left: 18px;
}
.stage-tools {
left: 16px;
bottom: 14px;
}
}
@media (max-width: 520px) {
.stage-heading p,
.stage-tools span {
display: none;
}
.stage-heading h1 {
font-size: 1.45rem;
}
#panel {
padding: 22px 16px 28px;
}
.party-label {
padding: 7px 8px;
}
.party-label strong {
font-size: 0.68rem;
}
.label-meta {
gap: 8px;
font-size: 0.55rem;
}
}
</style>
</head>
<body>
<div id="app">
<section id="stage" aria-label="Interactive 3D voxel market">
<div id="labels"></div>
<div class="stage-heading">
<div class="eyebrow">Fictional reservation-price market</div>
<h1>Clockwork Commons</h1>
<p>Voxel exchange court</p>
</div>
<div class="stage-tools">
<button id="resetView" type="button">Reset view</button>
<span>Drag to orbit · Scroll to zoom</span>
</div>
<div id="loading">Building the voxel market…</div>
</section>
<aside id="panel">
<div class="eyebrow">Supply & demand schedule</div>
<h1>Market Board</h1>
<p class="intro">
Sellers offer crates at a minimum reservation price. Buyers reserve
crates up to a maximum price. Offers only trade when the buyer’s
ceiling is at least the seller’s floor.
</p>
<div class="rule">
<strong>Compatibility:</strong>
buyer maximum ≥ seller minimum. Remaining offers stay visible when
they cannot trade.
</div>
<div class="metrics">
<div class="metric">
<strong id="mMatched">0</strong>
<span>Crates matched</span>
</div>
<div class="metric">
<strong id="mSeller">26</strong>
<span>Seller remains</span>
</div>
<div class="metric">
<strong id="mBuyer">24</strong>
<span>Buyer remains</span>
</div>
</div>
<div class="actions">
<button id="matchButton" class="primary" type="button">
Match compatible trades
</button>
<button id="resetMarket" class="secondary" type="button">
Reset
</button>
</div>
<div class="section-title">
<h2>Fixed schedules</h2>
<span>26 offered · 24 demanded</span>
</div>
<div id="schedule"></div>
<div class="section-title">
<h2>Trade ledger</h2>
<span id="tradeCount">0 trades</span>
</div>
<div id="trades" class="trade-list"></div>
<div class="legend">
<span><i class="swatch" style="--swatch:#f09a52"></i>Seller offer</span>
<span><i class="swatch" style="--swatch:#55c9d6"></i>Buyer demand</span>
<span><i class="swatch" style="--swatch:#f4c95d"></i>Matched crate</span>
</div>
<p class="allocation-note">
Allocation priority: highest buyer ceiling first, then lowest seller
floor. This is a compatible-trade demonstration, not an automatic
liquidation of the entire market.
</p>
</aside>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
const labelsContainer = document.getElementById("labels");
const loading = document.getElementById("loading");
const sellers = [
{
name: "Fern Farm",
price: 5,
qty: 8,
color: 0xe88946
},
{
name: "Copper Works",
price: 8,
qty: 12,
color: 0xd5a13c
},
{
name: "Star Forge",
price: 12,
qty: 6,
color: 0xc96545
}
];
const buyers = [
{
name: "Moon Kitchen",
price: 11,
qty: 10,
color: 0x49c4d1
},
{
name: "Hill Canteen",
price: 9,
qty: 5,
color: 0x68a9dc
},
{
name: "Lantern Guild",
price: 6,
qty: 9,
color: 0x7779c8
}
];
const sellerRemaining = sellers.map((offer) => offer.qty);
const buyerRemaining = buyers.map((offer) => offer.qty);
const sellerUnits = sellers.map(() => []);
const buyerUnits = buyers.map(() => []);
let currentMatches = [];
let marketState = "ready";
let runId = 0;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x091820);
scene.fog = new THREE.Fog(0x091820, 31, 58);
const camera = new THREE.PerspectiveCamera(
42,
stage.clientWidth / stage.clientHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(stage.clientWidth, stage.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
stage.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xc6efff,
0x152029,
1.8
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe0ae, 3.1);
sun.position.set(-9, 17, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -20;
sun.shadow.camera.right = 20;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
sun.shadow.bias = -0.00025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x71d8ff, 1.2);
rimLight.position.set(12, 8, -12);
scene.add(rimLight);
const geometryCache = new Map();
const materialCache = new Map();
function boxGeometry(width, height, depth) {
const key = `${width}:${height}:${depth}`;
if (!geometryCache.has(key)) {
geometryCache.set(
key,
new THREE.BoxGeometry(width, height, depth)
);
}
return geometryCache.get(key);
}
function boxMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: color === 0xf4c95d ? 0.24 : 0.04
})
);
}
return materialCache.get(color);
}
function box(
width,
height,
depth,
color,
x = 0,
y = 0,
z = 0,
parent = scene
) {
const mesh = new THREE.Mesh(
boxGeometry(width, height, depth),
boxMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Ground and central exchange court.
box(30, 0.5, 23, 0x0c2027, 0, -0.31, 0);
const grid = new THREE.GridHelper(28, 28, 0x31505b, 0x203b45);
grid.position.y = -0.045;
grid.scale.z = 0.79;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
box(15.4, 0.08, 2.25, 0x163039, 0, 0.015, 0);
for (let z = -9; z <= 9; z += 3) {
box(0.28, 0.04, 0.28, 0x46636b, 0, 0.075, z);
}
box(5.2, 0.36, 3.85, 0x1a3038, 0, 0.12, 0);
box(4.65, 0.12, 3.3, 0x29434a, 0, 0.36, 0);
// Voxel arch around the common trade court.
box(0.48, 3.8, 0.48, 0x58717a, -2.25, 2.1, -1.45);
box(0.48, 3.8, 0.48, 0x58717a, 2.25, 2.1, -1.45);
box(5.05, 0.42, 0.62, 0x76909a, 0, 4.02, -1.45);
box(4.25, 0.2, 0.3, 0xe0b75c, 0, 3.69, -1.72);
// Small voxel lamps.
for (const z of [-7.8, 7.8]) {
for (const x of [-3.5, 3.5]) {
box(0.18, 2.6, 0.18, 0x435b63, x, 1.25, z);
box(0.7, 0.22, 0.7, 0xd2b35c, x, 2.6, z);
box(0.38, 0.45, 0.38, 0xffe3a0, x, 2.9, z);
}
}
function makeTree(x, z, leafColor) {
box(0.42, 1.7, 0.42, 0x74543e, x, 0.75, z);
box(1.45, 0.75, 1.45, leafColor, x, 1.65, z);
box(0.95, 0.65, 0.95, leafColor, x + 0.2, 2.25, z - 0.1);
}
makeTree(-12, -8.3, 0x2f6658);
makeTree(12, -8.1, 0x35655d);
makeTree(-12, 8.1, 0x2b5a55);
makeTree(12, 8.2, 0x376a5a);
// Distant decorative crates.
for (let i = 0; i < 7; i++) {
box(
0.65,
0.65,
0.65,
i % 2 ? 0x79563c : 0x4e6b5a,
-11 + i * 0.72,
0.32,
8.9 + (i % 2) * 0.12
);
}
const worldLabels = [];
function addWorldLabel(position, className, html) {
const outer = document.createElement("div");
outer.className = `world-label ${className}`;
const inner = document.createElement("div");
inner.innerHTML = html;
outer.appendChild(inner);
labelsContainer.appendChild(outer);
const label = {
outer,
inner,
position: position.clone()
};
worldLabels.push(label);
return label;
}
function buildStall(offer, index, side) {
const direction = side === "seller" ? -1 : 1;
const centerX = direction * 7.15;
const centerZ = (index - 1) * 5.3;
const group = new THREE.Group();
group.position.set(centerX, 0, centerZ);
scene.add(group);
const frameColor = side === "seller" ? 0x75503a : 0x315966;
const darkColor = side === "seller" ? 0x51382c : 0x23404b;
box(3.7, 0.3, 3.85, darkColor, 0, 0.1, 0, group);
box(2.95, 0.68, 2.55, frameColor, 0, 0.59, 0, group);
box(3.08, 0.13, 2.68, 0x8b9c96, 0, 0.985, 0, group);
// Back frame and awning, leaving the offer tokens unobstructed.
box(0.22, 2.85, 0.22, frameColor, -1.58, 1.75, -1.68, group);
box(0.22, 2.85, 0.22, frameColor, 1.58, 1.75, -1.68, group);
box(3.42, 0.25, 0.84, offer.color, 0, 3.55, -1.43, group);
box(2.85, 0.72, 0.18, 0x172a33, 0, 2.91, -1.7, group);
// Colored trim along the counter.
for (let i = 0; i < 5; i++) {
box(
0.52,
0.08,
0.12,
offer.color,
-1.04 + i * 0.52,
0.8,
1.3,
group
);
}
const label = addWorldLabel(
new THREE.Vector3(centerX, 4.17, centerZ - 1.55),
`party-label ${side}`,
`
<div class="label-role">
${side === "seller" ? "Seller · floor" : "Buyer · ceiling"}
${offer.price}c
</div>
<strong>${offer.name}</strong>
<div class="label-meta">
<span>${offer.qty} crates fixed</span>
<b class="remaining">${offer.qty} open</b>
</div>
`
);
return { centerX, centerZ, label };
}
function makeOfferToken(color) {
const group = new THREE.Group();
box(0.5, 0.36, 0.5, color, 0, 0.18, 0, group);
box(0.27, 0.14, 0.27, color, 0, 0.43, 0, group);
scene.add(group);
return group;
}
function placeOfferTokens(offer, index, side) {
const stall = buildStall(offer, index, side);
const targetArray = side === "seller" ? sellerUnits : buyerUnits;
const rows = Math.ceil(offer.qty / 4);
const columns = 4;
for (let i = 0; i < offer.qty; i++) {
const row = Math.floor(i / columns);
const column = i % columns;
const x =
stall.centerX +
(column - (columns - 1) / 2) * 0.59;
const z =
stall.centerZ +
(row - (rows - 1) / 2) * 0.59;
const token = makeOfferToken(offer.color);
token.position.set(x, 1.05, z);
token.userData.initialPosition = token.position.clone();
targetArray[index].push(token);
}
}
sellers.forEach((offer, index) =>
placeOfferTokens(offer, index, "seller")
);
buyers.forEach((offer, index) =>
placeOfferTokens(offer, index, "buyer")
);
const courtLabel = addWorldLabel(
new THREE.Vector3(0, 4.75, -1.48),
"court-label",
`
<strong>COMMON TRADE COURT</strong>
<span class="court-status">0 crates matched · compatibility only</span>
`
);
// One gold voxel is displayed for every matched crate.
const matchedCrates = [];
const goldSlots = [];
for (let i = 0; i < 26; i++) {
const column = i % 5;
const row = Math.floor(i / 5);
const target = new THREE.Vector3(
(column - 2) * 0.62,
0.66,
(row - 1) * 0.62
);
const gold = new THREE.Group();
box(0.48, 0.42, 0.48, 0xf4c95d, 0, 0, 0, gold);
box(0.25, 0.13, 0.25, 0xffe49a, 0, 0.275, 0, gold);
gold.position.copy(target);
gold.visible = false;
scene.add(gold);
goldSlots.push(target);
matchedCrates.push(gold);
}
const tweens = [];
function animatePair(sellerToken, buyerToken, gold, target, delay) {
const sellerStart = sellerToken.position.clone();
const buyerStart = buyerToken.position.clone();
const startTime = performance.now() + delay;
const duration = 1050;
tweens.push({
update(now) {
if (now < startTime) return true;
const t = Math.min((now - startTime) / duration, 1);
const eased = 1 - Math.pow(1 - t, 3);
const arc = Math.sin(Math.PI * eased);
sellerToken.position.lerpVectors(sellerStart, target, eased);
buyerToken.position.lerpVectors(buyerStart, target, eased);
sellerToken.position.y += arc * 2.35;
buyerToken.position.y += arc * 2.35;
// The two offer tokens separate slightly until they meet.
sellerToken.position.x -= (1 - eased) * 0.28;
buyerToken.position.x += (1 - eased) * 0.28;
const scale = 1 - eased * 0.18;
sellerToken.scale.setScalar(scale);
buyerToken.scale.setScalar(scale);
if (t >= 1) {
sellerToken.visible = false;
buyerToken.visible = false;
sellerToken.scale.setScalar(1);
buyerToken.scale.setScalar(1);
gold.visible = true;
gold.scale.setScalar(0.01);
const popStart = now;
tweens.push({
update(popNow) {
const p = Math.min((popNow - popStart) / 250, 1);
const c1 = 1.70158;
const c3 = c1 + 1;
const value =
1 +
c3 * Math.pow(p - 1, 3) +
c1 * Math.pow(p - 1, 2);
gold.scale.setScalar(Math.max(0.01, value));
return p < 1;
}
});
return false;
}
return true;
}
});
}
function computeMatches() {
const sellerPool = sellers.map((offer, index) => ({
index,
price: offer.price,
remaining: sellerRemaining[index]
}));
const buyerPool = buyers.map((offer, index) => ({
index,
price: offer.price,
remaining: buyerRemaining[index]
}));
const buyerOrder = [...buyerPool].sort(
(a, b) => b.price - a.price
);
const matches = [];
for (const buyer of buyerOrder) {
const sellerOrder = [...sellerPool].sort(
(a, b) => a.price - b.price
);
for (const seller of sellerOrder) {
if (buyer.remaining <= 0) break;
if (seller.remaining <= 0) continue;
// Incompatible prices are not forced into a trade.
if (buyer.price < seller.price) break;
const quantity = Math.min(
buyer.remaining,
seller.remaining
);
matches.push({
sellerIndex: seller.index,
buyerIndex: buyer.index,
quantity,
price: seller.price
});
buyer.remaining -= quantity;
seller.remaining -= quantity;
}
}
return matches;
}
function renderSchedule() {
const renderGroup = (offers, remaining, side) => {
const rows = offers.map((offer, index) => {
const rem = remaining[index];
const depleted = rem === 0;
let status;
if (rem === offer.qty) {
status = `${offer.qty} open`;
} else if (rem === 0) {
status = side === "seller" ? "all sold" : "all filled";
} else {
status = `${rem} remain`;
}
const priceLabel =
side === "seller"
? `MIN ${offer.price}c`
: `MAX ${offer.price}c`;
return `
<div class="schedule-row ${side} ${
depleted ? "depleted" : ""
}">
<div class="row-top">
<strong>${offer.name}</strong>
<span class="price-pill">${priceLabel}</span>
</div>
<div class="row-bottom">
<span>${offer.qty} crates fixed</span>
<span class="row-status">${status}</span>
</div>
</div>
`;
}).join("");
return `
<div class="schedule-group">
<div class="group-label">${
side === "seller"
? "Sellers · minimum reservation price"
: "Buyers · maximum reservation price"
}</div>
${rows}
</div>
`;
};
document.getElementById("schedule").innerHTML =
renderGroup(sellers, sellerRemaining, "seller") +
renderGroup(buyers, buyerRemaining, "buyer");
}
function renderTrades(settled = true) {
const tradesElement = document.getElementById("trades");
if (!currentMatches.length) {
tradesElement.innerHTML = `
<div class="empty">
No trades yet. Match compatible offers to move paired tokens
through the common court.
</div>
`;
return;
}
tradesElement.innerHTML = currentMatches
.map((trade) => {
const seller = sellers[trade.sellerIndex];
const buyer = buyers[trade.buyerIndex];
return `
<div class="trade-row">
<div>
<div class="trade-route">
${seller.name}<em>→</em>${buyer.name}
</div>
<div class="trade-detail">
${trade.quantity} crates ·
${settled ? "settled" : "settling…"}
</div>
</div>
<div class="trade-price">${trade.price}c</div>
</div>
`;
})
.join("");
}
function renderSummary() {
const matched = currentMatches.reduce(
(sum, trade) => sum + trade.quantity,
0
);
const sellerRemains = sellerRemaining.reduce(
(sum, quantity) => sum + quantity,
0
);
const buyerRemains = buyerRemaining.reduce(
(sum, quantity) => sum + quantity,
0
);
document.getElementById("mMatched").textContent = matched;
document.getElementById("mSeller").textContent = sellerRemains;
document.getElementById("mBuyer").textContent = buyerRemains;
document.getElementById("tradeCount").textContent =
`${currentMatches.length} trade${
currentMatches.length === 1 ? "" : "s"
}`;
courtLabel.inner.querySelector(".court-status").textContent =
`${matched} crates matched · ${
currentMatches.length
} compatible trades`;
}
function updateWorldLabelStates() {
sellers.forEach((offer, index) => {
const rem = sellerRemaining[index];
const status =
rem === offer.qty
? `${rem} open`
: rem === 0
? "all sold"
: `${rem} remain`;
const label = worldLabels.find(
(item) =>
item.inner.querySelector("strong")?.textContent ===
offer.name
);
if (label) {
label.inner.querySelector(".remaining").textContent = status;
}
});
buyers.forEach((offer, index) => {
const rem = buyerRemaining[index];
const status =
rem === offer.qty
? `${rem} open`
: rem === 0
? "all filled"
: `${rem} remain`;
const label = worldLabels.find(
(item) =>
item.inner.querySelector("strong")?.textContent ===
offer.name
);
if (label) {
label.inner.querySelector(".remaining").textContent = status;
}
});
}
const matchButton = document.getElementById("matchButton");
const resetMarketButton = document.getElementById("resetMarket");
matchButton.addEventListener("click", () => {
if (marketState !== "ready") return;
marketState = "matching";
matchButton.disabled = true;
matchButton.textContent = "Matching…";
const thisRun = ++runId;
currentMatches = computeMatches();
const sellerTaken = sellers.map(() => 0);
const buyerTaken = buyers.map(() => 0);
let crateIndex = 0;
// Reserve the unmatched quantities before beginning the animation.
for (const trade of currentMatches) {
sellerRemaining[trade.sellerIndex] -= trade.quantity;
buyerRemaining[trade.buyerIndex] -= trade.quantity;
}
for (const trade of currentMatches) {
for (let i = 0; i < trade.quantity; i++) {
const sellerToken =
sellerUnits[trade.sellerIndex][
sellerTaken[trade.sellerIndex]++
];
const buyerToken =
buyerUnits[trade.buyerIndex][
buyerTaken[trade.buyerIndex]++
];
animatePair(
sellerToken,
buyerToken,
matchedCrates[crateIndex],
goldSlots[crateIndex],
crateIndex * 95
);
crateIndex++;
}
}
renderSchedule();
renderSummary();
updateWorldLabelStates();
renderTrades(false);
const totalDuration = crateIndex * 95 + 1350;
window.setTimeout(() => {
if (thisRun !== runId) return;
marketState = "matched";
matchButton.textContent = "Trades matched";
renderTrades(true);
}, totalDuration);
});
function resetMarket() {
runId++;
marketState = "ready";
currentMatches = [];
tweens.length = 0;
sellerRemaining.splice(
0,
sellerRemaining.length,
...sellers.map((offer) => offer.qty)
);
buyerRemaining.splice(
0,
buyerRemaining.length,
...buyers.map((offer) => offer.qty)
);
sellerUnits.forEach((units) => {
units.forEach((token) => {
token.visible = true;
token.position.copy(token.userData.initialPosition);
token.scale.setScalar(1);
});
});
buyerUnits.forEach((units) => {
units.forEach((token) => {
token.visible = true;
token.position.copy(token.userData.initialPosition);
token.scale.setScalar(1);
});
});
matchedCrates.forEach((gold) => {
gold.visible = false;
gold.scale.setScalar(1);
});
matchButton.disabled = false;
matchButton.textContent = "Match compatible trades";
renderSchedule();
renderSummary();
updateWorldLabelStates();
renderTrades(true);
}
resetMarketButton.addEventListener("click", resetMarket);
// Direct orbit controls, implemented without Three.js add-ons.
const orbit = {
theta: 0.38,
phi: 1.03,
radius: 29,
target: new THREE.Vector3(0, 1, 0)
};
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
orbit.theta -= deltaX * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - deltaY * 0.005,
0.55,
1.36
);
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.018,
17,
43
);
},
{ passive: false }
);
document.getElementById("resetView").addEventListener("click", () => {
orbit.theta = 0.38;
orbit.phi = 1.03;
orbit.radius = 29;
});
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);
}
function updateWorldLabels() {
const width = stage.clientWidth;
const height = stage.clientHeight;
for (const label of worldLabels) {
const projected = label.position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
label.outer.style.opacity = visible ? "1" : "0";
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
label.outer.style.transform =
`translate3d(${x}px, ${y}px, 0)`;
}
}
const resizeObserver = new ResizeObserver(() => {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
resizeObserver.observe(stage);
function animate(now) {
requestAnimationFrame(animate);
for (let i = tweens.length - 1; i >= 0; i--) {
if (!tweens[i].update(now)) {
tweens.splice(i, 1);
}
}
updateCamera();
renderer.render(scene, camera);
updateWorldLabels();
}
renderSchedule();
renderSummary();
updateWorldLabelStates();
renderTrades(true);
requestAnimationFrame(animate);
loading.remove();
</script>
</body>
</html>
```