Prompt specification
Build or customize the Three.js 3D scene "Game loot sampling teaching scene" 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: Game loot sampling teaching scene
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/game-loot-sampling-teaching-scene-x1803
Scene Description Prompt:
Compose fictional item chests using independent draws and finite-stock draws in separate modes; distinguish repeated probability from depletion of available outcomes. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Working Three.js Starter (game-loot-sampling-teaching-scene-x1803):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chest Forge — Voxel Loot Laboratory</title>
<style>
:root {
--bg: #090d18;
--panel: rgba(14, 19, 32, 0.92);
--panel-solid: #111827;
--line: rgba(170, 196, 230, 0.14);
--text: #eef5ff;
--muted: #8e9bb0;
--accent: #75dcff;
--accent-rgb: 117, 220, 255;
--danger: #ff7285;
--radius: 18px;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
--sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: var(--sans);
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas.dragging {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 38% 45%, transparent 20%, rgba(4, 7, 14, 0.24) 72%),
linear-gradient(180deg, rgba(5, 8, 16, 0.18), rgba(5, 8, 16, 0.42));
z-index: 1;
}
.topbar {
position: fixed;
z-index: 10;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.45);
}
.brand-mark {
display: grid;
place-items: center;
width: 42px;
height: 42px;
border: 1px solid rgba(var(--accent-rgb), 0.5);
border-radius: 12px;
color: var(--accent);
background: rgba(9, 15, 28, 0.78);
box-shadow:
0 0 24px rgba(var(--accent-rgb), 0.12),
inset 0 0 18px rgba(var(--accent-rgb), 0.06);
font-size: 23px;
}
.brand small,
.brand strong {
display: block;
}
.brand small {
margin-bottom: 2px;
color: var(--accent);
font: 700 9px/1 var(--mono);
letter-spacing: 0.22em;
}
.brand strong {
font-size: 18px;
letter-spacing: 0.12em;
}
.top-status {
display: flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(10, 15, 27, 0.76);
backdrop-filter: blur(14px);
color: var(--muted);
font: 700 10px/1 var(--mono);
letter-spacing: 0.12em;
}
.top-status .signal {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 12px var(--accent);
}
#modeBadge {
color: var(--accent);
}
.panel {
position: fixed;
z-index: 20;
top: 82px;
right: 22px;
bottom: 22px;
width: 382px;
padding: 18px;
overflow-y: auto;
border: 1px solid var(--line);
border-radius: var(--radius);
background:
linear-gradient(180deg, rgba(var(--accent-rgb), 0.035), transparent 160px),
var(--panel);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.42),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(22px);
scrollbar-width: thin;
scrollbar-color: rgba(var(--accent-rgb), 0.35) transparent;
}
.panel::-webkit-scrollbar {
width: 5px;
}
.panel::-webkit-scrollbar-thumb {
border-radius: 10px;
background: rgba(var(--accent-rgb), 0.3);
}
.eyebrow {
margin: 0 0 7px;
color: var(--accent);
font: 700 9px/1 var(--mono);
letter-spacing: 0.18em;
text-transform: uppercase;
}
.panel h1 {
margin: 0;
font-size: 22px;
letter-spacing: -0.03em;
}
.panel-intro {
margin: 8px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.field-label {
display: block;
margin-bottom: 7px;
color: #a9b6c9;
font: 700 9px/1 var(--mono);
letter-spacing: 0.12em;
text-transform: uppercase;
}
.name-field {
width: 100%;
height: 42px;
padding: 0 13px;
border: 1px solid var(--line);
border-radius: 10px;
outline: none;
color: var(--text);
background: rgba(3, 7, 15, 0.5);
font-weight: 650;
transition: border-color 160ms, box-shadow 160ms;
}
.name-field:focus {
border-color: rgba(var(--accent-rgb), 0.55);
box-shadow: 0 0 0 3px rgba(var(--accent-rgb), 0.07);
}
.mode-switch {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-top: 15px;
padding: 5px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(2, 5, 12, 0.46);
}
.mode-switch button {
min-height: 48px;
padding: 8px;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: var(--muted);
cursor: pointer;
transition: 160ms ease;
}
.mode-switch button strong,
.mode-switch button small {
display: block;
}
.mode-switch button strong {
margin-bottom: 4px;
font-size: 11px;
}
.mode-switch button small {
font: 9px/1.2 var(--mono);
opacity: 0.76;
}
.mode-switch button[aria-pressed="true"] {
border-color: rgba(var(--accent-rgb), 0.35);
color: var(--accent);
background: rgba(var(--accent-rgb), 0.1);
box-shadow: inset 0 0 18px rgba(var(--accent-rgb), 0.035);
}
.mode-explainer {
margin-top: 10px;
padding: 13px;
border: 1px solid rgba(var(--accent-rgb), 0.17);
border-radius: 12px;
background: rgba(var(--accent-rgb), 0.055);
}
.mode-explainer strong {
display: block;
margin-bottom: 5px;
font-size: 12px;
}
.mode-explainer p {
margin: 0;
color: #a9b5c7;
font-size: 11px;
line-height: 1.5;
}
.formula {
display: block;
margin-top: 9px;
padding-top: 8px;
border-top: 1px dashed rgba(var(--accent-rgb), 0.2);
color: var(--accent);
font: 10px/1.4 var(--mono);
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
margin: 18px 0 9px;
}
.section-head h2 {
margin: 0;
font: 700 10px/1 var(--mono);
letter-spacing: 0.14em;
text-transform: uppercase;
}
.add-button {
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 7px;
background: rgba(255, 255, 255, 0.025);
color: var(--muted);
cursor: pointer;
font: 700 9px/1 var(--mono);
}
.add-button:hover {
border-color: rgba(var(--accent-rgb), 0.38);
color: var(--accent);
}
.loot-list {
display: grid;
gap: 7px;
}
.loot-row {
display: grid;
grid-template-columns: 36px minmax(0, 1fr) 68px 20px;
gap: 8px;
align-items: center;
min-height: 67px;
padding: 9px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.022);
transition: border-color 160ms, opacity 160ms;
}
.loot-row:hover {
border-color: rgba(var(--accent-rgb), 0.2);
}
.loot-row.depleted {
opacity: 0.48;
}
.loot-icon {
display: grid;
place-items: center;
width: 36px;
height: 36px;
border: 1px solid color-mix(in srgb, var(--item-color), transparent 55%);
border-radius: 9px;
color: var(--item-color);
background: color-mix(in srgb, var(--item-color), transparent 88%);
box-shadow: inset 0 0 14px color-mix(in srgb, var(--item-color), transparent 91%);
font-size: 18px;
}
.loot-main {
min-width: 0;
}
.item-name {
width: 100%;
padding: 0;
border: 0;
outline: none;
color: #e9f1fb;
background: transparent;
font-size: 11px;
font-weight: 650;
}
.item-name:focus {
color: var(--accent);
}
.item-meta {
display: flex;
align-items: center;
gap: 7px;
margin-top: 7px;
}
.item-meta span:first-child {
min-width: 94px;
color: var(--muted);
font: 8px/1 var(--mono);
}
.mini-bar {
width: 100%;
height: 3px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
.mini-bar i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--item-color);
box-shadow: 0 0 8px var(--item-color);
transition: width 220ms ease;
}
.amount-wrap {
display: grid;
gap: 4px;
}
.amount-wrap input {
width: 68px;
height: 31px;
padding: 0 6px;
border: 1px solid var(--line);
border-radius: 7px;
outline: none;
color: var(--text);
background: rgba(2, 6, 13, 0.55);
text-align: center;
font: 700 11px/1 var(--mono);
}
.amount-wrap input:focus {
border-color: rgba(var(--accent-rgb), 0.45);
}
.amount-unit {
color: #68758a;
text-align: center;
font: 7px/1 var(--mono);
letter-spacing: 0.08em;
text-transform: uppercase;
}
.remove-button {
width: 20px;
height: 25px;
padding: 0;
border: 0;
background: transparent;
color: #596579;
cursor: pointer;
font-size: 16px;
}
.remove-button:hover {
color: var(--danger);
}
.empty-loot {
padding: 22px;
border: 1px dashed var(--line);
border-radius: 11px;
color: var(--muted);
text-align: center;
font-size: 11px;
}
.pool-status {
margin-top: 9px;
color: var(--muted);
font: 9px/1.45 var(--mono);
}
.pool-status.valid {
color: rgba(var(--accent-rgb), 0.8);
}
.pool-status.invalid {
color: #ff9ba8;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 16px;
}
.stat {
min-height: 63px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.022);
}
.stat span,
.stat strong {
display: block;
}
.stat span {
margin-bottom: 7px;
color: #718096;
font: 8px/1 var(--mono);
letter-spacing: 0.11em;
text-transform: uppercase;
}
.stat strong {
font: 700 19px/1 var(--mono);
}
.stat strong.accent {
color: var(--accent);
}
.actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 16px;
}
.open-button,
.reset-button {
height: 48px;
border-radius: 10px;
cursor: pointer;
font: 800 10px/1 var(--mono);
letter-spacing: 0.1em;
text-transform: uppercase;
transition: transform 130ms, filter 130ms, opacity 130ms;
}
.open-button {
border: 1px solid rgba(var(--accent-rgb), 0.6);
color: #07111b;
background: var(--accent);
box-shadow: 0 8px 26px rgba(var(--accent-rgb), 0.18);
}
.open-button:hover:not(:disabled) {
filter: brightness(1.08);
transform: translateY(-1px);
}
.open-button:active:not(:disabled) {
transform: translateY(1px);
}
.open-button:disabled {
cursor: not-allowed;
opacity: 0.34;
}
.reset-button {
padding: 0 14px;
border: 1px solid var(--line);
color: var(--muted);
background: rgba(255, 255, 255, 0.03);
}
.reset-button:hover {
color: var(--text);
border-color: rgba(255, 255, 255, 0.24);
}
.ledger {
position: fixed;
z-index: 12;
left: 22px;
bottom: 22px;
width: 292px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(10, 15, 27, 0.78);
box-shadow: 0 14px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
pointer-events: none;
}
.ledger-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
}
.ledger-head strong {
font: 800 9px/1 var(--mono);
letter-spacing: 0.14em;
}
.ledger-head span {
color: var(--accent);
font: 8px/1 var(--mono);
}
.history-list {
display: grid;
gap: 4px;
margin: 0;
padding: 0;
list-style: none;
}
.history-list li {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
min-height: 31px;
padding: 5px 7px;
border-radius: 7px;
background: rgba(255, 255, 255, 0.025);
}
.history-item {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
}
.history-dot {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 2px;
background: var(--history-color);
box-shadow: 0 0 8px var(--history-color);
}
.history-name {
overflow: hidden;
color: #d9e5f3;
font-size: 10px;
font-weight: 650;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-detail {
flex: 0 0 auto;
color: #748197;
font: 8px/1 var(--mono);
}
.history-empty {
padding: 10px 4px;
color: #667287;
font: 9px/1.4 var(--mono);
}
.controls-hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 21px;
transform: translateX(-50%);
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
color: rgba(191, 205, 224, 0.6);
background: rgba(7, 11, 20, 0.55);
font: 8px/1 var(--mono);
letter-spacing: 0.08em;
pointer-events: none;
}
#lootLabel {
position: fixed;
z-index: 30;
top: 0;
left: 0;
display: flex;
align-items: center;
gap: 7px;
padding: 8px 11px;
border: 1px solid rgba(var(--accent-rgb), 0.45);
border-radius: 9px;
opacity: 0;
color: var(--text);
background: rgba(8, 13, 24, 0.92);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.35);
transform: translate(-50%, -110%);
transition: opacity 100ms;
pointer-events: none;
font-size: 11px;
font-weight: 700;
white-space: nowrap;
}
#lootLabel span {
color: var(--accent);
font-size: 16px;
}
#toast {
position: fixed;
z-index: 40;
top: 80px;
left: 50%;
max-width: min(420px, calc(100vw - 40px));
padding: 10px 14px;
border: 1px solid rgba(var(--accent-rgb), 0.28);
border-radius: 10px;
opacity: 0;
color: #dfeaf8;
background: rgba(9, 14, 25, 0.94);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
transform: translate(-50%, -12px);
transition: 180ms ease;
pointer-events: none;
font: 10px/1.4 var(--mono);
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
.topbar {
top: 14px;
left: 14px;
right: 14px;
}
.brand-mark {
width: 36px;
height: 36px;
}
.brand strong {
font-size: 14px;
}
.top-status {
padding: 8px 10px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 52vh;
padding: 14px;
}
.ledger {
top: 68px;
bottom: auto;
left: 10px;
width: 225px;
max-height: 185px;
overflow: hidden;
}
.ledger .history-list li:nth-child(n + 4) {
display: none;
}
.controls-hint {
display: none;
}
#toast {
top: 63px;
}
}
@media (max-width: 520px) {
.brand small {
display: none;
}
.brand strong {
font-size: 12px;
}
.top-status {
font-size: 8px;
}
.ledger {
width: 190px;
}
.loot-row {
grid-template-columns: 32px minmax(0, 1fr) 60px 17px;
gap: 6px;
padding: 7px;
}
.loot-icon {
width: 32px;
height: 32px;
}
.amount-wrap input {
width: 60px;
}
}
</style>
</head>
<body data-mode="independent">
<div id="scene"></div>
<div class="vignette"></div>
<header class="topbar">
<div class="brand">
<span class="brand-mark">▦</span>
<div>
<small>VOXEL LOOT LABORATORY</small>
<strong>CHEST FORGE</strong>
</div>
</div>
<div class="top-status">
<span class="signal"></span>
<span id="modeBadge">INDEPENDENT ENGINE</span>
</div>
</header>
<aside class="panel">
<p class="eyebrow">Chest composition</p>
<h1>Design your loot table</h1>
<p class="panel-intro">
Build a fictional chest, then test whether its outcomes repeat forever
or disappear from a finite pool.
</p>
<label class="field-label" for="chestName">Chest designation</label>
<input
id="chestName"
class="name-field"
value="Astral Reliquary"
maxlength="42"
autocomplete="off"
/>
<div class="mode-switch" role="group" aria-label="Loot draw model">
<button id="independentMode" type="button" aria-pressed="true">
<strong>Independent</strong>
<small>PROBABILITY REPEATS</small>
</button>
<button id="finiteMode" type="button" aria-pressed="false">
<strong>Finite stock</strong>
<small>OUTCOMES DEPLETE</small>
</button>
</div>
<div class="mode-explainer">
<strong id="copyTitle"></strong>
<p id="copyText"></p>
<code id="copyFormula" class="formula"></code>
</div>
<div class="section-head">
<h2>Loot composition</h2>
<button id="addItem" class="add-button" type="button">+ ADD OUTCOME</button>
</div>
<div id="lootList" class="loot-list"></div>
<div id="poolStatus" class="pool-status"></div>
<div class="stats">
<div class="stat">
<span>Total rolls</span>
<strong id="statRolls">0</strong>
</div>
<div class="stat">
<span>Unique finds</span>
<strong id="statUnique">0</strong>
</div>
<div class="stat">
<span>Duplicate finds</span>
<strong id="statDuplicates">0</strong>
</div>
<div class="stat">
<span id="statPoolLabel">Depletion</span>
<strong id="statPool" class="accent">∞</strong>
</div>
</div>
<div class="actions">
<button id="openChest" class="open-button" type="button">Open chest</button>
<button id="resetChest" class="reset-button" type="button">Reset</button>
</div>
</aside>
<section class="ledger">
<div class="ledger-head">
<strong>LIVE LEDGER</strong>
<span id="ledgerMode">FIXED ODDS</span>
</div>
<ol id="historyList" class="history-list"></ol>
</section>
<div class="controls-hint">DRAG TO ORBIT · SCROLL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
<div id="lootLabel"><span></span><strong></strong></div>
<div id="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// State
// -------------------------------------------------------------------------
const CHEST_X = -1.6;
const state = {
mode: "independent",
chestName: "Astral Reliquary",
rolling: false,
animationToken: 0,
history: [],
remaining: {},
items: [
{
id: "moon-shard",
name: "Moon Shard",
icon: "◈",
color: "#79ddff",
chance: 50,
stock: 3
},
{
id: "ember-sigil",
name: "Ember Sigil",
icon: "◆",
color: "#ff805e",
chance: 30,
stock: 2
},
{
id: "whisper-ink",
name: "Whisper Ink",
icon: "❖",
color: "#b69cff",
chance: 15,
stock: 1
},
{
id: "void-pearl",
name: "Void Pearl",
icon: "●",
color: "#ffe38a",
chance: 5,
stock: 1
}
]
};
const el = {
chestName: document.querySelector("#chestName"),
independentMode: document.querySelector("#independentMode"),
finiteMode: document.querySelector("#finiteMode"),
modeBadge: document.querySelector("#modeBadge"),
copyTitle: document.querySelector("#copyTitle"),
copyText: document.querySelector("#copyText"),
copyFormula: document.querySelector("#copyFormula"),
lootList: document.querySelector("#lootList"),
addItem: document.querySelector("#addItem"),
poolStatus: document.querySelector("#poolStatus"),
statRolls: document.querySelector("#statRolls"),
statUnique: document.querySelector("#statUnique"),
statDuplicates: document.querySelector("#statDuplicates"),
statPool: document.querySelector("#statPool"),
statPoolLabel: document.querySelector("#statPoolLabel"),
openChest: document.querySelector("#openChest"),
resetChest: document.querySelector("#resetChest"),
historyList: document.querySelector("#historyList"),
ledgerMode: document.querySelector("#ledgerMode"),
lootLabel: document.querySelector("#lootLabel"),
toast: document.querySelector("#toast")
};
const palette = [
["◈", "#79ddff"],
["◆", "#ff805e"],
["❖", "#b69cff"],
["●", "#ffe38a"],
["✦", "#70f0b2"],
["⬟", "#ff72b5"],
["✧", "#d8e6f7"],
["☾", "#9b91ff"]
];
const relicNames = [
"Dream Shard",
"Copper Rune",
"Frost Compass",
"Sunken Crown",
"Prism Seed",
"Clockwork Eye"
];
function initializeRemaining() {
state.remaining = Object.fromEntries(
state.items.map(item => [item.id, item.stock])
);
}
initializeRemaining();
function formatNumber(value) {
const rounded = Math.round(value * 100) / 100;
return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
}
function chanceTotal() {
return state.items.reduce((sum, item) => sum + item.chance, 0);
}
function remainingTotal() {
return state.items.reduce(
(sum, item) => sum + (state.remaining[item.id] || 0),
0
);
}
function weightedPick(weights) {
const total = weights.reduce((sum, value) => sum + value, 0);
let roll = Math.random() * total;
for (let i = 0; i < weights.length; i++) {
roll -= weights[i];
if (roll <= 0) return i;
}
return weights.findIndex(value => value > 0);
}
let toastTimer = 0;
function showToast(message) {
el.toast.textContent = message;
el.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.toast.classList.remove("show"), 2400);
}
// -------------------------------------------------------------------------
// Interface
// -------------------------------------------------------------------------
function renderLoot() {
el.lootList.replaceChildren();
if (!state.items.length) {
const empty = document.createElement("div");
empty.className = "empty-loot";
empty.textContent = "No outcomes in this chest. Add an item to begin.";
el.lootList.appendChild(empty);
updateInterface();
return;
}
for (const item of state.items) {
const row = document.createElement("div");
row.className = "loot-row";
row.dataset.id = item.id;
row.style.setProperty("--item-color", item.color);
row.innerHTML = `
<div class="loot-icon"></div>
<div class="loot-main">
<input class="item-name" maxlength="28" autocomplete="off" />
<div class="item-meta">
<span></span>
<div class="mini-bar"><i></i></div>
</div>
</div>
<div class="amount-wrap">
<input class="amount" type="number" min="0" />
<span class="amount-unit"></span>
</div>
<button class="remove-button" type="button" title="Remove outcome" aria-label="Remove outcome">×</button>
`;
const icon = row.querySelector(".loot-icon");
const nameInput = row.querySelector(".item-name");
const amountInput = row.querySelector(".amount");
const removeButton = row.querySelector(".remove-button");
icon.textContent = item.icon;
nameInput.value = item.name;
if (state.mode === "independent") {
amountInput.step = "1";
amountInput.max = "100";
} else {
amountInput.step = "1";
amountInput.max = "999";
}
nameInput.addEventListener("input", () => {
item.name = nameInput.value.trim() || "Unnamed Relic";
updateSceneSign();
renderHistory();
});
amountInput.addEventListener("input", () => {
let value = Number.parseFloat(amountInput.value);
if (!Number.isFinite(value) || value < 0) value = 0;
if (state.mode === "independent") {
item.chance = Math.min(100, Math.round(value * 10) / 10);
} else {
item.stock = Math.min(999, Math.round(value));
state.remaining[item.id] = item.stock;
}
updateInterface();
});
amountInput.addEventListener("blur", () => {
amountInput.value =
state.mode === "independent" ? item.chance : item.stock;
});
removeButton.addEventListener("click", () => {
state.items = state.items.filter(candidate => candidate.id !== item.id);
delete state.remaining[item.id];
renderLoot();
});
el.lootList.appendChild(row);
}
updateInterface();
}
function updateLootVisuals() {
const totalChance = chanceTotal();
const totalRemaining = remainingTotal();
for (const row of el.lootList.querySelectorAll(".loot-row")) {
const item = state.items.find(candidate => candidate.id === row.dataset.id);
if (!item) continue;
const meta = row.querySelector(".item-meta span");
const bar = row.querySelector(".mini-bar i");
const amountInput = row.querySelector(".amount");
const unit = row.querySelector(".amount-unit");
if (state.mode === "independent") {
const percent = totalChance > 0 ? (item.chance / totalChance) * 100 : 0;
meta.textContent = `${formatNumber(item.chance)}% fixed`;
bar.style.width = `${percent}%`;
unit.textContent = "% chance";
amountInput.title = "Fixed chance in percent";
row.classList.remove("depleted");
} else {
const left = state.remaining[item.id] || 0;
const percent = totalRemaining > 0 ? (left / totalRemaining) * 100 : 0;
meta.textContent = left
? `${left} left · ${formatNumber(percent)}% now`
: "depleted";
bar.style.width = `${percent}%`;
unit.textContent = "stock";
amountInput.title = "Physical copies in the starting pool";
row.classList.toggle("depleted", left === 0);
}
}
}
function updateStats() {
const rolls = state.history.length;
const unique = new Set(state.history.map(entry => entry.id)).size;
const duplicates = rolls - unique;
const left = remainingTotal();
el.statRolls.textContent = rolls;
el.statUnique.textContent = unique;
el.statDuplicates.textContent = duplicates;
if (state.mode === "independent") {
el.statPoolLabel.textContent = "Depletion";
el.statPool.textContent = "∞";
} else {
el.statPoolLabel.textContent = "Copies left";
el.statPool.textContent = left;
}
}
function updateValidation() {
let valid = true;
let message = "";
let invalid = false;
if (state.mode === "independent") {
const total = chanceTotal();
valid = state.items.length > 0 && Math.abs(total - 100) < 0.001;
if (valid) {
message = "Fixed weights total 100%. Rolls never consume inventory.";
} else {
invalid = true;
message = `Weights total ${formatNumber(total)}%. Adjust the table to exactly 100%.`;
}
} else {
const total = remainingTotal();
valid = state.items.length > 0 && total > 0;
if (valid) {
message = `${total} physical copies remain. Odds rebalance after every draw.`;
} else {
invalid = true;
message = "Pool depleted. Restock the chest to continue.";
}
}
el.poolStatus.textContent = message;
el.poolStatus.classList.toggle("valid", valid);
el.poolStatus.classList.toggle("invalid", invalid);
el.openChest.disabled = !valid || state.rolling;
el.openChest.textContent = state.rolling ? "Rolling…" : "Open chest";
el.resetChest.textContent = state.mode === "finite" ? "Restock" : "Reset";
}
function renderHistory() {
el.historyList.replaceChildren();
if (!state.history.length) {
const empty = document.createElement("li");
empty.className = "history-empty";
empty.textContent = "No rolls recorded. Open the chest to begin.";
el.historyList.appendChild(empty);
return;
}
for (const entry of state.history.slice(0, 7)) {
const row = document.createElement("li");
const item = document.createElement("div");
item.className = "history-item";
const dot = document.createElement("span");
dot.className = "history-dot";
dot.style.setProperty("--history-color", entry.color);
const name = document.createElement("span");
name.className = "history-name";
name.textContent = entry.name;
item.append(dot, name);
const detail = document.createElement("span");
detail.className = "history-detail";
if (state.mode === "independent") {
detail.textContent = `${formatNumber(entry.chanceBefore)}% fixed`;
} else {
detail.textContent = `${entry.remainingBefore}→${entry.remainingAfter} · ${formatNumber(entry.chanceBefore)}%`;
}
row.append(item, detail);
el.historyList.appendChild(row);
}
}
function updateModeInterface() {
const independent = state.mode === "independent";
const accent = independent ? "#75dcff" : "#ffb45f";
const accentRgb = independent ? "117, 220, 255" : "255, 180, 95";
document.documentElement.style.setProperty("--accent", accent);
document.documentElement.style.setProperty("--accent-rgb", accentRgb);
document.body.dataset.mode = state.mode;
el.independentMode.setAttribute("aria-pressed", String(independent));
el.finiteMode.setAttribute("aria-pressed", String(!independent));
el.modeBadge.textContent = independent ? "INDEPENDENT ENGINE" : "FINITE STOCK ENGINE";
el.ledgerMode.textContent = independent ? "FIXED ODDS" : "DEPLETING POOL";
if (independent) {
el.copyTitle.textContent = "Every roll starts from the same table";
el.copyText.textContent =
"A miss does not weaken the next roll. A 25% outcome remains 25% whether it appears on roll one, roll ten, or roll one hundred.";
el.copyFormula.textContent = "P(item) = fixed chance ÷ 100";
} else {
el.copyTitle.textContent = "Each draw consumes a physical outcome";
el.copyText.textContent =
"Opening the chest removes one copy from the pool. As rare copies disappear, the odds of the remaining outcomes rise automatically.";
el.copyFormula.textContent = "P(item) = copies left ÷ total copies left";
}
updateSceneMode();
updateSceneSign();
}
function updateInterface() {
updateLootVisuals();
updateStats();
updateValidation();
renderHistory();
}
function setMode(mode) {
if (state.mode === mode) return;
state.mode = mode;
if (mode === "finite" && !Object.keys(state.remaining).length) {
initializeRemaining();
}
updateModeInterface();
renderLoot();
}
function addItem() {
if (state.items.length >= 8) {
showToast("This forge supports up to eight distinct outcomes.");
return;
}
const index = state.items.length;
const [icon, color] = palette[index % palette.length];
const id = `relic-${Date.now()}-${index}`;
state.items.push({
id,
name: relicNames[index % relicNames.length],
icon,
color,
chance: 0,
stock: 1
});
state.remaining[id] = 1;
renderLoot();
requestAnimationFrame(() => {
const rows = el.lootList.querySelectorAll(".loot-row");
const last = rows[rows.length - 1];
last?.querySelector(".item-name")?.focus();
last?.scrollIntoView({ behavior: "smooth", block: "nearest" });
});
}
function openChest() {
if (state.rolling) return;
if (state.mode === "independent") {
if (Math.abs(chanceTotal() - 100) > 0.001) {
showToast("The independent loot table must total exactly 100%.");
return;
}
} else if (remainingTotal() <= 0) {
showToast("The finite pool is empty. Restock it first.");
return;
}
const token = ++state.animationToken;
state.rolling = true;
updateValidation();
const weights =
state.mode === "independent"
? state.items.map(item => item.chance)
: state.items.map(item => state.remaining[item.id] || 0);
const index = weightedPick(weights);
const item = state.items[index];
const totalBefore =
state.mode === "independent" ? chanceTotal() : remainingTotal();
const weightBefore = weights[index];
const probabilityBefore = totalBefore
? (weightBefore / totalBefore) * 100
: 0;
const remainingBefore =
state.mode === "finite" ? state.remaining[item.id] || 0 : null;
if (state.mode === "finite") {
state.remaining[item.id] = Math.max(0, remainingBefore - 1);
}
state.history.unshift({
id: item.id,
name: item.name,
icon: item.icon,
color: item.color,
number: state.history.length + 1,
chanceBefore: probabilityBefore,
remainingBefore,
remainingAfter:
state.mode === "finite" ? state.remaining[item.id] : null
});
updateInterface();
setTimeout(() => {
if (token === state.animationToken) spawnLoot(item);
}, 260);
setTimeout(() => {
if (token !== state.animationToken) return;
state.rolling = false;
updateValidation();
}, 900);
}
function resetChest() {
state.animationToken++;
state.rolling = false;
state.history = [];
if (state.mode === "finite") {
initializeRemaining();
showToast("The finite pool has been restocked.");
} else {
showToast("Roll history reset. Fixed probabilities were not changed.");
}
clearBurst();
updateInterface();
}
el.chestName.addEventListener("input", () => {
state.chestName = el.chestName.value.trim() || "Unnamed Chest";
updateSceneSign();
});
el.independentMode.addEventListener("click", () => setMode("independent"));
el.finiteMode.addEventListener("click", () => setMode("finite"));
el.addItem.addEventListener("click", addItem);
el.openChest.addEventListener("click", openChest);
el.resetChest.addEventListener("click", resetChest);
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const sceneHost = document.querySelector("#scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x090d18);
scene.fog = new THREE.Fog(0x090d18, 12, 28);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 1.05, 0);
let cameraYaw = 0.48;
let cameraPitch = 0.39;
let cameraDistance = 12.5;
function updateCamera() {
const horizontal = Math.cos(cameraPitch) * cameraDistance;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraDistance,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = 0.48;
cameraPitch = 0.39;
cameraDistance = 12.5;
updateCamera();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xa9d8ff, 0x241225, 1.8);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff0d7, 3.3);
keyLight.position.set(-4, 10, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const blueRim = new THREE.PointLight(0x4b9fff, 24, 12, 2);
blueRim.position.set(-5, 3.5, -3);
scene.add(blueRim);
const warmRim = new THREE.PointLight(0xff765a, 18, 10, 2);
warmRim.position.set(4, 2.8, 1);
scene.add(warmRim);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function makeMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.78,
metalness: options.metalness ?? 0.05,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
}
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
let seed = 19387;
function seededRandom() {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
}
// Voxel floor.
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95,
metalness: 0
});
const floorGeometry = new THREE.BoxGeometry(0.94, 0.18, 0.94);
const floor = new THREE.InstancedMesh(floorGeometry, floorMaterial, 19 * 19);
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
let floorIndex = 0;
for (let x = -9; x <= 9; x++) {
for (let z = -9; z <= 9; z++) {
matrix.makeTranslation(x, -0.09, z);
floor.setMatrixAt(floorIndex, matrix);
const rug = x > -5 && x < 2 && z > -3 && z < 3;
if (rug) {
color.setHex((x + z) % 2 === 0 ? 0x263958 : 0x20314e);
} else {
const variation = Math.floor(seededRandom() * 4);
color.setHex([0x171f2d, 0x192331, 0x151d2a, 0x1c2533][variation]);
}
floor.setColorAt(floorIndex, color);
floorIndex++;
}
}
floor.receiveShadow = true;
floor.instanceMatrix.needsUpdate = true;
floor.instanceColor.needsUpdate = true;
scene.add(floor);
// Back and side voxel walls.
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.92
});
const wallEntries = [];
for (let row = 0; row < 7; row++) {
for (let x = -9; x <= 9; x++) {
wallEntries.push({
position: [x, row * 0.76 + 0.38, -8.45],
scale: [0.93, 0.7, 0.52],
color: [0x182131, 0x1c2636, 0x202b3c][Math.floor(seededRandom() * 3)]
});
}
}
for (let row = 0; row < 7; row++) {
for (let z = -8; z <= 3; z++) {
wallEntries.push({
position: [-8.45, row * 0.76 + 0.38, z],
scale: [0.52, 0.7, 0.93],
color: [0x182131, 0x1c2636, 0x202b3c][Math.floor(seededRandom() * 3)]
});
}
}
const wall = new THREE.InstancedMesh(
unitBox,
wallMaterial,
wallEntries.length
);
wallEntries.forEach((entry, index) => {
matrix.compose(
new THREE.Vector3(...entry.position),
new THREE.Quaternion(),
new THREE.Vector3(...entry.scale)
);
wall.setMatrixAt(index, matrix);
wall.setColorAt(index, color.setHex(entry.color));
});
wall.receiveShadow = true;
wall.castShadow = true;
wall.instanceMatrix.needsUpdate = true;
wall.instanceColor.needsUpdate = true;
scene.add(wall);
// Shelves and colorful voxel books.
const woodDark = makeMaterial(0x3b2730, { roughness: 0.88 });
const woodMid = makeMaterial(0x5a3632, { roughness: 0.85 });
const metal = makeMaterial(0xc59648, {
roughness: 0.34,
metalness: 0.72
});
const metalDark = makeMaterial(0x55402c, {
roughness: 0.5,
metalness: 0.48
});
function addShelf(x, z, width) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
addBox(group, [width, 0.16, 0.65], [0, 2.35, 0], woodDark);
addBox(group, [width, 0.16, 0.65], [0, 3.35, 0], woodDark);
addBox(group, [0.16, 2.5, 0.65], [-width / 2, 2.8, 0], woodDark);
addBox(group, [0.16, 2.5, 0.65], [width / 2, 2.8, 0], woodDark);
const bookColors = [0x7f4b6d, 0x356b85, 0xa25a45, 0x5b6b4a, 0x6f5aa1];
for (let shelf = 0; shelf < 2; shelf++) {
let cursor = -width / 2 + 0.22;
while (cursor < width / 2 - 0.25) {
const widthBook = 0.12 + seededRandom() * 0.18;
const heightBook = 0.42 + seededRandom() * 0.48;
addBox(
group,
[widthBook, heightBook, 0.3],
[
cursor + widthBook / 2,
(shelf === 0 ? 2.35 : 3.35) + heightBook / 2,
0.02
],
makeMaterial(
bookColors[Math.floor(seededRandom() * bookColors.length)],
{ roughness: 0.9 }
)
);
cursor += widthBook + 0.035;
}
}
}
addShelf(-4.9, -7.72, 4.8);
addShelf(4.8, -7.72, 4.8);
function addCrystalPedestal(x, z, hexColor) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
addBox(group, [1.15, 0.3, 1.15], [0, 0.15, 0], metalDark);
addBox(group, [0.82, 0.22, 0.82], [0, 0.41, 0], metal);
const crystalMaterial = makeMaterial(hexColor, {
roughness: 0.32,
emissive: hexColor,
emissiveIntensity: 0.65
});
addBox(group, [0.32, 0.72, 0.32], [0, 0.86, 0], crystalMaterial);
addBox(group, [0.25, 0.42, 0.25], [0.27, 1.18, 0.03], crystalMaterial);
addBox(group, [0.2, 0.3, 0.2], [-0.24, 1.02, -0.03], crystalMaterial);
const light = new THREE.PointLight(hexColor, 5, 4, 2);
light.position.set(0, 1.15, 0);
group.add(light);
}
addCrystalPedestal(-5.2, -2.8, 0x5aaeff);
addCrystalPedestal(3.4, -3.8, 0xff765a);
addCrystalPedestal(4.7, 1.1, 0x9f7cff);
// Central pedestal.
const pedestal = new THREE.Group();
pedestal.position.set(CHEST_X, 0, 0);
scene.add(pedestal);
addBox(pedestal, [3.6, 0.3, 2.7], [0, 0.15, 0], metalDark);
addBox(pedestal, [3.25, 0.16, 2.35], [0, 0.38, 0], metal);
addBox(pedestal, [2.95, 0.08, 2.08], [0, 0.49, 0], metalDark);
// Voxel chest.
const chest = new THREE.Group();
chest.position.set(CHEST_X, 0.54, 0);
scene.add(chest);
const chestWood = makeMaterial(0x6e3f31, { roughness: 0.86 });
const chestWoodLight = makeMaterial(0x86503a, { roughness: 0.83 });
const chestWoodDark = makeMaterial(0x43272a, { roughness: 0.9 });
const chestMetal = makeMaterial(0xd3a64f, {
roughness: 0.3,
metalness: 0.72
});
addBox(chest, [2.8, 1.12, 1.78], [0, 0.57, 0], chestWoodDark);
for (let i = 0; i < 4; i++) {
addBox(
chest,
[0.61, 0.91, 0.1],
[-1.03 + i * 0.69, 0.56, 0.94],
i % 2 ? chestWood : chestWoodLight
);
}
addBox(chest, [0.17, 1.25, 1.92], [-0.92, 0.61, 0], chestMetal);
addBox(chest, [0.17, 1.25, 1.92], [0.92, 0.61, 0], chestMetal);
addBox(chest, [0.34, 0.43, 0.18], [0, 0.79, 1.01], chestMetal);
addBox(chest, [0.12, 0.2, 0.11], [0, 0.75, 1.15], chestWoodDark);
const lidPivot = new THREE.Group();
lidPivot.position.set(0, 1.16, -0.89);
chest.add(lidPivot);
addBox(lidPivot, [2.93, 0.47, 1.88], [0, 0.05, 0.89], chestWoodDark);
for (let i = 0; i < 5; i++) {
addBox(
lidPivot,
[0.49, 0.18, 1.92],
[-1.1 + i * 0.55, 0.32, 0.89],
i % 2 ? chestWood : chestWoodLight
);
}
addBox(lidPivot, [0.17, 0.58, 1.98], [-0.92, 0.09, 0.89], chestMetal);
addBox(lidPivot, [0.17, 0.58, 1.98], [0.92, 0.09, 0.89], chestMetal);
const modeCrystalMaterial = makeMaterial(0x75dcff, {
roughness: 0.22,
metalness: 0.15,
emissive: 0x75dcff,
emissiveIntensity: 1.15
});
const modeCrystal = addBox(
chest,
[0.25, 0.25, 0.12],
[0, 0.79, 1.15],
modeCrystalMaterial
);
const chestLight = new THREE.PointLight(0x75dcff, 4, 4.5, 2);
chestLight.position.set(0, 1.25, 0.7);
chest.add(chestLight);
// Ambient motes.
const motePositions = new Float32Array(150 * 3);
for (let i = 0; i < 150; i++) {
motePositions[i * 3] = (seededRandom() - 0.5) * 18;
motePositions[i * 3 + 1] = 0.4 + seededRandom() * 6;
motePositions[i * 3 + 2] = (seededRandom() - 0.5) * 16;
}
const moteGeometry = new THREE.BufferGeometry();
moteGeometry.setAttribute(
"position",
new THREE.BufferAttribute(motePositions, 3)
);
const moteMaterial = new THREE.PointsMaterial({
color: 0x9acfff,
size: 0.055,
transparent: true,
opacity: 0.55,
sizeAttenuation: true
});
const motes = new THREE.Points(moteGeometry, moteMaterial);
scene.add(motes);
// Floating in-world sign.
const signCanvas = document.createElement("canvas");
signCanvas.width = 1024;
signCanvas.height = 256;
const signContext = signCanvas.getContext("2d");
const signTexture = new THREE.CanvasTexture(signCanvas);
signTexture.colorSpace = THREE.SRGBColorSpace;
const signMaterial = new THREE.SpriteMaterial({
map: signTexture,
transparent: true,
depthWrite: false
});
const signSprite = new THREE.Sprite(signMaterial);
signSprite.position.set(CHEST_X, 3.75, -3.1);
signSprite.scale.set(4.2, 1.05, 1);
scene.add(signSprite);
function updateSceneSign() {
const name = (state.chestName || "UNNAMED CHEST").toUpperCase();
const mode = state.mode === "independent" ? "INDEPENDENT ENGINE" : "FINITE STOCK ENGINE";
const accent = state.mode === "independent" ? "#75dcff" : "#ffb45f";
signContext.clearRect(0, 0, signCanvas.width, signCanvas.height);
signContext.fillStyle = "rgba(7, 12, 23, 0.86)";
signContext.strokeStyle = accent;
signContext.lineWidth = 5;
signContext.beginPath();
signContext.roundRect(12, 12, 1000, 232, 30);
signContext.fill();
signContext.stroke();
signContext.textAlign = "center";
signContext.textBaseline = "middle";
signContext.fillStyle = "#eef7ff";
signContext.font = "800 61px monospace";
signContext.fillText(name.slice(0, 25), 512, 101);
signContext.fillStyle = accent;
signContext.font = "700 27px monospace";
signContext.fillText(mode, 512, 174);
signTexture.needsUpdate = true;
}
function updateSceneMode() {
const color = state.mode === "independent" ? 0x75dcff : 0xffb45f;
modeCrystalMaterial.color.setHex(color);
modeCrystalMaterial.emissive.setHex(color);
chestLight.color.setHex(color);
}
updateModeInterface();
updateSceneSign();
// -------------------------------------------------------------------------
// Loot burst animation
// -------------------------------------------------------------------------
let burst = null;
const lootLabelIcon = el.lootLabel.querySelector("span");
const lootLabelName = el.lootLabel.querySelector("strong");
function clearBurst() {
if (!burst) return;
scene.remove(burst.group);
burst.materials.forEach(material => material.dispose());
burst = null;
el.lootLabel.style.opacity = "0";
}
function spawnLoot(item) {
clearBurst();
const group = new THREE.Group();
group.position.set(CHEST_X, 2.2, 0.25);
scene.add(group);
const primary = makeMaterial(item.color, {
roughness: 0.38,
emissive: item.color,
emissiveIntensity: 0.45
});
const secondary = makeMaterial(0xf4fbff, {
roughness: 0.22,
emissive: item.color,
emissiveIntensity: 0.2
});
const cubes = [];
for (let i = 0; i < 11; i++) {
const cube = new THREE.Mesh(unitBox, i % 4 === 0 ? secondary : primary);
const size = 0.12 + Math.random() * 0.16;
cube.scale.setScalar(size);
cube.position.set(
(Math.random() - 0.5) * 0.8,
(Math.random() - 0.5) * 0.3,
(Math.random() - 0.5) * 0.55
);
cube.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
group.add(cube);
cubes.push({
mesh: cube,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 2.1,
0.8 + Math.random() * 1.8,
(Math.random() - 0.5) * 1.6
),
baseScale: size
});
}
burst = {
group,
cubes,
materials: [primary, secondary],
born: performance.now()
};
lootLabelIcon.textContent = item.icon;
lootLabelName.textContent = item.name;
el.lootLabel.style.opacity = "1";
}
// -------------------------------------------------------------------------
// Direct camera controls — no OrbitControls or addons
// -------------------------------------------------------------------------
const pointers = new Map();
let activePointer = null;
let previousPointer = { x: 0, y: 0 };
let previousPinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
activePointer = event.pointerId;
previousPointer = { x: event.clientX, y: event.clientY };
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
previousPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointers.has(event.pointerId)) return;
const old = pointers.get(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size >= 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (previousPinchDistance > 0) {
cameraDistance = THREE.MathUtils.clamp(
cameraDistance * (previousPinchDistance / Math.max(1, distance)),
7,
19
);
updateCamera();
}
previousPinchDistance = distance;
return;
}
if (event.pointerId !== activePointer) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
previousPointer = { x: event.clientX, y: event.clientY };
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + dy * 0.004,
0.17,
1.02
);
updateCamera();
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 0) {
activePointer = null;
previousPinchDistance = 0;
renderer.domElement.classList.remove("dragging");
} else if (pointers.size === 1) {
const [pointerId, pointer] = [...pointers.entries()][0];
activePointer = pointerId;
previousPointer = { x: pointer.x, y: pointer.y };
}
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraDistance = THREE.MathUtils.clamp(
cameraDistance + event.deltaY * 0.009,
7,
19
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
window.addEventListener("keydown", event => {
if (
event.key.toLowerCase() === "r" &&
!["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName)
) {
resetCamera();
}
});
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
cameraTarget.x = window.innerWidth <= 900 ? CHEST_X : 0;
updateCamera();
}
window.addEventListener("resize", resize);
resize();
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let opening = null;
function animate(now) {
const delta = Math.min(clock.getDelta(), 0.05);
const time = now * 0.001;
motes.rotation.y = Math.sin(time * 0.07) * 0.06;
motes.position.y = Math.sin(time * 0.4) * 0.06;
modeCrystal.rotation.y = time * 0.8;
modeCrystal.rotation.z = Math.sin(time * 1.4) * 0.08;
const glow = 0.9 + Math.sin(time * 3) * 0.2;
modeCrystalMaterial.emissiveIntensity = 1.05 + glow * 0.28;
chestLight.intensity = 3.6 + glow * 1.2;
if (opening) {
const progress = THREE.MathUtils.clamp(
(now - opening.start) / opening.duration,
0,
1
);
lidPivot.rotation.x = -1.12 * Math.sin(progress * Math.PI);
chest.scale.y = 1 + Math.sin(progress * Math.PI) * 0.025;
if (progress >= 1) {
lidPivot.rotation.x = 0;
chest.scale.y = 1;
opening = null;
}
}
if (burst) {
const age = (now - burst.born) / 1000;
for (const cube of burst.cubes) {
cube.mesh.position.addScaledVector(cube.velocity, delta);
cube.velocity.y -= 2.5 * delta;
cube.mesh.rotation.x += delta * 2.3;
cube.mesh.rotation.y += delta * 1.7;
const scale = cube.baseScale * Math.max(0, 1 - age / 1.55);
cube.mesh.scale.setScalar(scale);
}
const labelPosition = new THREE.Vector3(
CHEST_X,
3.15 + Math.sin(time * 3) * 0.06,
0.3
).project(camera);
el.lootLabel.style.left =
`${(labelPosition.x * 0.5 + 0.5) * window.innerWidth}px`;
el.lootLabel.style.top =
`${(-labelPosition.y * 0.5 + 0.5) * window.innerHeight}px`;
el.lootLabel.style.opacity = String(Math.max(0, 1 - age / 1.55));
if (age >= 1.55) clearBurst();
}
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
// Start an opening animation whenever the chest button is used.
const originalOpenChest = openChest;
el.openChest.addEventListener("click", () => {
if (!state.rolling) {
opening = {
start: performance.now(),
duration: 950
};
}
});
renderLoot();
</script>
</body>
</html>
```