Prompt specification
Build or customize the Three.js 3D scene "Counting invariant puzzle" 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: Counting invariant puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/counting-invariant-puzzle-x1708
Scene Description Prompt:
Please make a voxel Three.js scene in one standalone HTML file using cdnjs. Let users move, group, add, or remove toy objects; distinguish layout changes from quantity changes and provide a visible one-to-one mapping that verifies the total.
Working Three.js Starter (counting-invariant-puzzle-x1708):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Toy Yard — Layout & Quantity Audit</title>
<style>
:root {
--ink: #172033;
--muted: #68738a;
--panel: rgba(250, 252, 255, 0.92);
--line: #dce3ed;
--accent: #6d5dfc;
--accent-dark: #5141d7;
--green: #14966f;
--green-bg: #e4f8f0;
--red: #d84b5b;
--orange: #e98920;
--shadow: 0 18px 45px rgba(30, 43, 70, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dce9f2;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 20;
top: 14px;
left: 16px;
right: 16px;
height: 58px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 0 17px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 17px;
background: rgba(255, 255, 255, 0.88);
box-shadow: 0 10px 30px rgba(30, 43, 70, 0.12);
backdrop-filter: blur(16px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 35px;
height: 35px;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
display: block;
width: 13px;
height: 13px;
border-radius: 3px;
background: var(--accent);
box-shadow: inset -3px -3px 0 rgba(0, 0, 0, 0.12);
}
.brand-mark i:nth-child(1) { left: 1px; top: 1px; }
.brand-mark i:nth-child(2) { right: 1px; top: 1px; background: #f59e0b; }
.brand-mark i:nth-child(3) { left: 1px; bottom: 1px; background: #ef5da8; }
.brand-mark i:nth-child(4) {
right: 1px;
bottom: 1px;
background: #16b69b;
}
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.1;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
}
.global-status {
display: flex;
align-items: center;
gap: 9px;
padding: 8px 12px;
border: 1px solid #bce8d8;
border-radius: 999px;
color: #0c7556;
background: var(--green-bg);
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
.global-status::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: #19aa7e;
box-shadow: 0 0 0 4px rgba(25, 170, 126, 0.12);
}
.global-status.bad {
color: #a42f42;
border-color: #f0b7c0;
background: #fff0f2;
}
.global-status.bad::before {
background: var(--red);
box-shadow: 0 0 0 4px rgba(216, 75, 91, 0.12);
}
.panel {
position: fixed;
z-index: 15;
border: 1px solid rgba(255, 255, 255, 0.76);
border-radius: 19px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
.shelf {
top: 86px;
left: 18px;
width: 236px;
padding: 16px;
}
.audit {
top: 86px;
right: 18px;
bottom: 52px;
width: 388px;
padding: 16px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #c7cfdd transparent;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 0 0 5px;
font-size: 14px;
letter-spacing: 0.02em;
}
.subtle {
margin: 0 0 13px;
color: var(--muted);
font-size: 11.5px;
line-height: 1.45;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.palette {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.toy-button {
position: relative;
min-height: 66px;
display: flex;
align-items: center;
gap: 9px;
padding: 10px 9px;
border: 1px solid var(--line);
border-radius: 12px;
color: var(--ink);
background: #fff;
cursor: pointer;
text-align: left;
transition: transform 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
}
.toy-button:hover {
transform: translateY(-2px);
border-color: #bcb5ff;
box-shadow: 0 7px 18px rgba(83, 70, 190, 0.1);
}
.toy-button:active {
transform: translateY(0);
}
.toy-button b {
display: block;
font-size: 11.5px;
line-height: 1.2;
}
.toy-button small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.toy-button .plus {
position: absolute;
right: 7px;
top: 5px;
color: var(--accent);
font-size: 16px;
font-weight: 800;
}
.mini-toy {
position: relative;
width: 27px;
height: 27px;
flex: 0 0 auto;
border-radius: 5px;
background: var(--toy);
box-shadow:
inset -5px -5px 0 rgba(0, 0, 0, 0.12),
5px -5px 0 color-mix(in srgb, var(--toy), white 30%);
}
.mini-toy::after {
content: "";
position: absolute;
width: 7px;
height: 7px;
left: 5px;
top: 5px;
border-radius: 2px;
background: #fff;
opacity: 0.8;
}
.divider {
height: 1px;
margin: 15px 0;
background: var(--line);
}
.selection-summary {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
font-size: 12px;
}
.selection-summary strong {
color: var(--accent-dark);
}
.action-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.action-button {
min-height: 37px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--ink);
background: #fff;
cursor: pointer;
font-size: 11.5px;
font-weight: 750;
transition: 0.15s ease;
}
.action-button:hover:not(:disabled) {
border-color: #b8b0ff;
background: #f8f7ff;
}
.action-button.primary {
border-color: var(--accent);
color: #fff;
background: var(--accent);
}
.action-button.primary:hover:not(:disabled) {
background: var(--accent-dark);
}
.action-button.danger {
color: #b93749;
border-color: #f0c5cc;
background: #fff7f8;
}
.action-button:disabled {
opacity: 0.42;
cursor: not-allowed;
}
.wide {
grid-column: 1 / -1;
}
.control-note {
margin: 13px 0 0;
padding: 11px;
border-radius: 11px;
color: #59657a;
background: rgba(232, 237, 245, 0.72);
font-size: 10.5px;
line-height: 1.55;
}
.control-note b {
color: #354158;
}
.audit-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.audit-heading h2 {
margin: 2px 0 0;
font-size: 16px;
}
.badge {
display: inline-flex;
align-items: center;
min-height: 25px;
padding: 5px 9px;
border-radius: 999px;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.06em;
text-transform: uppercase;
white-space: nowrap;
}
.badge.ok {
color: #087454;
background: var(--green-bg);
border: 1px solid #bee7d8;
}
.badge.bad {
color: #a42f42;
background: #fff0f2;
border: 1px solid #f1bec7;
}
.audit-cards {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
margin-bottom: 10px;
}
.audit-card {
min-width: 0;
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.82);
}
.audit-card strong {
display: block;
margin-top: 3px;
font-size: 18px;
line-height: 1;
}
.audit-card small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 8.5px;
font-weight: 700;
line-height: 1.2;
text-transform: uppercase;
}
.equation {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
margin-bottom: 8px;
padding: 10px 11px;
border: 1px solid #d9d4ff;
border-radius: 11px;
background: #f4f2ff;
color: #514a83;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
}
.equation strong {
color: var(--accent-dark);
font-size: 14px;
}
.map-check {
margin-bottom: 12px;
padding: 9px 10px;
border-radius: 10px;
color: #31705d;
background: #ecf8f3;
border: 1px solid #d1ecdf;
font-size: 10px;
font-weight: 750;
line-height: 1.4;
}
.map-check.bad {
color: #9d3444;
background: #fff1f3;
border-color: #f0c3cb;
}
.subhead {
display: flex;
align-items: center;
justify-content: space-between;
margin: 13px 0 7px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.map-list {
display: grid;
gap: 6px;
max-height: 248px;
overflow: auto;
padding-right: 3px;
scrollbar-width: thin;
}
.map-row {
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fff;
cursor: pointer;
transition: 0.14s ease;
}
.map-row:hover {
border-color: #c3bcff;
transform: translateX(-2px);
}
.map-row.selected {
border-color: #8f84ff;
background: #f5f3ff;
box-shadow: inset 3px 0 0 var(--accent);
}
.map-row.broken {
border-color: #efb2bd;
background: #fff3f5;
}
.row-main,
.row-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.row-main {
justify-content: flex-start;
}
.id-chip {
color: #fff;
background: #344158;
border-radius: 5px;
padding: 3px 5px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
font-weight: 800;
}
.row-name {
flex: 1;
min-width: 0;
overflow: hidden;
font-size: 11px;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.row-ok {
color: var(--green);
font-size: 12px;
font-weight: 900;
}
.row-meta {
justify-content: flex-start;
margin-top: 6px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 8.5px;
}
.group-tag {
margin-left: auto;
padding: 2px 5px;
border-radius: 4px;
color: #5c50bc;
background: #ebe8ff;
font-family: inherit;
font-weight: 800;
}
.groups-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.group-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--ink);
background: #fff;
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.group-chip.active {
border-color: #aaa1ff;
background: #f1efff;
}
.group-dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--group);
}
.group-chip small {
color: var(--muted);
font-size: 8.5px;
font-weight: 650;
}
.empty {
width: 100%;
padding: 12px;
border: 1px dashed #ccd4df;
border-radius: 9px;
color: var(--muted);
font-size: 10px;
text-align: center;
}
.activity-list {
display: grid;
gap: 6px;
}
.activity-item {
display: grid;
grid-template-columns: 64px 1fr;
gap: 8px;
align-items: start;
padding: 7px 0;
border-bottom: 1px solid #e6ebf1;
}
.activity-item:last-child {
border-bottom: 0;
}
.event-kind {
align-self: start;
padding: 3px 5px;
border-radius: 5px;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.04em;
text-align: center;
}
.event-kind.layout {
color: #5b4fc2;
background: #ece9ff;
}
.event-kind.quantity {
color: #a55c0c;
background: #fff0dc;
}
.event-kind.system {
color: #21725c;
background: #e5f6ef;
}
.activity-item b {
display: block;
font-size: 10px;
line-height: 1.3;
}
.activity-item small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8.5px;
line-height: 1.35;
}
.hint {
position: fixed;
z-index: 10;
left: 50%;
bottom: 13px;
transform: translateX(-50%);
max-width: calc(100vw - 36px);
padding: 8px 13px;
border: 1px solid rgba(255, 255, 255, 0.74);
border-radius: 999px;
color: #4c5870;
background: rgba(255, 255, 255, 0.83);
box-shadow: 0 8px 24px rgba(30, 43, 70, 0.1);
backdrop-filter: blur(12px);
font-size: 10.5px;
text-align: center;
white-space: nowrap;
}
.toast {
position: fixed;
z-index: 30;
top: 82px;
left: 50%;
transform: translate(-50%, -10px);
padding: 9px 14px;
border-radius: 10px;
color: #fff;
background: #29354b;
box-shadow: 0 10px 25px rgba(20, 30, 48, 0.22);
font-size: 11px;
font-weight: 750;
opacity: 0;
pointer-events: none;
transition: 0.2s ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 1000px) {
.shelf {
width: 215px;
}
.audit {
width: 350px;
}
.brand p {
display: none;
}
}
@media (max-width: 720px) {
.topbar {
left: 9px;
right: 9px;
top: 9px;
height: 54px;
}
.brand h1 {
font-size: 12px;
}
.global-status {
font-size: 9px;
padding: 7px 9px;
}
.shelf {
top: 72px;
left: 9px;
width: 205px;
max-height: 43vh;
overflow: auto;
padding: 12px;
}
.audit {
top: auto;
right: 9px;
bottom: 42px;
left: 9px;
width: auto;
max-height: 43vh;
padding: 12px;
}
.palette {
grid-template-columns: 1fr 1fr;
}
.hint {
bottom: 7px;
font-size: 8.5px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel toy scene"></canvas>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div>
<h1>Voxel Toy Yard</h1>
<p>Arrange toys without confusing layout changes with quantity changes.</p>
</div>
</div>
<div id="globalStatus" class="global-status">Starting audit…</div>
</header>
<aside class="panel shelf">
<div class="eyebrow">Toy shelf</div>
<h2 class="section-title">Add an object</h2>
<p class="subtle">Adding creates a new scene object and a matching ID row.</p>
<div id="palette" class="palette"></div>
<div class="divider"></div>
<div class="eyebrow">Selection</div>
<div class="selection-summary">
<span id="selectedSummary">0 selected</span>
<strong id="selectionMode">Nothing selected</strong>
</div>
<div class="action-grid">
<button id="groupButton" class="action-button primary" disabled>Group selected</button>
<button id="ungroupButton" class="action-button" disabled>Ungroup</button>
<button id="removeButton" class="action-button danger wide" disabled>
Remove selected toys
</button>
<button id="clearButton" class="action-button wide" disabled>Clear selection</button>
</div>
<p class="control-note">
<b>Scene:</b> drag a toy to move it. Shift-click to multi-select.
Double-click a toy to focus it.<br />
<b>Camera:</b> right-drag to orbit, middle-drag to pan, wheel to zoom.<br />
<b>Groups:</b> select a group chip, then drag one member to move the whole group.
</p>
</aside>
<aside class="panel audit">
<div class="audit-heading">
<div>
<div class="eyebrow">Visible one-to-one map</div>
<h2>Scene ↔ ID ledger</h2>
</div>
<span id="mappingBadge" class="badge">Checking</span>
</div>
<div class="audit-cards">
<div class="audit-card">
<strong id="sceneCount">0</strong>
<small>Scene objects</small>
</div>
<div class="audit-card">
<strong id="ledgerCount">0</strong>
<small>Ledger rows</small>
</div>
<div class="audit-card">
<strong id="layoutCount">0</strong>
<small>Layout ops</small>
</div>
<div class="audit-card">
<strong id="quantityCount">0</strong>
<small>Quantity ops</small>
</div>
</div>
<div id="quantityEquation" class="equation"></div>
<div id="mapCheck" class="map-check"></div>
<div class="subhead">
<span>ID map</span>
<span id="mapRowCount">0 rows</span>
</div>
<div id="mapList" class="map-list"></div>
<div class="subhead">
<span>Groups</span>
<span>Click to select a set</span>
</div>
<div id="groupsList" class="groups-list"></div>
<div class="subhead">
<span>Operation log</span>
<span>Layout vs quantity</span>
</div>
<div id="activityList" class="activity-list"></div>
</aside>
<div class="hint">
Drag toys to move · Shift-click to multi-select · G to group · Delete to remove · Arrow keys to nudge
</div>
<div id="toast" class="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and shared state
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const paletteEl = document.querySelector("#palette");
const mapListEl = document.querySelector("#mapList");
const groupsListEl = document.querySelector("#groupsList");
const activityListEl = document.querySelector("#activityList");
const toastEl = document.querySelector("#toast");
const groupButton = document.querySelector("#groupButton");
const ungroupButton = document.querySelector("#ungroupButton");
const removeButton = document.querySelector("#removeButton");
const clearButton = document.querySelector("#clearButton");
// Scene objects and ledger rows intentionally live in separate collections.
// The audit compares their independent ID sets.
const sceneObjects = new Map();
const ledger = new Map();
const groups = new Map();
const selected = new Set();
const activity = [];
const groupColors = [
"#6d5dfc",
"#ef5da8",
"#0ea5e9",
"#f59e0b",
"#10a878",
"#e85d75"
];
let nextToyNumber = 1;
let nextGroupNumber = 1;
let addedTotal = 0;
let removedTotal = 0;
let layoutOperations = 0;
let quantityOperations = 0;
let toastTimer = 0;
const INITIAL_COUNT = 4;
const TYPES = {
robot: {
name: "Voxel Bot",
color: "#8b5cf6",
height: 2.58
},
duck: {
name: "Block Duck",
color: "#f59e0b",
height: 1.72
},
rocket: {
name: "Mini Rocket",
color: "#ef4444",
height: 2.58
},
train: {
name: "Voxel Train",
color: "#0ea5e9",
height: 1.95
},
bear: {
name: "Pink Bear",
color: "#ec4899",
height: 2.16
},
blocks: {
name: "Block Stack",
color: "#22c55e",
height: 1.85
}
};
// -------------------------------------------------------------------------
// Renderer, camera, lighting, and diorama
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#dce9f2");
scene.fog = new THREE.Fog("#dce9f2", 25, 52);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
target: new THREE.Vector3(0, 0.55, 0),
yaw: 0.58,
pitch: 0.73,
radius: 22
};
function updateCamera() {
const { target, yaw, pitch, radius } = cameraState;
const horizontal = Math.sin(pitch) * radius;
camera.position.set(
target.x + horizontal * Math.sin(yaw),
target.y + Math.cos(pitch) * radius,
target.z + horizontal * Math.cos(yaw)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x8ea8ba, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff5df, 3.1);
sun.position.set(8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xc8e6ff, 1.0);
fill.position.set(-9, 8, -10);
scene.add(fill);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(22, 0.3, 22),
new THREE.MeshStandardMaterial({
color: 0xf7f2e9,
roughness: 0.92,
metalness: 0
})
);
platform.position.y = -0.15;
platform.receiveShadow = true;
scene.add(platform);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0xd7e4e9,
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.32;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(22, 22, 0x9eafbc, 0xc5d0d9);
grid.position.y = 0.008;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const boundaryPoints = [
new THREE.Vector3(-10.8, 0.018, -10.8),
new THREE.Vector3(10.8, 0.018, -10.8),
new THREE.Vector3(10.8, 0.018, 10.8),
new THREE.Vector3(-10.8, 0.018, 10.8)
];
const boundary = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(boundaryPoints),
new THREE.LineBasicMaterial({
color: 0x7c8b99,
transparent: true,
opacity: 0.35
})
);
scene.add(boundary);
const selectionHelper = new THREE.Box3Helper(
new THREE.Box3(),
new THREE.Color("#6d5dfc")
);
selectionHelper.visible = false;
selectionHelper.material.transparent = true;
selectionHelper.material.opacity = 0.9;
selectionHelper.material.depthTest = false;
scene.add(selectionHelper);
// -------------------------------------------------------------------------
// Voxel toy construction
// -------------------------------------------------------------------------
function addVoxel(parent, size, position, color, options = {}) {
const geometry = new THREE.BoxGeometry(...size);
const material = new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.72,
metalness: options.metalness ?? 0,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabelSprite(text, color = "#344158") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 64;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 256, 64);
context.fillStyle = "rgba(255,255,255,0.94)";
context.fillRect(3, 3, 250, 58);
context.strokeStyle = color;
context.lineWidth = 4;
context.strokeRect(3, 3, 250, 58);
context.fillStyle = color;
context.font = "bold 27px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 33);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.12, 0.28, 1);
sprite.renderOrder = 10;
return sprite;
}
function buildToyModel(type) {
const root = new THREE.Group();
if (type === "robot") {
addVoxel(root, [0.86, 1.02, 0.7], [0, 0.98, 0], "#7452df");
addVoxel(root, [0.54, 0.34, 0.06], [0, 1.08, 0.37], "#f9d65c");
addVoxel(root, [0.8, 0.64, 0.72], [0, 1.82, 0], "#a78bfa");
addVoxel(root, [0.14, 0.14, 0.06], [-0.2, 1.9, 0.39], "#20283a");
addVoxel(root, [0.14, 0.14, 0.06], [0.2, 1.9, 0.39], "#20283a");
addVoxel(root, [0.3, 0.06, 0.05], [0, 1.68, 0.39], "#312a57");
addVoxel(root, [0.28, 0.83, 0.3], [-0.62, 1.02, 0], "#4f8fe8");
addVoxel(root, [0.28, 0.83, 0.3], [0.62, 1.02, 0], "#4f8fe8");
addVoxel(root, [0.3, 0.22, 0.34], [-0.62, 0.64, 0.02], "#f2b84b");
addVoxel(root, [0.3, 0.22, 0.34], [0.62, 0.64, 0.02], "#f2b84b");
addVoxel(root, [0.31, 0.66, 0.35], [-0.25, 0.35, 0], "#303b56");
addVoxel(root, [0.31, 0.66, 0.35], [0.25, 0.35, 0], "#303b56");
addVoxel(root, [0.4, 0.18, 0.52], [-0.25, 0.09, 0.09], "#20283a");
addVoxel(root, [0.4, 0.18, 0.52], [0.25, 0.09, 0.09], "#20283a");
addVoxel(root, [0.08, 0.34, 0.08], [0, 2.29, 0], "#303b56");
addVoxel(root, [0.18, 0.18, 0.18], [0, 2.49, 0], "#f05d75");
}
if (type === "duck") {
addVoxel(root, [1.16, 0.68, 0.86], [0, 0.38, 0], "#f6bd35");
addVoxel(root, [0.62, 0.62, 0.62], [0.36, 1.02, 0.04], "#ffd65b");
addVoxel(root, [0.46, 0.18, 0.44], [0.37, 0.97, 0.53], "#ef7e32");
addVoxel(root, [0.11, 0.12, 0.06], [0.2, 1.12, 0.38], "#252d3d");
addVoxel(root, [0.11, 0.12, 0.06], [0.53, 1.12, 0.38], "#252d3d");
addVoxel(root, [0.16, 0.45, 0.5], [-0.48, 0.47, -0.02], "#eaa92d");
addVoxel(root, [0.16, 0.45, 0.5], [0.48, 0.47, -0.02], "#eaa92d");
addVoxel(root, [0.3, 0.12, 0.46], [-0.22, 0.06, 0.08], "#e99129");
addVoxel(root, [0.3, 0.12, 0.46], [0.22, 0.06, 0.08], "#e99129");
}
if (type === "rocket") {
addVoxel(root, [0.82, 1.36, 0.82], [0, 0.84, 0], "#ef5350");
addVoxel(root, [0.68, 0.36, 0.68], [0, 1.69, 0], "#f46a63");
addVoxel(root, [0.48, 0.32, 0.48], [0, 2.02, 0], "#ff8177");
addVoxel(root, [0.25, 0.26, 0.25], [0, 2.28, 0], "#ffd0c8");
addVoxel(root, [0.42, 0.42, 0.08], [0, 1.05, 0.44], "#64c9ee");
addVoxel(root, [0.14, 0.14, 0.1], [-0.2, 1.05, 0.5], "#ffffff", {
emissive: 0x4fc8eb,
emissiveIntensity: 0.35
});
addVoxel(root, [0.18, 0.57, 0.5], [-0.5, 0.39, 0], "#d94848");
addVoxel(root, [0.18, 0.57, 0.5], [0.5, 0.39, 0], "#d94848");
addVoxel(root, [0.52, 0.28, 0.56], [0, 0.1, 0], "#38445b");
}
if (type === "train") {
addVoxel(root, [1.72, 0.3, 0.92], [0, 0.43, 0], "#299bd3");
addVoxel(root, [0.92, 0.72, 0.78], [-0.28, 0.93, 0], "#3cb5ea");
addVoxel(root, [0.58, 0.4, 0.8], [0.55, 0.77, 0], "#f2b84b");
addVoxel(root, [0.48, 0.42, 0.06], [-0.43, 1.03, 0.42], "#d9f4ff");
addVoxel(root, [0.28, 0.28, 0.3], [0.05, 1.46, -0.08], "#38445b");
addVoxel(root, [0.4, 0.12, 0.4], [0.05, 1.66, -0.08], "#273247");
addVoxel(root, [0.34, 0.34, 0.18], [-0.55, 0.19, 0.48], "#263247");
addVoxel(root, [0.34, 0.34, 0.18], [0.52, 0.19, 0.48], "#263247");
addVoxel(root, [0.34, 0.34, 0.18], [-0.55, 0.19, -0.48], "#263247");
addVoxel(root, [0.34, 0.34, 0.18], [0.52, 0.19, -0.48], "#263247");
}
if (type === "bear") {
addVoxel(root, [0.9, 0.94, 0.65], [0, 0.82, 0], "#df5796");
addVoxel(root, [0.76, 0.68, 0.68], [0, 1.5, 0.02], "#ef6cab");
addVoxel(root, [0.28, 0.28, 0.28], [-0.3, 1.88, 0], "#d94c8c");
addVoxel(root, [0.28, 0.28, 0.28], [0.3, 1.88, 0], "#d94c8c");
addVoxel(root, [0.12, 0.12, 0.08], [-0.18, 1.57, 0.38], "#273044");
addVoxel(root, [0.12, 0.12, 0.08], [0.18, 1.57, 0.38], "#273044");
addVoxel(root, [0.36, 0.24, 0.12], [0, 1.4, 0.38], "#ffd1df");
addVoxel(root, [0.12, 0.09, 0.08], [0, 1.43, 0.46], "#513144");
addVoxel(root, [0.32, 0.58, 0.34], [-0.61, 0.76, 0], "#d94c8c");
addVoxel(root, [0.32, 0.58, 0.34], [0.61, 0.76, 0], "#d94c8c");
addVoxel(root, [0.34, 0.38, 0.4], [-0.26, 0.19, 0.03], "#c83d7c");
addVoxel(root, [0.34, 0.38, 0.4], [0.26, 0.19, 0.03], "#c83d7c");
}
if (type === "blocks") {
addVoxel(root, [0.62, 0.62, 0.62], [-0.25, 0.31, 0.18], "#ef5b62");
addVoxel(root, [0.62, 0.62, 0.62], [0.27, 0.31, -0.16], "#3e83e5");
addVoxel(root, [0.62, 0.62, 0.62], [0, 0.93, 0.08], "#f3c342");
addVoxel(root, [0.5, 0.5, 0.5], [-0.08, 1.49, -0.03], "#21ad79");
addVoxel(root, [0.28, 0.28, 0.28], [0.1, 1.86, 0.08], "#9b62e6");
}
return {
root,
height: TYPES[type].height
};
}
function makeToyId(number) {
return `T-${String(number).padStart(3, "0")}`;
}
function createToy(type, id, position, rotation = 0) {
const model = buildToyModel(type);
const root = model.root;
root.name = id;
root.position.set(position[0], 0, position[1]);
root.rotation.y = rotation;
root.userData.toyId = id;
root.userData.toyType = type;
const idLabel = makeLabelSprite(id, TYPES[type].color);
idLabel.position.set(0, model.height, 0);
root.add(idLabel);
root.traverse((object) => {
object.userData.toyId = id;
if (object.isMesh) {
object.castShadow = true;
object.receiveShadow = true;
}
});
scene.add(root);
sceneObjects.set(id, root);
ledger.set(id, {
id,
type,
name: TYPES[type].name,
color: TYPES[type].color,
groupId: null
});
return root;
}
function disposeToy(root) {
root.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 findSpawnPosition() {
for (let attempt = 0; attempt < 100; attempt++) {
const x = THREE.MathUtils.randFloatSpread(16);
const z = THREE.MathUtils.randFloatSpread(16);
let clear = true;
for (const root of sceneObjects.values()) {
const dx = root.position.x - x;
const dz = root.position.z - z;
if (dx * dx + dz * dz < 2.25) {
clear = false;
break;
}
}
if (clear) return [x, z];
}
return [0, 0];
}
// -------------------------------------------------------------------------
// Audit, selection, grouping, and operations
// -------------------------------------------------------------------------
function validateMapping() {
const sceneIds = new Set(sceneObjects.keys());
const ledgerIds = new Set(ledger.keys());
const missingInScene = [...ledgerIds].filter((id) => !sceneIds.has(id));
const missingInLedger = [...sceneIds].filter((id) => !ledgerIds.has(id));
const duplicateIds = 0;
const valid =
missingInScene.length === 0 &&
missingInLedger.length === 0 &&
duplicateIds === 0 &&
sceneObjects.size === ledger.size;
return {
valid,
missingInScene,
missingInLedger,
duplicateIds
};
}
function recordActivity(kind, label, text, detail = "") {
activity.unshift({
kind,
label,
text,
detail,
time: new Date().toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
})
});
if (activity.length > 30) activity.pop();
}
function showToast(message) {
toastEl.textContent = message;
toastEl.classList.add("show");
clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => {
toastEl.classList.remove("show");
}, 1500);
}
function selectOnly(ids) {
selected.clear();
for (const id of ids) {
if (sceneObjects.has(id)) selected.add(id);
}
renderAll();
}
function toggleSelection(id) {
if (selected.has(id)) {
selected.delete(id);
} else if (sceneObjects.has(id)) {
selected.add(id);
}
renderAll();
}
function addToy(type) {
const id = makeToyId(nextToyNumber++);
const position = findSpawnPosition();
const rotation = Math.random() * Math.PI * 2;
createToy(type, id, position, rotation);
addedTotal++;
quantityOperations++;
recordActivity(
"quantity",
`QTY +1`,
`Added ${id} · ${TYPES[type].name}`,
`Quantity changed; layout count is unchanged. Total is now ${sceneObjects.size}.`
);
selectOnly([id]);
showToast(`${id} added — one new ledger row created`);
}
function removeSelectedToys() {
const ids = [...selected].filter((id) => sceneObjects.has(id));
if (ids.length === 0) return;
for (const id of ids) {
const row = ledger.get(id);
if (row?.groupId) {
const oldGroup = groups.get(row.groupId);
if (oldGroup) {
oldGroup.toyIds = oldGroup.toyIds.filter((memberId) => memberId !== id);
}
}
const root = sceneObjects.get(id);
if (root) {
scene.remove(root);
disposeToy(root);
}
sceneObjects.delete(id);
ledger.delete(id);
}
selected.clear();
removedTotal += ids.length;
quantityOperations++;
pruneEmptyGroups();
const shownIds = ids.slice(0, 3).join(", ");
const extra = ids.length > 3 ? ` +${ids.length - 3} more` : "";
recordActivity(
"quantity",
`QTY −${ids.length}`,
`Removed ${shownIds}${extra}`,
`Quantity changed; layout count is unchanged. Total is now ${sceneObjects.size}.`
);
renderAll();
showToast(`${ids.length} toy${ids.length === 1 ? "" : "s"} removed`);
}
function groupSelectedToys() {
const ids = [...selected].filter((id) => sceneObjects.has(id));
if (ids.length < 2) return;
for (const id of ids) {
const row = ledger.get(id);
if (row?.groupId) {
const oldGroup = groups.get(row.groupId);
if (oldGroup) {
oldGroup.toyIds = oldGroup.toyIds.filter((memberId) => memberId !== id);
}
}
}
pruneEmptyGroups();
const groupNumber = nextGroupNumber++;
const groupId = `G${groupNumber}`;
const color = groupColors[(groupNumber - 1) % groupColors.length];
const group = {
id: groupId,
color,
toyIds: [...ids],
helper: null,
label: null
};
const helper = new THREE.Box3Helper(new THREE.Box3(), color);
helper.material.transparent = true;
helper.material.opacity = 0.55;
helper.material.depthTest = false;
group.helper = helper;
scene.add(helper);
const label = makeLabelSprite(`${groupId} · ${ids.length}`, color);
label.scale.set(1.22, 0.3, 1);
group.label = label;
scene.add(label);
groups.set(groupId, group);
for (const id of ids) {
ledger.get(id).groupId = groupId;
}
layoutOperations++;
recordActivity(
"layout",
"LAYOUT",
`Grouped ${ids.length} toys as ${groupId}`,
"Organization changed; no toy was added or removed."
);
renderAll();
showToast(`${groupId} created — drag a member to move the set`);
}
function removeGroupVisual(group) {
if (group.helper) {
scene.remove(group.helper);
group.helper.geometry.dispose();
group.helper.material.dispose();
}
if (group.label) {
scene.remove(group.label);
if (group.label.material.map) group.label.material.map.dispose();
group.label.material.dispose();
}
}
function pruneEmptyGroups() {
for (const [id, group] of groups) {
const validMembers = group.toyIds.filter((memberId) => {
const row = ledger.get(memberId);
return row && row.groupId === id;
});
group.toyIds = validMembers;
if (validMembers.length === 0) {
removeGroupVisual(group);
groups.delete(id);
}
}
}
function ungroupSelectedToys() {
const affectedGroups = new Set();
for (const id of selected) {
const row = ledger.get(id);
if (row?.groupId) affectedGroups.add(row.groupId);
}
if (affectedGroups.size === 0) return;
let affectedCount = 0;
for (const groupId of affectedGroups) {
const group = groups.get(groupId);
if (!group) continue;
affectedCount += group.toyIds.length;
for (const memberId of group.toyIds) {
const row = ledger.get(memberId);
if (row) row.groupId = null;
}
removeGroupVisual(group);
groups.delete(groupId);
}
layoutOperations++;
recordActivity(
"layout",
"LAYOUT",
`Ungrouped ${affectedCount} toy${affectedCount === 1 ? "" : "s"}`,
"Organization changed; quantity is unchanged."
);
renderAll();
showToast("Group dissolved — toy quantity is unchanged");
}
function boundsForIds(ids) {
const bounds = new THREE.Box3();
for (const id of ids) {
const root = sceneObjects.get(id);
if (!root) continue;
root.updateMatrixWorld(true);
root.traverse((object) => {
if (object.isMesh) {
bounds.expandByObject(object);
}
});
}
return bounds;
}
function updateSelectionAndGroupVisuals() {
const selectionIds = [...selected].filter((id) => sceneObjects.has(id));
const selectionBounds = boundsForIds(selectionIds);
if (selectionBounds.isEmpty()) {
selectionHelper.visible = false;
} else {
selectionHelper.visible = true;
selectionHelper.box.copy(selectionBounds);
}
for (const group of groups.values()) {
const bounds = boundsForIds(group.toyIds);
if (bounds.isEmpty()) continue;
group.helper.visible = true;
group.helper.box.copy(bounds);
group.label.visible = true;
group.label.position.set(
(bounds.min.x + bounds.max.x) * 0.5,
bounds.max.y + 0.48,
(bounds.min.z + bounds.max.z) * 0.5
);
}
}
// -------------------------------------------------------------------------
// UI rendering
// -------------------------------------------------------------------------
function renderPalette() {
paletteEl.innerHTML = Object.entries(TYPES)
.map(
([type, data]) => `
<button class="toy-button" data-add="${type}" title="Add ${data.name}">
<span class="mini-toy" style="--toy:${data.color}"></span>
<span>
<b>${data.name}</b>
<small>+ add toy</small>
</span>
<span class="plus">+</span>
</button>
`
)
.join("");
}
function renderMap() {
const validation = validateMapping();
const rows = [...ledger.values()].sort((a, b) => a.id.localeCompare(b.id));
mapListEl.innerHTML = rows
.map((row) => {
const root = sceneObjects.get(row.id);
const group = row.groupId ? groups.get(row.groupId) : null;
const selectedClass = selected.has(row.id) ? "selected" : "";
const brokenClass = root ? "" : "broken";
const location = root
? `x ${root.position.x.toFixed(1)} · z ${root.position.z.toFixed(1)}`
: "missing from scene";
return `
<div
class="map-row ${selectedClass} ${brokenClass}"
data-id="${row.id}"
role="button"
tabindex="0"
title="Select ${row.id}. Double-click to focus it."
>
<div class="row-main">
<span class="id-chip">${row.id}</span>
<span class="row-name">${row.name}</span>
<span class="row-ok">${root ? "✓" : "!"}</span>
</div>
<div class="row-meta">
<span>${root ? "↔ scene" : "✕ missing"}</span>
<span>${location}</span>
<span class="group-tag">${group ? group.id : "ungrouped"}</span>
</div>
</div>
`;
})
.join("");
if (rows.length === 0) {
mapListEl.innerHTML = `<div class="empty">No toys. Add one from the shelf.</div>`;
}
document.querySelector("#sceneCount").textContent = sceneObjects.size;
document.querySelector("#ledgerCount").textContent = ledger.size;
document.querySelector("#layoutCount").textContent = layoutOperations;
document.querySelector("#quantityCount").textContent = quantityOperations;
document.querySelector("#mapRowCount").textContent = `${rows.length} rows`;
const currentCount = INITIAL_COUNT + addedTotal - removedTotal;
document.querySelector("#quantityEquation").innerHTML = `
<span>START ${INITIAL_COUNT}</span>
<span>+</span>
<span>ADD ${addedTotal}</span>
<span>−</span>
<span>REM ${removedTotal}</span>
<span>=</span>
<strong>${currentCount}</strong>
`;
const mapCheck = document.querySelector("#mapCheck");
mapCheck.classList.toggle("bad", !validation.valid);
mapCheck.textContent = validation.valid
? `Verified 1:1 — SCENE ${sceneObjects.size} = LEDGER ${ledger.size}. Every scene object has exactly one ledger row, with 0 missing IDs and 0 duplicates.`
: `Audit failed — missing from scene: ${validation.missingInScene.length}, missing from ledger: ${validation.missingInLedger.length}, duplicates: ${validation.duplicateIds}.`;
const badge = document.querySelector("#mappingBadge");
badge.className = `badge ${validation.valid ? "ok" : "bad"}`;
badge.textContent = validation.valid ? "1:1 verified" : "Audit failed";
const globalStatus = document.querySelector("#globalStatus");
globalStatus.classList.toggle("bad", !validation.valid);
globalStatus.textContent = validation.valid
? `${sceneObjects.size} toys · ${ledger.size} mapped · VERIFIED`
: `Mapping error · ${sceneObjects.size} scene / ${ledger.size} ledger`;
}
function renderGroups() {
if (groups.size === 0) {
groupsListEl.innerHTML = `<div class="empty">No groups. Select 2+ toys and group them.</div>`;
return;
}
groupsListEl.innerHTML = [...groups.values()]
.map((group) => {
const active = group.toyIds.every((id) => selected.has(id));
return `
<button
class="group-chip ${active ? "active" : ""}"
data-group="${group.id}"
style="--group:${group.color}"
title="Select all toys in ${group.id}"
>
<span class="group-dot"></span>
${group.id}
<small>${group.toyIds.length} toys</small>
</button>
`;
})
.join("");
}
function renderActivity() {
if (activity.length === 0) {
activityListEl.innerHTML = `<div class="empty">No operations yet.</div>`;
return;
}
activityListEl.innerHTML = activity
.slice(0, 12)
.map(
(entry) => `
<div class="activity-item">
<span class="event-kind ${entry.kind}">${entry.label}</span>
<div>
<b>${entry.text}</b>
<small>${entry.detail} · ${entry.time}</small>
</div>
</div>
`
)
.join("");
}
function renderSelectionControls() {
document.querySelector("#selectedSummary").textContent =
`${selected.size} selected`;
document.querySelector("#selectionMode").textContent =
selected.size === 0
? "Nothing selected"
: selected.size === 1
? "1 object"
: `${selected.size} objects`;
groupButton.disabled = selected.size < 2;
const hasGroupedSelection = [...selected].some((id) => {
return ledger.get(id)?.groupId;
});
ungroupButton.disabled = !hasGroupedSelection;
removeButton.disabled = selected.size === 0;
clearButton.disabled = selected.size === 0;
}
function renderAll() {
renderMap();
renderGroups();
renderActivity();
renderSelectionControls();
updateSelectionAndGroupVisuals();
}
// -------------------------------------------------------------------------
// Direct camera and object controls — no addons
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const groundPoint = new THREE.Vector3();
let pointerState = null;
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function intersectToy(event) {
updatePointer(event);
const roots = [...sceneObjects.values()];
const intersections = raycaster.intersectObjects(roots, true);
for (const intersection of intersections) {
let object = intersection.object;
while (object && !object.userData.toyId) {
object = object.parent;
}
if (object?.userData.toyId) {
return object.userData.toyId;
}
}
return null;
}
function getGroundIntersection(event) {
updatePointer(event);
return raycaster.ray.intersectPlane(groundPlane, groundPoint)
? groundPoint.clone()
: null;
}
function beginDrag(event, toyId) {
if (!selected.has(toyId)) return;
const startGround = getGroundIntersection(event);
if (!startGround) return;
const startPositions = new Map();
for (const id of selected) {
const root = sceneObjects.get(id);
if (root) startPositions.set(id, root.position.clone());
}
pointerState = {
mode: "drag",
pointerId: event.pointerId,
startGround,
startPositions,
moved: false
};
}
canvas.addEventListener("pointerdown", (event) => {
canvas.focus();
canvas.setPointerCapture(event.pointerId);
if (event.button === 0) {
const toyId = intersectToy(event);
if (toyId) {
if (event.shiftKey) {
const wasSelected = selected.has(toyId);
if (wasSelected) {
selected.delete(toyId);
} else {
selected.add(toyId);
}
renderAll();
if (!wasSelected) {
beginDrag(event, toyId);
}
return;
}
// Keeping a multi-selection allows a selected group to be dragged
// by any one of its members. Use the map or double-click to isolate.
if (!selected.has(toyId) || selected.size === 1) {
selectOnly([toyId]);
} else {
renderAll();
}
beginDrag(event, toyId);
return;
}
if (!event.shiftKey) {
selectOnly([]);
}
pointerState = {
mode: "orbit",
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
return;
}
if (event.button === 2) {
pointerState = {
mode: "orbit",
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
return;
}
if (event.button === 1) {
pointerState = {
mode: "pan",
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointerState) return;
if (pointerState.mode === "drag") {
const currentGround = getGroundIntersection(event);
if (!currentGround) return;
const deltaX = currentGround.x - pointerState.startGround.x;
const deltaZ = currentGround.z - pointerState.startGround.z;
if (Math.hypot(deltaX, deltaZ) > 0.025) {
pointerState.moved = true;
}
for (const [id, startPosition] of pointerState.startPositions) {
const root = sceneObjects.get(id);
if (!root) continue;
root.position.x = THREE.MathUtils.clamp(startPosition.x + deltaX, -10.2, 10.2);
root.position.z = THREE.MathUtils.clamp(startPosition.z + deltaZ, -10.2, 10.2);
}
updateSelectionAndGroupVisuals();
renderMap();
return;
}
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
if (pointerState.mode === "orbit") {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.28,
1.38
);
updateCamera();
}
if (pointerState.mode === "pan") {
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = camera.getWorldDirection(new THREE.Vector3());
forward.y = 0;
forward.normalize();
const scale = cameraState.radius * 0.0015;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -8, 8);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -8, 8);
updateCamera();
}
});
function finishPointer(event) {
if (!pointerState) return;
if (
pointerState.mode === "drag" &&
pointerState.moved &&
pointerState.startPositions.size > 0
) {
layoutOperations++;
const movedCount = pointerState.startPositions.size;
const groupIds = new Set();
for (const id of pointerState.startPositions.keys()) {
const groupId = ledger.get(id)?.groupId;
if (groupId) groupIds.add(groupId);
}
const detail = groupIds.size
? `Moved as group${groupIds.size > 1 ? " set" : ""}; quantity is unchanged.`
: "Position changed; quantity is unchanged.";
recordActivity(
"layout",
"LAYOUT",
`Moved ${movedCount} toy${movedCount === 1 ? "" : "s"}`,
detail
);
renderAll();
}
pointerState = null;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", finishPointer);
canvas.addEventListener("pointercancel", finishPointer);
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
38
);
updateCamera();
},
{ passive: false }
);
function focusToy(id) {
const root = sceneObjects.get(id);
if (!root) return;
cameraState.target.set(root.position.x, 0.65, root.position.z);
cameraState.radius = 8.5;
updateCamera();
}
canvas.addEventListener("dblclick", (event) => {
const toyId = intersectToy(event);
if (toyId) {
selectOnly([toyId]);
focusToy(toyId);
}
});
function frameAll() {
cameraState.target.set(0, 0.55, 0);
cameraState.yaw = 0.58;
cameraState.pitch = 0.73;
cameraState.radius = 22;
updateCamera();
}
// -------------------------------------------------------------------------
// UI events and keyboard shortcuts
// -------------------------------------------------------------------------
paletteEl.addEventListener("click", (event) => {
const button = event.target.closest("[data-add]");
if (button) addToy(button.dataset.add);
});
groupButton.addEventListener("click", groupSelectedToys);
ungroupButton.addEventListener("click", ungroupSelectedToys);
removeButton.addEventListener("click", removeSelectedToys);
clearButton.addEventListener("click", () => {
selectOnly([]);
});
mapListEl.addEventListener("click", (event) => {
const row = event.target.closest("[data-id]");
if (!row) return;
const id = row.dataset.id;
if (event.shiftKey) {
toggleSelection(id);
} else {
selectOnly([id]);
}
});
mapListEl.addEventListener("dblclick", (event) => {
const row = event.target.closest("[data-id]");
if (row) focusToy(row.dataset.id);
});
mapListEl.addEventListener("keydown", (event) => {
if (event.key !== "Enter" && event.key !== " ") return;
const row = event.target.closest("[data-id]");
if (!row) return;
event.preventDefault();
selectOnly([row.dataset.id]);
});
groupsListEl.addEventListener("click", (event) => {
const chip = event.target.closest("[data-group]");
if (!chip) return;
const group = groups.get(chip.dataset.group);
if (group) selectOnly(group.toyIds);
});
document.addEventListener("keydown", (event) => {
const tag = event.target.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
const key = event.key.toLowerCase();
if (key === "delete" || key === "backspace") {
event.preventDefault();
removeSelectedToys();
return;
}
if (key === "g" && selected.size >= 2) {
event.preventDefault();
groupSelectedToys();
return;
}
if (key === "u") {
event.preventDefault();
ungroupSelectedToys();
return;
}
if (key === "escape") {
selectOnly([]);
return;
}
if (key === "f") {
frameAll();
return;
}
const nudges = {
arrowleft: [-1, 0],
arrowright: [1, 0],
arrowup: [0, -1],
arrowdown: [0, 1]
};
if (nudges[key] && selected.size > 0) {
event.preventDefault();
const step = event.shiftKey ? 1 : 0.25;
const [dx, dz] = nudges[key];
for (const id of selected) {
const root = sceneObjects.get(id);
if (!root) continue;
root.position.x = THREE.MathUtils.clamp(root.position.x + dx * step, -10.2, 10.2);
root.position.z = THREE.MathUtils.clamp(root.position.z + dz * step, -10.2, 10.2);
}
layoutOperations++;
recordActivity(
"layout",
"LAYOUT",
`Nudged ${selected.size} toy${selected.size === 1 ? "" : "s"}`,
"Position changed; quantity is unchanged."
);
renderAll();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Initial scene and render loop
// -------------------------------------------------------------------------
createToy("robot", "T-001", [-3.3, -2.2], 0.1);
createToy("duck", "T-002", [0.9, -2.4], -0.3);
createToy("rocket", "T-003", [3.6, -0.4], 0.2);
createToy("train", "T-004", [-0.8, 2.7], -0.1);
nextToyNumber = 5;
recordActivity(
"system",
"AUDIT",
"Audit initialized",
`${INITIAL_COUNT} scene objects matched ${INITIAL_COUNT} ledger rows.`
);
renderPalette();
renderAll();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```