Prompt specification
Build or customize the Three.js 3D scene "Harvest Shock in a Fictional Market" 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: Harvest Shock in a Fictional Market
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/harvest-shock-in-a-fictional-market-x3143
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring supply and demand schedules in a fictional market. Build a produce market with a stated supply schedule and unchanged demand schedule. Reduce available harvest and recalculate transactions only through the declared matching rules. Voxel style.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Apply the 30% supply reduction while keeping demand fixed. Compute trades from available supply and orders, and keep unsold stock nonnegative and consistent with trades.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (harvest-shock-in-a-fictional-market-x3143):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fictional Voxel Produce Exchange</title>
<style>
:root {
--ink: #17252e;
--muted: #61727c;
--paper: #f5f0e4;
--panel: #fffaf0;
--line: #d8d1c1;
--green: #287d5c;
--orange: #d97532;
--blue: #326b91;
--red: #b84f45;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
min-height: 100%;
background: #c6dce2;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
body { overflow: hidden; }
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 410px;
width: 100vw;
height: 100vh;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #c6dce2;
}
#viewport canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas.dragging { cursor: grabbing; }
#scene-hud {
position: absolute;
z-index: 3;
top: 16px;
left: 16px;
max-width: min(420px, calc(100% - 32px));
pointer-events: none;
}
.scene-badge,
.scene-help {
display: inline-block;
padding: 9px 12px;
border: 2px solid var(--ink);
background: rgba(255, 250, 240, 0.92);
box-shadow: 4px 4px 0 rgba(23, 37, 46, 0.16);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
line-height: 1.5;
}
.scene-help {
display: block;
margin-top: 8px;
color: #40515b;
font-weight: 700;
letter-spacing: 0.035em;
}
aside {
position: relative;
z-index: 5;
height: 100vh;
overflow-y: auto;
padding: 18px 18px 28px;
border-left: 3px solid var(--ink);
background:
linear-gradient(rgba(23, 37, 46, 0.035) 1px, transparent 1px),
var(--panel);
background-size: 100% 24px;
}
h1 {
margin: 0;
font-size: 22px;
line-height: 1.12;
letter-spacing: -0.045em;
}
.subtitle {
margin: 8px 0 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.synthetic {
display: inline-block;
margin-bottom: 14px;
padding: 5px 8px;
border: 2px solid var(--ink);
background: #f2c14e;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
}
.controls {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-bottom: 16px;
}
button {
min-height: 42px;
border: 2px solid var(--ink);
border-radius: 0;
padding: 9px 12px;
background: var(--green);
color: white;
font: inherit;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.035em;
cursor: pointer;
box-shadow: 3px 3px 0 var(--ink);
}
button:hover:not(:disabled) { transform: translate(-1px, -1px); }
button:active:not(:disabled) { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--ink); }
button:disabled { cursor: default; opacity: 0.45; box-shadow: none; }
button.secondary {
min-width: 92px;
background: #e9e2d3;
color: var(--ink);
}
section {
margin-top: 14px;
padding-top: 13px;
border-top: 2px solid var(--ink);
}
.section-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.pill {
padding: 3px 6px;
border: 1px solid var(--ink);
background: #e4eee5;
font-size: 9px;
font-weight: 900;
white-space: nowrap;
}
.pill.orange { background: #f6d29d; }
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th {
padding: 5px 4px;
border-bottom: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
text-align: right;
text-transform: uppercase;
}
th:first-child, td:first-child { text-align: left; }
td {
padding: 6px 4px;
border-bottom: 1px solid #e8e2d5;
text-align: right;
white-space: nowrap;
}
td.emphasis { font-weight: 900; }
.unchanged { color: var(--green); font-weight: 900; }
.rules {
margin: 0;
padding: 10px 11px 10px 27px;
border: 1px solid #bfb7a7;
background: rgba(233, 226, 211, 0.6);
font-size: 10px;
line-height: 1.62;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 76px;
padding: 10px;
border: 2px solid var(--ink);
background: #fffdf7;
}
.metric .name {
min-height: 24px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
line-height: 1.3;
}
.metric .value {
margin-top: 4px;
font-size: 26px;
font-weight: 900;
line-height: 1;
letter-spacing: -0.06em;
}
.metric .note {
margin-top: 4px;
color: var(--muted);
font-size: 8px;
}
.metric.available .value { color: var(--orange); }
.metric.matched .value { color: var(--green); }
.audit {
margin-top: 9px;
padding: 10px;
border: 2px solid var(--green);
background: #e4f0e5;
font-size: 10px;
font-weight: 800;
line-height: 1.6;
}
.state-note {
margin-top: 8px;
color: #4d5e67;
font-size: 10px;
line-height: 1.58;
}
details {
margin-top: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.38);
}
summary {
padding: 8px 9px;
cursor: pointer;
font-size: 10px;
font-weight: 900;
}
details table { padding: 0 7px 7px; }
.footnote {
margin-top: 18px;
color: var(--muted);
font-size: 9px;
line-height: 1.55;
}
@media (max-width: 900px) {
body { overflow: auto; }
#app {
grid-template-columns: 1fr;
grid-template-rows: 58vh auto;
height: auto;
}
#viewport { min-height: 430px; }
aside {
height: auto;
border-left: 0;
border-top: 3px solid var(--ink);
}
}
</style>
</head>
<body>
<main id="app">
<div id="viewport">
<div id="scene-hud">
<div class="scene-badge">FICTIONAL MARKET · SYNTHETIC SCHEDULE</div>
<div class="scene-help">DRAG TO ORBIT · WHEEL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
</div>
</div>
<aside>
<h1>Voxel Produce Exchange</h1>
<p class="subtitle">
A deliberately synthetic market for testing a harvest reduction and a
deterministic supply–demand match. All names, quantities, and prices are fictional.
</p>
<div class="synthetic">SCHEMATIC DATA · NOT A REAL MARKET</div>
<div class="controls">
<button id="reduce" type="button">REDUCE HARVEST BY 30%</button>
<button id="reset" class="secondary" type="button">RESET</button>
</div>
<section>
<div class="section-head">
<h2>Supply schedule</h2>
<span id="supply-state" class="pill">BASE HARVEST</span>
</div>
<table>
<thead>
<tr>
<th>Producer</th>
<th>Ask</th>
<th>Initial</th>
<th>Current</th>
</tr>
</thead>
<tbody id="supply-rows"></tbody>
</table>
</section>
<section>
<div class="section-head">
<h2>Demand schedule</h2>
<span class="pill">UNCHANGED · 230 UNITS</span>
</div>
<table>
<thead>
<tr>
<th>Buyer</th>
<th>Limit</th>
<th>Demand</th>
<th>Current</th>
</tr>
</thead>
<tbody id="demand-rows"></tbody>
</table>
</section>
<section>
<div class="section-head">
<h2>Declared matching rules</h2>
</div>
<ol class="rules">
<li>Process buyers by descending price limit.</li>
<li>Process sellers by ascending ask price.</li>
<li>Match only when buyer limit is at least seller ask.</li>
<li>Trade the smaller remaining quantity.</li>
<li>Transaction price equals the seller’s ask.</li>
</ol>
</section>
<section>
<div class="section-head">
<h2>Current result</h2>
<span id="result-state" class="pill">INITIAL MATCH</span>
</div>
<div class="metrics">
<div class="metric">
<div class="name">HARVEST OFFERED</div>
<div id="metric-offered" class="value">270</div>
<div class="note">CURRENT SUPPLY</div>
</div>
<div class="metric matched">
<div class="name">MATCHED UNITS</div>
<div id="metric-matched" class="value">210</div>
<div class="note">TRADES EXECUTED</div>
</div>
<div class="metric available">
<div class="name">UNSOLD / AVAILABLE</div>
<div id="metric-unsold" class="value">60</div>
<div class="note">REMAINING STOCK</div>
</div>
<div class="metric">
<div class="name">UNMET DEMAND</div>
<div id="metric-unmet" class="value">20</div>
<div class="note">UNFILLED ORDERS</div>
</div>
</div>
<div id="audit" class="audit"></div>
<div id="state-note" class="state-note"></div>
</section>
<section>
<div class="section-head">
<h2>Initial versus current</h2>
</div>
<table>
<thead>
<tr>
<th>Counter</th>
<th>Initial</th>
<th>Current</th>
</tr>
</thead>
<tbody id="comparison-rows"></tbody>
</table>
</section>
<section>
<div class="section-head">
<h2>Matched pair quantities</h2>
</div>
<details open>
<summary>Show all buyer–seller pairs</summary>
<table>
<thead>
<tr>
<th>Buyer / Seller</th>
<th>Initial</th>
<th>Current</th>
</tr>
</thead>
<tbody id="transaction-rows"></tbody>
</table>
</details>
</section>
<p class="footnote">
“Unsold / available” is the nonnegative supply remaining after matching.
It is never computed as demand minus sales. The scene’s crate stacks and
trade pillars use the same values shown in the data tables.
</p>
</aside>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const reduceButton = document.getElementById("reduce");
const resetButton = document.getElementById("reset");
const SUPPLY = [
{ id: "S1", name: "Orchard A", ask: 1, initial: 120, color: 0x4f9d58 },
{ id: "S2", name: "Orchard B", ask: 2, initial: 90, color: 0xe18a3a },
{ id: "S3", name: "Orchard C", ask: 3, initial: 60, color: 0xc65345 }
];
const DEMAND = [
{ id: "D1", name: "Canteen", limit: 4, qty: 90, color: 0x347ba5 },
{ id: "D2", name: "Corner Grocer", limit: 3, qty: 80, color: 0x7564a6 },
{ id: "D3", name: "School Kitchen", limit: 2, qty: 60, color: 0xd0a12e }
];
const INITIAL_RESULT = null;
let currentResult = null;
let currentReduced = false;
function runMatching(supplyQuantities) {
const sellers = SUPPLY.map((seller, index) => ({
...seller,
qty: supplyQuantities[index],
remaining: supplyQuantities[index],
sourceIndex: index
}));
const buyers = DEMAND.map((buyer, index) => ({
...buyer,
remaining: buyer.qty,
sourceIndex: index
}));
const trades = [];
for (const buyer of buyers.sort((a, b) => b.limit - a.limit)) {
for (const seller of sellers.sort((a, b) => a.ask - b.ask)) {
if (buyer.remaining <= 0) break;
if (seller.remaining <= 0) continue;
if (buyer.limit < seller.ask) continue;
const quantity = Math.min(buyer.remaining, seller.remaining);
buyer.remaining -= quantity;
seller.remaining -= quantity;
trades.push({
buyerId: buyer.id,
buyerName: buyer.name,
buyerLimit: buyer.limit,
sellerId: seller.id,
sellerName: seller.name,
sellerAsk: seller.ask,
price: seller.ask,
quantity
});
}
}
const matched = trades.reduce((sum, trade) => sum + trade.quantity, 0);
const available = sellers.reduce((sum, seller) => sum + seller.remaining, 0);
const unmet = buyers.reduce((sum, buyer) => sum + buyer.remaining, 0);
const offered = supplyQuantities.reduce((sum, quantity) => sum + quantity, 0);
const demanded = DEMAND.reduce((sum, buyer) => sum + buyer.qty, 0);
if (matched + available !== offered) {
throw new Error("Supply accounting failed.");
}
if (matched + unmet !== demanded) {
throw new Error("Demand accounting failed.");
}
if ([matched, available, unmet].some(value => value < 0)) {
throw new Error("A market counter became negative.");
}
return { trades, matched, available, unmet, offered, demanded, sellers, buyers };
}
function quantitiesFor(reduced) {
return SUPPLY.map(seller =>
reduced ? Math.round(seller.initial * 0.70) : seller.initial
);
}
function pairQuantity(result, buyerId, sellerId) {
return result.trades
.filter(trade => trade.buyerId === buyerId && trade.sellerId === sellerId)
.reduce((sum, trade) => sum + trade.quantity, 0);
}
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xc6dce2);
scene.fog = new THREE.Fog(0xc6dce2, 31, 57);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.id = "market-canvas";
renderer.domElement.setAttribute("aria-label", "Interactive voxel produce market");
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf6fbff, 0x8b795d, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d8, 3.0);
sun.position.set(-12, 21, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9dc9e8, 0.65);
fill.position.set(14, 8, -12);
scene.add(fill);
function addBox(parent, width, height, depth, color, x = 0, y = 0, z = 0, options = {}) {
const material = new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.82,
metalness: options.metalness ?? 0,
flatShading: true,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
});
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function disposeGroup(group) {
while (group.children.length) {
const child = group.children.pop();
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material) ? object.material : [object.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
}
}
function makeLabel(text, options = {}) {
const lines = text.split("\n");
const font = `800 ${options.fontSize || 30}px ui-monospace, SFMono-Regular, Menlo, monospace`;
const probe = document.createElement("canvas").getContext("2d");
probe.font = font;
const widest = Math.max(...lines.map(line => probe.measureText(line).width));
const width = Math.max(160, Math.min(900, Math.ceil(widest + 42)));
const height = 28 + lines.length * 42;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
context.fillStyle = options.background || "#17252e";
context.fillRect(0, 0, width, height);
context.fillStyle = options.accent || "#f2c14e";
context.fillRect(5, 5, width - 10, 6);
context.strokeStyle = options.border || "#f7f0df";
context.lineWidth = 4;
context.strokeRect(3, 3, width - 6, height - 6);
context.font = font;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = options.color || "#fffaf0";
lines.forEach((line, index) => {
context.fillText(line, width / 2, 35 + index * 42);
});
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
const worldWidth = options.worldWidth || 2.5;
sprite.scale.set(worldWidth, worldWidth * height / width, 1);
sprite.renderOrder = 30;
return sprite;
}
const market = new THREE.Group();
scene.add(market);
addBox(market, 24, 0.72, 15, 0x8b7657, 0, -0.42, 0);
const tileColors = [0xb9c79e, 0xc2cfa7, 0xb3c399, 0xc8d2ad];
for (let ix = 0; ix < 16; ix++) {
for (let iz = 0; iz < 10; iz++) {
const color = tileColors[(ix + iz * 2) % tileColors.length];
addBox(
market,
1.46,
0.08,
1.46,
color,
-11.25 + ix * 1.5,
0.04,
-6.75 + iz * 1.5,
{ castShadow: false }
);
}
}
addBox(market, 4.45, 0.12, 13.35, 0x667275, 0, 0.13, 0);
for (let z = -6; z <= 6; z += 1.35) {
addBox(market, 0.12, 0.025, 0.62, 0xf2c14e, -2.02, 0.205, z, { castShadow: false });
addBox(market, 0.12, 0.025, 0.62, 0xf2c14e, 2.02, 0.205, z, { castShadow: false });
}
function buildStall(x, z, roofColor, accentColor, orientation) {
const group = new THREE.Group();
group.position.set(x, 0, z);
market.add(group);
addBox(group, 3.0, 0.16, 2.75, 0x6d5941, 0, 0.16, 0);
addBox(group, 0.18, 2.45, 0.18, 0x59483a, -1.25, 1.38, -1.05);
addBox(group, 0.18, 2.45, 0.18, 0x59483a, 1.25, 1.38, -1.05);
addBox(group, 0.18, 2.45, 0.18, 0x59483a, -1.25, 1.38, 1.05);
addBox(group, 0.18, 2.45, 0.18, 0x59483a, 1.25, 1.38, 1.05);
for (let strip = 0; strip < 6; strip++) {
const color = strip % 2 === 0 ? roofColor : accentColor;
addBox(group, 3.12, 0.25, 0.47, color, 0, 2.68, -1.18 + strip * 0.47);
}
const counterX = orientation === "supply" ? 1.28 : -1.28;
addBox(group, 0.55, 0.72, 2.35, 0x8e6847, counterX, 0.62, 0);
addBox(group, 0.7, 0.12, 2.48, 0xc6925e, counterX, 1.02, 0);
return group;
}
const sellerZ = [-4.1, 0, 4.1];
const buyerZ = [-4.1, 0, 4.1];
const sellerX = -7.45;
const buyerX = 7.45;
SUPPLY.forEach((seller, index) => {
buildStall(sellerX, sellerZ[index], seller.color, 0xf0d8a2, "supply");
});
DEMAND.forEach((buyer, index) => {
buildStall(buyerX, buyerZ[index], buyer.color, 0xe8ddc6, "demand");
});
function buildTree(x, z, color) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
market.add(tree);
addBox(tree, 0.48, 1.65, 0.48, 0x765039, 0, 0.82, 0);
addBox(tree, 1.7, 0.9, 1.45, color, 0, 2.05, 0);
addBox(tree, 1.15, 0.85, 1.15, color, -0.55, 2.72, 0.12);
addBox(tree, 1.05, 0.75, 1.05, color, 0.58, 2.62, -0.08);
}
buildTree(-10.65, -5.55, 0x497c53);
buildTree(-10.5, 5.55, 0x5e8c58);
buildTree(10.55, -5.5, 0x4d8058);
buildTree(10.6, 5.55, 0x5c8c58);
for (let i = 0; i < 7; i++) {
addBox(market, 0.55, 0.55, 0.55, i % 2 ? 0xd5b26c : 0x7f9a66, -3.25, 0.31, -5.2 + i * 1.72);
}
for (let i = 0; i < 7; i++) {
addBox(market, 0.55, 0.55, 0.55, i % 2 ? 0xc59c62 : 0x799064, 3.25, 0.31, -5.2 + i * 1.72);
}
const staticLabels = new THREE.Group();
scene.add(staticLabels);
const titleLabel = makeLabel("CLEARED TRADES · SCHEMATIC\n1 VOXEL BLOCK = 10 UNITS", {
background: "#243842",
accent: "#f2c14e",
worldWidth: 4.8
});
titleLabel.position.set(0, 3.65, -6.25);
staticLabels.add(titleLabel);
const columnX = [-1.45, 0, 1.45];
const rowZ = [-3.25, 0, 3.25];
SUPPLY.forEach((seller, index) => {
const label = makeLabel(`${seller.id} SELLER`, {
background: "#33483f",
accent: "#87c78c",
worldWidth: 1.8,
fontSize: 27
});
label.position.set(columnX[index], 0.48, -4.75);
staticLabels.add(label);
});
DEMAND.forEach((buyer, index) => {
const label = makeLabel(`${buyer.id}`, {
background: "#344b5a",
accent: "#7fc0e3",
worldWidth: 1.0,
fontSize: 28
});
label.position.set(-2.62, 0.48, rowZ[index]);
staticLabels.add(label);
});
const supplyVisuals = new THREE.Group();
const demandVisuals = new THREE.Group();
const tradeVisuals = new THREE.Group();
scene.add(supplyVisuals, demandVisuals, tradeVisuals);
function addProduceCrate(parent, x, z, color, heightScale = 1) {
const bodyHeight = 0.34 * heightScale;
const baseY = 0.13;
addBox(parent, 0.50, bodyHeight, 0.50, 0x9a7048, x, baseY + bodyHeight / 2, z);
const topColor = new THREE.Color(color)
.lerp(new THREE.Color(0xffe58e), 0.42)
.getHex();
const topHeight = Math.min(0.075, bodyHeight * 0.42);
addBox(
parent,
0.39,
topHeight,
0.39,
topColor,
x,
baseY + bodyHeight + topHeight / 2,
z
);
}
function buildSupplyVisuals(result, reduced) {
disposeGroup(supplyVisuals);
SUPPLY.forEach((seller, index) => {
const quantity = result.sellers[index].remaining;
const full = Math.floor(quantity / 10);
const remainder = quantity % 10;
const originX = -5.18;
const originZ = sellerZ[index];
for (let i = 0; i < full; i++) {
const x = originX - Math.floor(i / 4) * 0.61;
const z = originZ + ((i % 4) - 1.5) * 0.61;
addProduceCrate(supplyVisuals, x, z, seller.color, 1);
}
if (remainder > 0) {
const i = full;
const x = originX - Math.floor(i / 4) * 0.61;
const z = originZ + ((i % 4) - 1.5) * 0.61;
addProduceCrate(supplyVisuals, x, z, seller.color, remainder / 10);
}
const stateText = reduced ? "30% HARVEST CUT" : "BASE HARVEST";
const label = makeLabel(
`${seller.id} · ${seller.name}\nASK $${seller.ask} · ${quantity} u\n${stateText}`,
{
background: "#263a32",
accent: "#8ed18b",
worldWidth: 3.0
}
);
label.position.set(sellerX, 3.55, sellerZ[index]);
supplyVisuals.add(label);
});
}
function buildDemandVisuals() {
disposeGroup(demandVisuals);
DEMAND.forEach((buyer, index) => {
const full = Math.floor(buyer.qty / 10);
const remainder = buyer.qty % 10;
const originX = 5.2;
const originZ = buyerZ[index];
for (let i = 0; i < full; i++) {
const x = originX + Math.floor(i / 3) * 0.58;
const z = originZ + ((i % 3) - 1) * 0.58;
addBox(demandVisuals, 0.46, 0.31, 0.46, buyer.color, x, 1.25, z);
addBox(demandVisuals, 0.34, 0.06, 0.34, 0xe8eef0, x, 1.435, z);
}
if (remainder > 0) {
const i = full;
const x = originX + Math.floor(i / 3) * 0.58;
const z = originZ + ((i % 3) - 1) * 0.58;
addBox(demandVisuals, 0.46, 0.31 * remainder / 10, 0.46, buyer.color, x, 1.25, z);
}
const label = makeLabel(
`${buyer.id} · ${buyer.name}\nLIMIT $${buyer.limit} · ${buyer.qty} u\nSCHEMATIC DEMAND`,
{
background: "#293d49",
accent: "#86c5e5",
worldWidth: 3.05
}
);
label.position.set(buyerX, 3.55, buyerZ[index]);
demandVisuals.add(label);
});
}
function buildTradeVisuals(result) {
disposeGroup(tradeVisuals);
for (let row = 0; row < DEMAND.length; row++) {
for (let col = 0; col < SUPPLY.length; col++) {
const x = columnX[col];
const z = rowZ[row];
addBox(tradeVisuals, 1.18, 0.07, 1.18, 0x879092, x, 0.235, z, { castShadow: false });
const trade = result.trades.find(item =>
item.buyerId === DEMAND[row].id && item.sellerId === SUPPLY[col].id
);
if (!trade || trade.quantity <= 0) continue;
const full = Math.floor(trade.quantity / 10);
const remainder = trade.quantity % 10;
const blockHeight = 0.20;
const step = 0.215;
const seller = SUPPLY[col];
for (let block = 0; block < full; block++) {
addBox(
tradeVisuals,
0.80,
blockHeight,
0.80,
seller.color,
x,
0.36 + block * step + blockHeight / 2,
z
);
}
if (remainder > 0) {
const height = blockHeight * remainder / 10;
addBox(
tradeVisuals,
0.80,
height,
0.80,
seller.color,
x,
0.36 + full * step + height / 2,
z
);
}
const label = makeLabel(
`${trade.quantity} u @ $${trade.price}\nMATCHED`,
{
background: "#26343b",
accent: "#f2c14e",
worldWidth: 1.48,
fontSize: 26
}
);
const stackHeight = full * step + (remainder ? remainder / 10 * blockHeight : 0);
label.position.set(x, 0.43 + stackHeight + 0.36, z);
tradeVisuals.add(label);
}
}
}
function renderTables(result, reduced) {
const quantities = quantitiesFor(reduced);
document.getElementById("supply-rows").innerHTML = SUPPLY.map((seller, index) => `
<tr>
<td><strong>${seller.id}</strong> ${seller.name}</td>
<td>$${seller.ask}</td>
<td>${seller.initial}</td>
<td class="emphasis ${reduced ? "unchanged" : ""}">${quantities[index]}</td>
</tr>
`).join("");
document.getElementById("demand-rows").innerHTML = DEMAND.map(buyer => `
<tr>
<td><strong>${buyer.id}</strong> ${buyer.name}</td>
<td>$${buyer.limit}</td>
<td>${buyer.qty}</td>
<td class="emphasis unchanged">${buyer.qty}</td>
</tr>
`).join("");
document.getElementById("metric-offered").textContent = result.offered;
document.getElementById("metric-matched").textContent = result.matched;
document.getElementById("metric-unsold").textContent = result.available;
document.getElementById("metric-unmet").textContent = result.unmet;
document.getElementById("supply-state").textContent =
reduced ? "30% CUT APPLIED" : "BASE HARVEST";
document.getElementById("supply-state").className = reduced ? "pill orange" : "pill";
document.getElementById("result-state").textContent =
reduced ? "REDUCED MATCH" : "INITIAL MATCH";
document.getElementById("audit").innerHTML = `
ACCOUNTING CHECK<br>
${result.matched} matched + ${result.available} unsold = ${result.offered} supplied<br>
${result.matched} matched + ${result.unmet} unmet = ${result.demanded} demanded
`;
document.getElementById("state-note").textContent = reduced
? "Harvest only was reduced: 120→84, 90→63, and 60→42 units. The demand schedule remains 90, 80, and 60 units. Matching was rerun from the beginning using the declared rules."
: "Initial state: all supply and demand quantities use their stated schedules. Matching is complete, and both accounting identities hold.";
const initial = runMatching(quantitiesFor(false));
const comparison = [
["Harvest offered", initial.offered, result.offered],
["Matched units", initial.matched, result.matched],
["Unsold / available", initial.available, result.available],
["Unmet demand", initial.unmet, result.unmet]
];
document.getElementById("comparison-rows").innerHTML = comparison.map(row => `
<tr>
<td>${row[0]}</td>
<td>${row[1]}</td>
<td class="emphasis">${row[2]}</td>
</tr>
`).join("");
document.getElementById("transaction-rows").innerHTML = DEMAND.map(buyer => {
return SUPPLY.map(seller => {
const initialQuantity = pairQuantity(initial, buyer.id, seller.id);
const currentQuantity = pairQuantity(result, buyer.id, seller.id);
return `
<tr>
<td>${buyer.id} ← ${seller.id} · $${seller.ask}</td>
<td>${initialQuantity}</td>
<td class="emphasis">${currentQuantity}</td>
</tr>
`;
}).join("");
}).join("");
reduceButton.disabled = reduced;
resetButton.disabled = !reduced;
}
function applyMarketState(reduced) {
currentReduced = reduced;
currentResult = runMatching(quantitiesFor(reduced));
renderTables(currentResult, reduced);
buildSupplyVisuals(currentResult, reduced);
buildTradeVisuals(currentResult);
}
reduceButton.addEventListener("click", () => {
if (!currentReduced) applyMarketState(true);
});
resetButton.addEventListener("click", () => {
if (currentReduced) applyMarketState(false);
});
// Direct camera controls: no addons, pointer lock, or external controller.
const controls = {
theta: 0.60,
phi: 0.76,
zoomFactor: 1,
fitRadius: 28,
target: new THREE.Vector3(0, 1.0, 0),
dragging: false,
lastX: 0,
lastY: 0
};
function updateCamera() {
const radius = controls.fitRadius * controls.zoomFactor;
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x + radius * sinPhi * Math.sin(controls.theta),
controls.target.y + radius * Math.cos(controls.phi),
controls.target.z + radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
}
renderer.domElement.addEventListener("pointerdown", event => {
controls.dragging = true;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
renderer.domElement.classList.add("dragging");
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!controls.dragging) return;
const deltaX = event.clientX - controls.lastX;
const deltaY = event.clientY - controls.lastY;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
controls.theta -= deltaX * 0.006;
controls.phi = THREE.MathUtils.clamp(controls.phi - deltaY * 0.005, 0.35, 1.25);
updateCamera();
});
function stopDragging(event) {
controls.dragging = false;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
controls.zoomFactor = THREE.MathUtils.clamp(
controls.zoomFactor * Math.exp(event.deltaY * 0.001),
0.56,
1.8
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
controls.theta = 0.60;
controls.phi = 0.76;
controls.zoomFactor = 1;
updateCamera();
});
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
const halfVertical = Math.tan(THREE.MathUtils.degToRad(camera.fov * 0.5));
controls.fitRadius = Math.max(
28,
8.8 / halfVertical,
13.4 / (halfVertical * camera.aspect)
);
updateCamera();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
buildDemandVisuals();
applyMarketState(false);
resize();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```