Prompt specification
Build or customize the Three.js 3D scene "Packing With Forbidden Combinations" 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: Packing With Forbidden Combinations
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/packing-with-forbidden-combinations-x3399
Scene Description Prompt:
Packing with forbidden combinations. Build a toy packing bench with explicitly incompatible item pairs. Let users assemble valid sets and show which negative constraint is violated by each rejected placement. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (packing-with-forbidden-combinations-x3399):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voidpack — Constraint Packing Bench</title>
<style>
:root {
color-scheme: dark;
--bg: #080c12;
--panel: #111823;
--panel-2: #161f2c;
--panel-3: #1c2735;
--line: #273447;
--line-bright: #3a4b61;
--text: #edf4fb;
--muted: #8f9fb2;
--muted-2: #637389;
--cyan: #61e5ff;
--cyan-dark: #123944;
--green: #63d69a;
--red: #ff6577;
--red-dark: #351720;
--amber: #ffca58;
--shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
background:
radial-gradient(circle at 50% -20%, #172537 0%, transparent 48%),
var(--bg);
color: var(--text);
}
body {
overflow: hidden;
}
button {
font: inherit;
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.app {
width: 100%;
height: 100vh;
display: grid;
grid-template-rows: 72px minmax(0, 1fr);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(9, 14, 21, 0.88);
backdrop-filter: blur(14px);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 34px;
height: 34px;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
display: block;
width: 14px;
height: 14px;
border: 1px solid rgba(97, 229, 255, 0.7);
background: #17333d;
box-shadow: inset 0 0 12px rgba(97, 229, 255, 0.16);
transform: rotate(30deg) skew(-7deg);
}
.brand-mark i:nth-child(1) {
left: 1px;
top: 10px;
}
.brand-mark i:nth-child(2) {
left: 12px;
top: 4px;
border-color: rgba(99, 214, 154, 0.7);
background: #18372e;
}
.brand-mark i:nth-child(3) {
left: 12px;
top: 17px;
border-color: rgba(255, 101, 119, 0.7);
background: #3b2028;
}
.brand h1 {
margin: 0;
font-size: 18px;
font-weight: 800;
letter-spacing: 0.17em;
line-height: 1;
}
.brand h1 span {
color: var(--cyan);
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.header-stats {
display: flex;
align-items: center;
gap: 24px;
}
.header-stat {
display: grid;
gap: 2px;
text-align: right;
}
.header-stat span {
color: var(--muted-2);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.header-stat strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
font-weight: 700;
}
.live-pill {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.live-pill::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px var(--green);
}
.workspace {
min-height: 0;
display: grid;
grid-template-columns: 248px minmax(420px, 1fr) 320px;
gap: 12px;
padding: 12px;
}
.panel,
.viewport-card {
min-height: 0;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(16, 23, 33, 0.92);
box-shadow: var(--shadow);
overflow: hidden;
}
.panel {
display: flex;
flex-direction: column;
}
.panel-header {
min-height: 64px;
padding: 16px 17px 13px;
border-bottom: 1px solid var(--line);
}
.eyebrow {
margin: 0 0 5px;
color: var(--muted-2);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.panel-header h2 {
margin: 0;
font-size: 15px;
font-weight: 750;
letter-spacing: 0.01em;
}
.panel-header h2 span {
color: var(--cyan);
}
.panel-scroll {
min-height: 0;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: var(--line-bright) transparent;
}
.palette-intro {
margin: 0;
padding: 14px 17px;
border-bottom: 1px solid var(--line);
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
#itemPalette {
display: grid;
gap: 9px;
padding: 13px;
}
.item-card {
position: relative;
display: grid;
grid-template-columns: 49px minmax(0, 1fr) auto;
align-items: center;
gap: 11px;
width: 100%;
min-height: 70px;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: #141d29;
color: var(--text);
text-align: left;
cursor: grab;
transition:
border-color 150ms ease,
background 150ms ease,
transform 150ms ease,
opacity 150ms ease;
}
.item-card:hover:not(:disabled) {
border-color: var(--line-bright);
background: #192433;
transform: translateY(-1px);
}
.item-card.active {
border-color: var(--cyan);
background: linear-gradient(90deg, rgba(97, 229, 255, 0.12), #17222f);
box-shadow: inset 3px 0 0 var(--cyan);
}
.item-card:disabled {
cursor: default;
opacity: 0.42;
}
.item-card.used {
opacity: 0.56;
}
.item-card.shake {
animation: shake 320ms ease;
border-color: var(--red);
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
.voxel-icon {
position: relative;
width: 38px;
height: 38px;
margin-left: 3px;
}
.voxel-icon i {
position: absolute;
display: block;
width: 23px;
height: 23px;
border: 1px solid color-mix(in srgb, var(--item-color) 70%, white);
background: var(--item-color);
box-shadow:
inset -5px -5px 0 rgba(0, 0, 0, 0.16),
inset 4px 4px 0 rgba(255, 255, 255, 0.12),
5px 7px 0 rgba(0, 0, 0, 0.25);
transform: rotate(30deg) skew(-7deg);
}
.voxel-icon i:nth-child(2) {
width: 15px;
height: 15px;
left: 20px;
top: 3px;
opacity: 0.88;
}
.voxel-icon i:nth-child(3) {
width: 15px;
height: 15px;
left: 5px;
top: 22px;
opacity: 0.65;
}
.item-copy {
min-width: 0;
}
.item-copy strong {
display: block;
overflow: hidden;
font-size: 12px;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.item-copy small {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.item-code {
align-self: start;
padding: 4px 5px;
border: 1px solid var(--line);
border-radius: 4px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
font-weight: 800;
}
.palette-tip {
margin-top: auto;
padding: 14px 17px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.palette-tip kbd {
display: inline-block;
padding: 2px 5px;
border: 1px solid var(--line-bright);
border-bottom-width: 2px;
border-radius: 4px;
background: var(--panel-3);
color: var(--text);
font-family: ui-monospace, monospace;
font-size: 9px;
}
.viewport-card {
display: grid;
grid-template-rows: minmax(0, 1fr) 70px;
background: #0b1119;
}
#sceneWrap {
position: relative;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 45%, rgba(34, 58, 76, 0.3), transparent 48%),
linear-gradient(180deg, #101923, #090e15);
}
#scene {
display: block;
width: 100%;
height: 100%;
cursor: crosshair;
touch-action: none;
outline: none;
}
#scene.orbiting {
cursor: grabbing;
}
.view-hud {
position: absolute;
z-index: 2;
pointer-events: none;
}
.view-hud.top-left {
top: 17px;
left: 17px;
}
.view-hud.top-right {
top: 17px;
right: 17px;
text-align: right;
}
.view-hud.bottom-left {
bottom: 16px;
left: 17px;
}
.hud-tag {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 7px 9px;
border: 1px solid rgba(83, 105, 127, 0.5);
border-radius: 6px;
background: rgba(10, 16, 24, 0.78);
color: #a8b7c8;
backdrop-filter: blur(8px);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
}
.hud-tag strong {
color: var(--cyan);
}
.view-help {
margin-top: 8px;
color: var(--muted-2);
font-size: 10px;
}
.cell-readout {
min-width: 72px;
text-align: center;
color: var(--text);
font-size: 13px;
}
#pieceTools {
position: absolute;
z-index: 4;
top: 16px;
left: 50%;
display: flex;
align-items: center;
gap: 9px;
padding: 8px 9px 8px 12px;
border: 1px solid var(--line-bright);
border-radius: 9px;
background: rgba(15, 23, 33, 0.95);
box-shadow: var(--shadow);
transform: translateX(-50%);
}
#pieceTools[hidden] {
display: none;
}
#pieceTools strong {
font-size: 11px;
white-space: nowrap;
}
#pieceTools small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.mini-button {
padding: 7px 9px;
border: 1px solid var(--line-bright);
border-radius: 6px;
background: var(--panel-3);
color: var(--text);
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
.mini-button:hover {
border-color: var(--cyan);
color: var(--cyan);
}
.mini-button.danger:hover {
border-color: var(--red);
color: var(--red);
}
#toast {
position: absolute;
z-index: 5;
left: 50%;
bottom: 55px;
max-width: calc(100% - 30px);
padding: 10px 14px;
border: 1px solid var(--line-bright);
border-radius: 7px;
background: rgba(12, 19, 28, 0.94);
color: var(--text);
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 8px);
transition: opacity 160ms ease, transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
border-color: var(--red);
color: #ffd2d8;
}
#toast.success {
border-color: var(--green);
color: #ceffe7;
}
.bench-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
padding: 12px 14px;
border-top: 1px solid var(--line);
background: #101721;
}
.active-set {
min-width: 0;
}
.active-set span {
display: block;
margin-bottom: 4px;
color: var(--muted-2);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.active-set strong {
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.action-row {
display: flex;
gap: 8px;
}
.button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
min-height: 38px;
padding: 0 13px;
border: 1px solid var(--line-bright);
border-radius: 7px;
background: var(--panel-3);
color: var(--text);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.05em;
cursor: pointer;
transition: border-color 150ms ease, background 150ms ease;
}
.button:hover:not(:disabled) {
border-color: var(--cyan);
background: #203040;
}
.button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.button.primary {
border-color: #3eb9ce;
background: var(--cyan);
color: #061117;
}
.button.primary:hover:not(:disabled) {
background: #92edff;
}
.button.danger:hover:not(:disabled) {
border-color: var(--red);
color: var(--red);
}
.inspector {
display: grid;
grid-template-rows: auto auto minmax(0, 1fr);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 13px 16px 10px;
}
.section-title h3 {
margin: 0;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.count-badge {
min-width: 22px;
padding: 3px 6px;
border-radius: 999px;
background: var(--cyan-dark);
color: var(--cyan);
font-family: ui-monospace, monospace;
font-size: 9px;
font-weight: 800;
text-align: center;
}
#ruleList {
display: grid;
gap: 7px;
padding: 0 12px 13px;
border-bottom: 1px solid var(--line);
}
.rule-card {
padding: 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(24, 33, 46, 0.7);
}
.rule-pair {
display: flex;
align-items: center;
gap: 5px;
margin-bottom: 7px;
}
.pair-item {
display: inline-flex;
align-items: center;
gap: 5px;
min-width: 0;
color: #c8d3df;
font-size: 9px;
font-weight: 750;
}
.pair-item i {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 2px;
background: var(--pair-color);
box-shadow: 0 0 7px color-mix(in srgb, var(--pair-color) 60%, transparent);
}
.rule-symbol {
color: var(--red);
font-family: ui-monospace, monospace;
font-size: 11px;
font-weight: 900;
}
.rule-card strong {
display: block;
color: #ffc3ca;
font-size: 10px;
}
.rule-card p {
margin: 4px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.rejection-section {
min-height: 0;
display: grid;
grid-template-rows: auto minmax(0, 1fr);
}
#rejectionList {
min-height: 0;
overflow: auto;
padding: 0 12px 14px;
scrollbar-width: thin;
scrollbar-color: var(--line-bright) transparent;
}
.empty-state {
margin: 10px 0;
padding: 22px 14px;
border: 1px dashed var(--line);
border-radius: 8px;
color: var(--muted-2);
font-size: 11px;
line-height: 1.55;
text-align: center;
}
.empty-state .empty-icon {
display: grid;
place-items: center;
width: 34px;
height: 34px;
margin: 0 auto 9px;
border: 1px solid var(--line-bright);
border-radius: 8px;
color: var(--green);
font-family: ui-monospace, monospace;
font-size: 16px;
}
.rejection-card {
margin-bottom: 9px;
overflow: hidden;
border: 1px solid #56303a;
border-radius: 9px;
background: linear-gradient(145deg, rgba(61, 27, 36, 0.85), rgba(27, 27, 35, 0.9));
}
.rejection-head {
display: flex;
justify-content: space-between;
gap: 10px;
padding: 9px 10px;
border-bottom: 1px solid rgba(116, 55, 68, 0.45);
color: #ff9ba8;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.attempt-line {
display: flex;
align-items: center;
gap: 7px;
padding: 10px;
color: #d5dce5;
font-size: 10px;
}
.attempt-line strong {
overflow: hidden;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.attempt-line .arrow {
margin-left: auto;
color: var(--red);
font-family: ui-monospace, monospace;
font-weight: 900;
}
.attempt-swatch {
display: grid;
place-items: center;
width: 23px;
height: 23px;
flex: 0 0 auto;
border: 1px solid color-mix(in srgb, var(--swatch) 60%, white);
border-radius: 5px;
background: color-mix(in srgb, var(--swatch) 35%, #101722);
color: var(--swatch);
font-family: ui-monospace, monospace;
font-size: 8px;
font-weight: 900;
}
.violation {
margin: 0 10px 10px;
padding: 9px;
border-left: 2px solid var(--red);
border-radius: 4px;
background: rgba(255, 101, 119, 0.08);
}
.violation-title {
color: #ffb5bf;
font-size: 10px;
font-weight: 850;
}
.violation p {
margin: 5px 0 0;
color: #bba3aa;
font-size: 9px;
line-height: 1.45;
}
.archive-section {
border-top: 1px solid var(--line);
}
#archiveList {
display: grid;
gap: 7px;
max-height: 150px;
overflow: auto;
padding: 0 12px 13px;
}
.archive-card {
padding: 10px;
border: 1px solid #28533f;
border-radius: 8px;
background: rgba(25, 55, 43, 0.45);
}
.archive-card header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.archive-card header span {
color: var(--green);
font-size: 8px;
}
.archive-items {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.archive-chip {
padding: 3px 6px;
border: 1px solid var(--line-bright);
border-radius: 4px;
color: #c4d1dc;
font-size: 8px;
font-weight: 750;
}
@media (max-width: 1150px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
}
.workspace {
grid-template-columns: 225px minmax(420px, 1fr);
grid-template-rows: minmax(610px, calc(100vh - 96px)) auto;
}
.inspector {
grid-column: 1 / -1;
grid-template-columns: 1fr 1fr;
grid-template-rows: auto auto;
max-height: 520px;
}
.inspector > .panel-header {
grid-column: 1 / -1;
}
#ruleList {
border-right: 1px solid var(--line);
border-bottom: 0;
}
.archive-section {
grid-column: 1 / -1;
border-top: 1px solid var(--line);
}
}
@media (max-width: 760px) {
.app {
grid-template-rows: auto auto;
}
header {
padding: 14px;
}
.brand p,
.header-stat,
.live-pill {
display: none;
}
.workspace {
display: flex;
flex-direction: column;
padding: 8px;
}
.palette-panel {
order: 2;
}
.viewport-card {
order: 1;
height: 610px;
min-height: 610px;
}
.inspector {
order: 3;
display: flex;
max-height: none;
}
#ruleList {
border-right: 0;
border-bottom: 1px solid var(--line);
}
#itemPalette {
grid-template-columns: 1fr 1fr;
}
.item-card {
grid-template-columns: 40px minmax(0, 1fr);
}
.item-code {
display: none;
}
.palette-tip {
display: none;
}
}
@media (max-width: 470px) {
#itemPalette {
grid-template-columns: 1fr;
}
.bench-actions {
align-items: stretch;
flex-direction: column;
}
.action-row {
display: grid;
grid-template-columns: 1fr 1fr;
}
.view-hud.top-right,
.view-help {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i>
</div>
<div>
<h1>VOID<span>PACK</span></h1>
<p>Constraint packing bench</p>
</div>
</div>
<div class="header-stats">
<div class="header-stat">
<span>Active set</span>
<strong id="activeSetHeader">01</strong>
</div>
<div class="header-stat">
<span>Archived</span>
<strong id="archivedHeader">00</strong>
</div>
<div class="live-pill">Constraint engine live</div>
</div>
</header>
<main class="workspace">
<aside class="panel palette-panel">
<div class="panel-header">
<p class="eyebrow">Inventory / 04 modules</p>
<h2>Voxel <span>Modules</span></h2>
</div>
<p class="palette-intro">
Select a module, then click a bench cell. You can also drag a module
directly onto the grid.
</p>
<div id="itemPalette"></div>
<div class="palette-tip">
<kbd>Click</kbd> to place or select<br>
<kbd>Drag</kbd> empty space to orbit<br>
<kbd>Scroll</kbd> to zoom · <kbd>Esc</kbd> to deselect
</div>
</aside>
<section class="viewport-card" aria-label="Interactive packing bench">
<div id="sceneWrap">
<canvas id="scene" tabindex="0" aria-label="3D voxel packing bench"></canvas>
<div class="view-hud top-left">
<div class="hud-tag">
<strong id="hudSetLabel">SET 01</strong>
<span id="hudItemCount">0 ITEMS</span>
</div>
</div>
<div class="view-hud top-right">
<div class="hud-tag">GRID 06 × 04</div>
<div class="view-help">Drag to orbit · wheel to zoom</div>
</div>
<div class="view-hud bottom-left">
<div class="hud-tag cell-readout" id="cellReadout">CELL —</div>
</div>
<div id="pieceTools" hidden>
<div>
<strong id="selectedPieceName">Module</strong>
<small id="selectedPieceCell">Cell</small>
</div>
<button class="mini-button" id="movePieceButton" type="button">Move</button>
<button class="mini-button danger" id="removePieceButton" type="button">Remove</button>
</div>
<div id="toast" role="status" aria-live="polite"></div>
</div>
<div class="bench-actions">
<div class="active-set">
<span>Assembly in progress</span>
<strong id="activeSetSummary">Empty bench · add at least two modules</strong>
</div>
<div class="action-row">
<button class="button danger" id="clearButton" type="button">Clear</button>
<button class="button primary" id="archiveButton" type="button" disabled>
Archive valid set
</button>
</div>
</div>
</section>
<aside class="panel inspector">
<div class="panel-header">
<p class="eyebrow">Negative constraints</p>
<h2>Forbidden <span>Pairs</span></h2>
</div>
<section>
<div class="section-title">
<h3>Active incompatibilities</h3>
<span class="count-badge" id="ruleCount">3</span>
</div>
<div id="ruleList"></div>
</section>
<section class="rejection-section">
<div class="section-title">
<h3>Rejected placements</h3>
<span class="count-badge" id="rejectionCount">0</span>
</div>
<div id="rejectionList"></div>
</section>
<section class="archive-section">
<div class="section-title">
<h3>Archived valid sets</h3>
<span class="count-badge" id="archiveCount">0</span>
</div>
<div id="archiveList"></div>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const ITEMS = {
ember: {
name: "Ember core",
code: "EC",
color: 0xff6b4a,
css: "#ff6b4a",
height: 0.86,
voxels: [
{ x: 0, y: 0.39, z: 0, size: [0.78, 0.78, 0.78] }
]
},
cobalt: {
name: "Cobalt relay",
code: "CR",
color: 0x4e8cff,
css: "#4e8cff",
height: 1.08,
voxels: [
{ x: 0, y: 0.24, z: 0, size: [0.68, 0.48, 0.68] },
{ x: 0, y: 0.64, z: 0, size: [0.44, 0.44, 0.44] }
]
},
solar: {
name: "Solar wafer",
code: "SW",
color: 0xffca4b,
css: "#ffca4b",
height: 0.42,
voxels: [
{ x: 0, y: 0.18, z: 0, size: [0.82, 0.36, 0.82] }
]
},
moss: {
name: "Moss stack",
code: "MS",
color: 0x62d394,
css: "#62d394",
height: 1.3,
voxels: [
{ x: 0, y: 0.29, z: 0, size: [0.58, 0.58, 0.58] },
{ x: 0, y: 0.74, z: 0, size: [0.48, 0.48, 0.48] },
{ x: 0, y: 1.1, z: 0, size: [0.38, 0.38, 0.38] }
]
}
};
const RULES = [
{
a: "ember",
b: "cobalt",
title: "Opposed polarity",
detail: "Their magnetic fields cannot share the same set."
},
{
a: "ember",
b: "moss",
title: "Thermal runaway",
detail: "The heat-sensitive moss cannot share Ember's chamber."
},
{
a: "cobalt",
b: "moss",
title: "Signal isolation",
detail: "The relay and organic stack require separate sets."
}
];
const COLS = 6;
const ROWS = 4;
const CELL = 1.02;
const BOARD_WIDTH = COLS * CELL;
const BOARD_DEPTH = ROWS * CELL;
const placements = new Map();
const rejectionAttempts = [];
const archivedSets = [];
let selectedItemId = null;
let selectedPlacementKey = null;
let movePlacementKey = null;
let rejectionCounter = 0;
let toastTimer = null;
// -------------------------------------------------------------------------
// DOM setup
// -------------------------------------------------------------------------
const paletteElement = $("#itemPalette");
const ruleListElement = $("#ruleList");
const rejectionListElement = $("#rejectionList");
const archiveListElement = $("#archiveList");
function makeItemIcon(item) {
return `
<div class="voxel-icon" style="--item-color:${item.css}" aria-hidden="true">
<i></i><i></i><i></i>
</div>
`;
}
function renderPalette() {
paletteElement.innerHTML = Object.entries(ITEMS).map(([id, item]) => {
const used = [...placements.values()].some((placement) => placement.itemId === id);
const active = selectedItemId === id;
return `
<button
class="item-card ${used ? "used" : ""} ${active ? "active" : ""}"
type="button"
data-item="${id}"
draggable="${!used}"
${used ? "disabled" : ""}
aria-pressed="${active}"
>
${makeItemIcon(item)}
<span class="item-copy">
<strong>${item.name}</strong>
<small>${used ? "Already packed" : "Ready to place"}</small>
</span>
<span class="item-code">${item.code}</span>
</button>
`;
}).join("");
paletteElement.querySelectorAll(".item-card").forEach((button) => {
const itemId = button.dataset.item;
button.addEventListener("click", () => {
if (button.disabled) return;
selectedItemId = itemId;
selectedPlacementKey = null;
movePlacementKey = null;
updateUI();
showToast(`${ITEMS[itemId].name} selected — choose a cell`);
});
button.addEventListener("dragstart", (event) => {
if (button.disabled) {
event.preventDefault();
return;
}
event.dataTransfer.setData("text/plain", itemId);
event.dataTransfer.effectAllowed = "copy";
selectedItemId = itemId;
selectedPlacementKey = null;
movePlacementKey = null;
updateUI();
});
});
}
function renderRules() {
ruleListElement.innerHTML = RULES.map((rule) => `
<article class="rule-card">
<div class="rule-pair">
<span class="pair-item" style="--pair-color:${ITEMS[rule.a].css}">
<i></i>${ITEMS[rule.a].name}
</span>
<span class="rule-symbol">≠</span>
<span class="pair-item" style="--pair-color:${ITEMS[rule.b].css}">
<i></i>${ITEMS[rule.b].name}
</span>
</div>
<strong>${rule.title}</strong>
<p>${rule.detail}</p>
</article>
`).join("");
$("#ruleCount").textContent = RULES.length;
}
function renderRejections() {
$("#rejectionCount").textContent = rejectionAttempts.length;
if (!rejectionAttempts.length) {
rejectionListElement.innerHTML = `
<div class="empty-state">
<div class="empty-icon">✓</div>
No rejected placements yet.<br>
Try packing a forbidden pair to inspect its violation.
</div>
`;
return;
}
rejectionListElement.innerHTML = rejectionAttempts.map((attempt) => `
<article class="rejection-card">
<div class="rejection-head">
<span>Rejected placement</span>
<span>Attempt ${String(attempt.number).padStart(2, "0")}</span>
</div>
<div class="attempt-line">
<span
class="attempt-swatch"
style="--swatch:${ITEMS[attempt.itemId].css}"
>${ITEMS[attempt.itemId].code}</span>
<strong>${ITEMS[attempt.itemId].name}</strong>
<span class="arrow">→ ${attempt.cellName}</span>
</div>
${attempt.violations.map((violation) => `
<div class="violation">
<div class="violation-title">× ${violation.rule.title}</div>
<p>
${ITEMS[attempt.itemId].name} conflicts with
${ITEMS[violation.otherId].name} at
${cellName(violation.otherCell)} under the
“${violation.rule.title}” negative constraint.
</p>
</div>
`).join("")}
</article>
`).join("");
}
function renderArchive() {
$("#archiveCount").textContent = archivedSets.length;
$("#archivedHeader").textContent = String(archivedSets.length).padStart(2, "0");
if (!archivedSets.length) {
archiveListElement.innerHTML = `
<div class="empty-state">
Valid sets you archive will appear here.
</div>
`;
return;
}
archiveListElement.innerHTML = archivedSets.map((set) => `
<article class="archive-card">
<header>
<strong>${set.name}</strong>
<span>✓ All pairs clear</span>
</header>
<div class="archive-items">
${set.items.map((itemId) => `
<span class="archive-chip">${ITEMS[itemId].code} · ${ITEMS[itemId].name}</span>
`).join("")}
</div>
</article>
`).join("");
}
function updateUI() {
const itemCount = placements.size;
const setNumber = archivedSets.length + 1;
renderPalette();
renderRejections();
renderArchive();
$("#activeSetHeader").textContent = String(setNumber).padStart(2, "0");
$("#hudSetLabel").textContent = `SET ${String(setNumber).padStart(2, "0")}`;
$("#hudItemCount").textContent = `${itemCount} ITEM${itemCount === 1 ? "" : "S"}`;
$("#archiveButton").disabled = itemCount < 2;
const names = [...placements.values()].map((placement) => ITEMS[placement.itemId].name);
$("#activeSetSummary").textContent = itemCount
? names.join(" + ")
: "Empty bench · add at least two modules";
const tools = $("#pieceTools");
if (selectedPlacementKey && placements.has(selectedPlacementKey)) {
const placement = placements.get(selectedPlacementKey);
tools.hidden = false;
$("#selectedPieceName").textContent = ITEMS[placement.itemId].name;
$("#selectedPieceCell").textContent = movePlacementKey
? "Choose a destination cell"
: `Cell ${cellName(selectedPlacementKey)}`;
$("#movePieceButton").textContent = movePlacementKey ? "Cancel move" : "Move";
} else {
tools.hidden = true;
selectedPlacementKey = null;
movePlacementKey = null;
}
updateSelectionOutlines();
}
function showToast(message, type = "") {
const toast = $("#toast");
toast.textContent = message;
toast.className = `show ${type}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.className = type;
}, 2600);
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const canvas = $("#scene");
const sceneWrap = $("#sceneWrap");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.setClearColor(0x000000, 0);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(39, 1, 0.1, 100);
const orbit = {
yaw: 0.76,
pitch: 0.68,
distance: 11.8,
target: new THREE.Vector3(0, 0.25, 0)
};
const hemisphere = new THREE.HemisphereLight(0xb9ddff, 0x18202c, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(4, 9, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x49cfff, 22, 16, 2);
rimLight.position.set(-4, 4, -4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff805f, 12, 11, 2);
warmLight.position.set(4, 2.5, -2);
scene.add(warmLight);
const floor = new THREE.Mesh(
new THREE.BoxGeometry(28, 0.2, 24),
new THREE.MeshStandardMaterial({
color: 0x0b1119,
roughness: 0.98,
metalness: 0.02
})
);
floor.position.y = -1.18;
floor.receiveShadow = true;
scene.add(floor);
const bench = new THREE.Group();
scene.add(bench);
const benchBaseMaterial = new THREE.MeshStandardMaterial({
color: 0x182331,
roughness: 0.72,
metalness: 0.34
});
const benchTopMaterial = new THREE.MeshStandardMaterial({
color: 0x243443,
roughness: 0.62,
metalness: 0.28
});
const benchEdgeMaterial = new THREE.MeshStandardMaterial({
color: 0x3b5264,
roughness: 0.48,
metalness: 0.48
});
const benchBase = new THREE.Mesh(
new THREE.BoxGeometry(BOARD_WIDTH + 0.8, 0.42, BOARD_DEPTH + 0.8),
benchBaseMaterial
);
benchBase.position.y = -0.25;
benchBase.castShadow = true;
benchBase.receiveShadow = true;
bench.add(benchBase);
const benchTop = new THREE.Mesh(
new THREE.BoxGeometry(BOARD_WIDTH + 0.52, 0.16, BOARD_DEPTH + 0.52),
benchTopMaterial
);
benchTop.position.y = -0.03;
benchTop.castShadow = true;
benchTop.receiveShadow = true;
bench.add(benchTop);
const legGeometry = new THREE.BoxGeometry(0.48, 0.68, 0.48);
[
[-1, -1],
[1, -1],
[-1, 1],
[1, 1]
].forEach(([sx, sz]) => {
const leg = new THREE.Mesh(legGeometry, benchBaseMaterial);
leg.position.set(
sx * (BOARD_WIDTH / 2 + 0.13),
-0.77,
sz * (BOARD_DEPTH / 2 + 0.13)
);
leg.castShadow = true;
bench.add(leg);
});
const gridMaterial = new THREE.MeshStandardMaterial({
color: 0x577185,
roughness: 0.42,
metalness: 0.48,
emissive: 0x172a35,
emissiveIntensity: 0.35
});
for (let column = 0; column <= COLS; column++) {
const x = (column - COLS / 2) * CELL;
const line = new THREE.Mesh(
new THREE.BoxGeometry(0.026, 0.022, BOARD_DEPTH),
gridMaterial
);
line.position.set(x, 0.065, 0);
bench.add(line);
}
for (let row = 0; row <= ROWS; row++) {
const z = (row - ROWS / 2) * CELL;
const line = new THREE.Mesh(
new THREE.BoxGeometry(BOARD_WIDTH, 0.022, 0.026),
gridMaterial
);
line.position.set(0, 0.066, z);
bench.add(line);
}
const railGeometryX = new THREE.BoxGeometry(BOARD_WIDTH + 0.48, 0.16, 0.12);
const railGeometryZ = new THREE.BoxGeometry(0.12, 0.16, BOARD_DEPTH + 0.48);
[-1, 1].forEach((sign) => {
const xRail = new THREE.Mesh(railGeometryX, benchEdgeMaterial);
xRail.position.set(0, 0.04, sign * (BOARD_DEPTH / 2 + 0.19));
xRail.castShadow = true;
bench.add(xRail);
const zRail = new THREE.Mesh(railGeometryZ, benchEdgeMaterial);
zRail.position.set(sign * (BOARD_WIDTH / 2 + 0.19), 0.04, 0);
zRail.castShadow = true;
bench.add(zRail);
});
function createTextSprite(text, color = "#8ea3b8") {
const textCanvas = document.createElement("canvas");
textCanvas.width = 128;
textCanvas.height = 64;
const context = textCanvas.getContext("2d");
context.clearRect(0, 0, 128, 64);
context.fillStyle = "rgba(8, 14, 21, 0.82)";
context.fillRect(24, 12, 80, 40);
context.strokeStyle = "rgba(111, 142, 165, 0.5)";
context.lineWidth = 2;
context.strokeRect(24, 12, 80, 40);
context.fillStyle = color;
context.font = "700 27px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 64, 33);
const texture = new THREE.CanvasTexture(textCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(0.48, 0.24, 1);
return sprite;
}
for (let column = 0; column < COLS; column++) {
const sprite = createTextSprite(String.fromCharCode(65 + column));
sprite.position.set(
(column - (COLS - 1) / 2) * CELL,
0.1,
BOARD_DEPTH / 2 + 0.47
);
bench.add(sprite);
}
for (let row = 0; row < ROWS; row++) {
const sprite = createTextSprite(String(row + 1));
sprite.position.set(
-BOARD_WIDTH / 2 - 0.47,
0.1,
(row - (ROWS - 1) / 2) * CELL
);
bench.add(sprite);
}
const cellTargets = [];
const cellGeometry = new THREE.PlaneGeometry(CELL * 0.94, CELL * 0.94);
const cellMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
side: THREE.DoubleSide,
depthWrite: false
});
for (let row = 0; row < ROWS; row++) {
for (let column = 0; column < COLS; column++) {
const key = `${column},${row}`;
const cell = new THREE.Mesh(cellGeometry, cellMaterial);
cell.rotation.x = -Math.PI / 2;
cell.position.set(
(column - (COLS - 1) / 2) * CELL,
0.085,
(row - (ROWS - 1) / 2) * CELL
);
cell.userData.cellKey = key;
scene.add(cell);
cellTargets.push(cell);
}
}
const hoverMarker = new THREE.Mesh(
new THREE.BoxGeometry(CELL * 0.89, 0.045, CELL * 0.89),
new THREE.MeshBasicMaterial({
color: 0x61e5ff,
transparent: true,
opacity: 0.2,
depthWrite: false
})
);
hoverMarker.visible = false;
scene.add(hoverMarker);
const flashMarker = new THREE.Mesh(
new THREE.BoxGeometry(CELL * 0.94, 0.07, CELL * 0.94),
new THREE.MeshBasicMaterial({
color: 0xff4058,
transparent: true,
opacity: 0.55,
depthWrite: false
})
);
flashMarker.visible = false;
scene.add(flashMarker);
let flashTimeout = null;
function cellPosition(key) {
const [column, row] = key.split(",").map(Number);
return {
x: (column - (COLS - 1) / 2) * CELL,
z: (row - (ROWS - 1) / 2) * CELL
};
}
function cellName(key) {
const [column, row] = key.split(",").map(Number);
return `${String.fromCharCode(65 + column)}${row + 1}`;
}
function createItemGroup(itemId) {
const item = ITEMS[itemId];
const group = new THREE.Group();
const pad = new THREE.Mesh(
new THREE.BoxGeometry(0.89, 0.07, 0.89),
new THREE.MeshStandardMaterial({
color: new THREE.Color(item.color).multiplyScalar(0.3),
roughness: 0.6,
metalness: 0.3
})
);
pad.position.y = 0.035;
pad.receiveShadow = true;
group.add(pad);
item.voxels.forEach((voxel, index) => {
const color = new THREE.Color(item.color);
color.offsetHSL(0, 0, index * 0.035);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(...voxel.size),
new THREE.MeshStandardMaterial({
color,
roughness: 0.46,
metalness: 0.18,
emissive: new THREE.Color(item.color).multiplyScalar(0.08),
emissiveIntensity: 0.35
})
);
mesh.position.set(voxel.x, voxel.y, voxel.z);
mesh.castShadow = true;
mesh.receiveShadow = true;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.16
})
);
mesh.add(edges);
group.add(mesh);
});
const outline = new THREE.Mesh(
new THREE.BoxGeometry(0.94, item.height + 0.08, 0.94),
new THREE.MeshBasicMaterial({
color: 0xffffff,
wireframe: true,
transparent: true,
opacity: 0.7,
depthTest: false
})
);
outline.position.y = item.height / 2 + 0.03;
outline.visible = false;
outline.renderOrder = 10;
group.add(outline);
const label = createTextSprite(item.code, item.css);
label.position.set(0, item.height + 0.31, 0);
group.add(label);
group.userData.itemId = itemId;
group.userData.outline = outline;
group.userData.spawnTime = performance.now();
return group;
}
function updateSelectionOutlines() {
placements.forEach((placement, key) => {
const outline = placement.group.userData.outline;
if (outline) {
outline.visible = key === selectedPlacementKey;
}
});
}
// -------------------------------------------------------------------------
// Constraint engine
// -------------------------------------------------------------------------
function getViolations(itemId, ignoredCell = null) {
const violations = [];
for (const rule of RULES) {
let otherId = null;
if (rule.a === itemId) otherId = rule.b;
else if (rule.b === itemId) otherId = rule.a;
if (!otherId) continue;
for (const [key, placement] of placements.entries()) {
if (key === ignoredCell) continue;
if (placement.itemId === otherId) {
violations.push({
rule,
otherId,
otherCell: key
});
}
}
}
return violations;
}
function logRejectedPlacement(itemId, cellKey, violations, isMove = false) {
rejectionCounter += 1;
rejectionAttempts.unshift({
number: rejectionCounter,
itemId,
cellKey,
cellName: cellName(cellKey),
violations,
isMove
});
const card = paletteElement.querySelector(`[data-item="${itemId}"]`);
card?.classList.add("shake");
setTimeout(() => card?.classList.remove("shake"), 340);
flashRejectedCell(cellKey);
updateUI();
const suffix = violations.length === 1
? "1 negative constraint violated"
: `${violations.length} negative constraints violated`;
showToast(`Placement rejected · ${suffix}`, "error");
}
function flashRejectedCell(key) {
const position = cellPosition(key);
flashMarker.position.set(position.x, 0.12, position.z);
flashMarker.visible = true;
clearTimeout(flashTimeout);
flashTimeout = setTimeout(() => {
flashMarker.visible = false;
}, 650);
}
function attemptPlace(itemId, cellKey) {
if (!ITEMS[itemId] || !cellKey) return;
const alreadyPacked = [...placements.values()].some(
(placement) => placement.itemId === itemId
);
if (alreadyPacked) {
showToast(`${ITEMS[itemId].name} is already in this set`, "error");
return;
}
if (placements.has(cellKey)) {
showToast(`Cell ${cellName(cellKey)} is already occupied`, "error");
flashRejectedCell(cellKey);
return;
}
const violations = getViolations(itemId);
if (violations.length) {
logRejectedPlacement(itemId, cellKey, violations);
return;
}
const group = createItemGroup(itemId);
const position = cellPosition(cellKey);
group.position.set(position.x, 0.09, position.z);
group.scale.setScalar(0.72);
scene.add(group);
placements.set(cellKey, { itemId, group });
selectedItemId = null;
selectedPlacementKey = null;
movePlacementKey = null;
updateUI();
showToast(`${ITEMS[itemId].name} packed at ${cellName(cellKey)}`, "success");
}
function attemptMove(cellKey) {
if (!movePlacementKey || !placements.has(movePlacementKey)) return;
const oldKey = movePlacementKey;
const placement = placements.get(oldKey);
if (cellKey === oldKey) {
movePlacementKey = null;
updateUI();
return;
}
if (placements.has(cellKey)) {
showToast(`Cell ${cellName(cellKey)} is already occupied`, "error");
flashRejectedCell(cellKey);
return;
}
const violations = getViolations(placement.itemId, oldKey);
if (violations.length) {
logRejectedPlacement(placement.itemId, cellKey, violations, true);
return;
}
placements.delete(oldKey);
placement.group.userData.cellKey = cellKey;
placements.set(cellKey, placement);
const position = cellPosition(cellKey);
placement.group.userData.moveFrom = placement.group.position.clone();
placement.group.userData.moveTo = new THREE.Vector3(position.x, 0.09, position.z);
placement.group.userData.moveStart = performance.now();
selectedPlacementKey = cellKey;
movePlacementKey = null;
updateUI();
showToast(`${ITEMS[placement.itemId].name} moved to ${cellName(cellKey)}`, "success");
}
function selectPlacedItem(cellKey) {
selectedItemId = null;
selectedPlacementKey = cellKey;
movePlacementKey = null;
updateUI();
}
function removeSelectedPlacement() {
if (!selectedPlacementKey || !placements.has(selectedPlacementKey)) return;
const placement = placements.get(selectedPlacementKey);
const name = ITEMS[placement.itemId].name;
scene.remove(placement.group);
placements.delete(selectedPlacementKey);
selectedPlacementKey = null;
movePlacementKey = null;
updateUI();
showToast(`${name} removed from the bench`);
}
function clearBench() {
for (const placement of placements.values()) {
scene.remove(placement.group);
}
placements.clear();
selectedItemId = null;
selectedPlacementKey = null;
movePlacementKey = null;
updateUI();
showToast("Bench cleared");
}
function archiveCurrentSet() {
if (placements.size < 2) {
showToast("Add at least two modules before archiving", "error");
return;
}
const itemIds = [...placements.values()].map((placement) => placement.itemId);
const setNumber = archivedSets.length + 1;
archivedSets.push({
name: `SET ${String(setNumber).padStart(2, "0")}`,
items: itemIds
});
for (const placement of placements.values()) {
scene.remove(placement.group);
}
placements.clear();
selectedItemId = null;
selectedPlacementKey = null;
movePlacementKey = null;
updateUI();
showToast(`Set ${String(setNumber).padStart(2, "0")} archived · all constraints clear`, "success");
}
// -------------------------------------------------------------------------
// Pointer picking and direct camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function getCellAt(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(cellTargets, false);
return intersections.length ? intersections[0].object.userData.cellKey : null;
}
function updateHover(clientX, clientY) {
const cellKey = getCellAt(clientX, clientY);
if (!cellKey) {
hoverMarker.visible = false;
$("#cellReadout").textContent = "CELL —";
return;
}
const position = cellPosition(cellKey);
hoverMarker.position.set(position.x, 0.115, position.z);
hoverMarker.visible = true;
hoverMarker.material.color.setHex(movePlacementKey ? 0x63d69a : 0x61e5ff);
$("#cellReadout").textContent = `CELL ${cellName(cellKey)}`;
}
function handleCellClick(cellKey) {
if (!cellKey) return;
if (movePlacementKey) {
attemptMove(cellKey);
return;
}
if (selectedItemId) {
attemptPlace(selectedItemId, cellKey);
return;
}
if (placements.has(cellKey)) {
selectPlacedItem(cellKey);
return;
}
selectedPlacementKey = null;
updateUI();
}
let pointerState = null;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
canvas.setPointerCapture(event.pointerId);
pointerState = {
id: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
distance: 0,
mode: event.button === 2 ? "pan" : "orbit"
};
canvas.classList.add("orbiting");
});
canvas.addEventListener("pointermove", (event) => {
updateHover(event.clientX, event.clientY);
if (!pointerState || pointerState.id !== event.pointerId) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.distance += Math.hypot(dx, dy);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
if (pointerState.mode === "orbit") {
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(orbit.pitch + dy * 0.005, 0.34, 1.22);
} else {
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
direction.y = 0;
direction.normalize();
const right = new THREE.Vector3().crossVectors(direction, camera.up).normalize();
orbit.target.addScaledVector(right, -dx * 0.012);
orbit.target.addScaledVector(direction, -dy * 0.012);
}
});
canvas.addEventListener("pointerup", (event) => {
if (!pointerState || pointerState.id !== event.pointerId) return;
const wasClick = pointerState.distance < 6;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
pointerState = null;
canvas.classList.remove("orbiting");
if (wasClick && event.button === 0) {
const cellKey = getCellAt(event.clientX, event.clientY);
handleCellClick(cellKey);
}
});
canvas.addEventListener("pointercancel", () => {
pointerState = null;
canvas.classList.remove("orbiting");
});
canvas.addEventListener("pointerleave", () => {
if (!pointerState) {
hoverMarker.visible = false;
$("#cellReadout").textContent = "CELL —";
}
});
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
orbit.distance = THREE.MathUtils.clamp(
orbit.distance * Math.exp(event.deltaY * 0.001),
6.5,
18
);
}, { passive: false });
canvas.addEventListener("dragover", (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
updateHover(event.clientX, event.clientY);
});
canvas.addEventListener("drop", (event) => {
event.preventDefault();
const itemId = event.dataTransfer.getData("text/plain");
const cellKey = getCellAt(event.clientX, event.clientY);
if (ITEMS[itemId] && cellKey) {
attemptPlace(itemId, cellKey);
}
});
window.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
selectedItemId = null;
selectedPlacementKey = null;
movePlacementKey = null;
updateUI();
}
});
function updateCamera() {
const cosPitch = Math.cos(orbit.pitch);
camera.position.set(
orbit.target.x + orbit.distance * cosPitch * Math.sin(orbit.yaw),
orbit.target.y + orbit.distance * Math.sin(orbit.pitch),
orbit.target.z + orbit.distance * cosPitch * Math.cos(orbit.yaw)
);
camera.lookAt(orbit.target);
}
let firstResize = true;
function resizeRenderer() {
const width = Math.max(1, sceneWrap.clientWidth);
const height = Math.max(1, sceneWrap.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
if (firstResize) {
if (camera.aspect < 1) {
orbit.distance = 13.5;
}
firstResize = false;
}
camera.updateProjectionMatrix();
updateCamera();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(sceneWrap);
// -------------------------------------------------------------------------
// Buttons and animation
// -------------------------------------------------------------------------
$("#clearButton").addEventListener("click", clearBench);
$("#archiveButton").addEventListener("click", archiveCurrentSet);
$("#removePieceButton").addEventListener("click", removeSelectedPlacement);
$("#movePieceButton").addEventListener("click", () => {
if (!selectedPlacementKey) return;
if (movePlacementKey) {
movePlacementKey = null;
showToast("Move cancelled");
} else {
movePlacementKey = selectedPlacementKey;
showToast("Choose a destination cell on the bench");
}
updateUI();
});
renderRules();
updateUI();
resizeRenderer();
function animate(now) {
requestAnimationFrame(animate);
for (const placement of placements.values()) {
const group = placement.group;
if (group.userData.spawnTime) {
const elapsed = now - group.userData.spawnTime;
const progress = Math.min(elapsed / 320, 1);
const eased = 1 - Math.pow(1 - progress, 3);
const scale = 0.72 + eased * 0.28;
group.scale.setScalar(scale);
if (progress >= 1) {
group.scale.setScalar(1);
delete group.userData.spawnTime;
}
}
if (group.userData.moveFrom && group.userData.moveTo) {
const elapsed = now - group.userData.moveStart;
const progress = Math.min(elapsed / 240, 1);
const eased = 1 - Math.pow(1 - progress, 3);
group.position.lerpVectors(
group.userData.moveFrom,
group.userData.moveTo,
eased
);
if (progress >= 1) {
group.position.copy(group.userData.moveTo);
delete group.userData.moveFrom;
delete group.userData.moveTo;
}
}
const outline = group.userData.outline;
if (outline?.visible) {
outline.material.opacity = 0.55 + Math.sin(now * 0.006) * 0.18;
}
}
updateCamera();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```