Prompt specification
Build or customize the Three.js 3D scene "Tokens become a counted result" 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: Tokens become a counted result
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/tokens-become-a-counted-result-x3850
Scene Description Prompt:
Voxel residents cast one token each; count all visible votes and announce the winner by simple plurality. Create one HTML with Three.js from cdnjs.
Working Three.js Starter (tokens-become-a-counted-result-x3850):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Vote</title>
<style>
:root {
color-scheme: dark;
--ink: #eef6ff;
--muted: #91a4bd;
--panel: rgba(8, 17, 31, 0.86);
--line: rgba(165, 198, 235, 0.16);
--gold: #ffd76a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07101d;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
}
button,
select {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas.dragging {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.panel {
pointer-events: auto;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 20px 55px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
#controls {
position: absolute;
top: 20px;
left: 20px;
width: 340px;
padding: 20px;
border-radius: 20px;
}
.eyebrow {
color: var(--gold);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 8px;
font-size: 34px;
line-height: 1;
letter-spacing: -0.045em;
}
.intro {
margin: 0 0 17px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.scenario-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
select {
min-width: 160px;
padding: 9px 30px 9px 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: #111f34;
color: var(--ink);
outline: none;
cursor: pointer;
}
select:focus {
border-color: rgba(255, 215, 106, 0.65);
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
}
button {
border: 0;
border-radius: 11px;
padding: 12px 14px;
font-weight: 800;
cursor: pointer;
transition: transform 150ms ease, opacity 150ms ease, background 150ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: default;
opacity: 0.55;
}
#voteButton {
color: #171207;
background: linear-gradient(135deg, #ffe49a, #ffc94f);
box-shadow: 0 8px 22px rgba(255, 199, 70, 0.18);
}
#resetButton {
color: var(--ink);
background: rgba(255, 255, 255, 0.08);
border: 1px solid var(--line);
}
.status-line {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 17px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
#counted {
color: var(--ink);
white-space: nowrap;
}
.progress {
height: 5px;
margin-top: 9px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.08);
}
#progressBar {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #ffd76a, #ff8f6b);
transition: width 180ms ease;
}
#tally {
position: absolute;
top: 20px;
right: 20px;
width: 310px;
padding: 17px;
border-radius: 20px;
}
.tally-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.tally-heading strong {
font-size: 12px;
letter-spacing: 0.04em;
}
.tally-heading span {
color: var(--muted);
font-size: 11px;
}
#candidateCards {
display: grid;
gap: 8px;
}
.candidate-card {
--party: #ffffff;
position: relative;
padding: 11px 12px 10px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.075);
border-radius: 13px;
background: rgba(255, 255, 255, 0.035);
transition: border-color 200ms ease, background 200ms ease;
}
.candidate-card.winner {
border-color: color-mix(in srgb, var(--party) 75%, white 10%);
background: color-mix(in srgb, var(--party) 11%, transparent);
}
.candidate-top {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 3px;
background: var(--party);
box-shadow: 0 0 13px color-mix(in srgb, var(--party) 50%, transparent);
}
.party-name {
font-size: 12px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.winner-badge {
display: none;
margin-left: auto;
padding: 3px 6px;
border-radius: 6px;
color: #111827;
background: var(--party);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.candidate-card.winner .winner-badge {
display: inline-block;
}
.count-row {
display: flex;
align-items: baseline;
gap: 6px;
margin: 5px 0 8px 17px;
}
.count-row strong {
font-size: 24px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.count-row span {
color: var(--muted);
font-size: 10px;
}
.bar {
height: 3px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.065);
}
.bar i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--party);
transition: width 220ms ease;
}
.tally-note {
margin: 12px 2px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
#result {
position: absolute;
left: 50%;
bottom: 25px;
width: min(560px, calc(100% - 40px));
padding: 17px 21px;
border: 1px solid rgba(255, 215, 106, 0.34);
border-radius: 18px;
background: rgba(9, 17, 28, 0.94);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.45);
opacity: 0;
transform: translate(-50%, 18px);
transition: opacity 250ms ease, transform 250ms ease;
pointer-events: none;
}
#result.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#resultKicker {
color: var(--gold);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.18em;
text-transform: uppercase;
}
#resultTitle {
margin: 4px 0 4px;
font-size: 24px;
letter-spacing: -0.03em;
}
#resultText {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#hint {
position: absolute;
left: 20px;
bottom: 18px;
color: rgba(205, 222, 242, 0.62);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
}
@media (max-width: 760px) {
#controls {
top: 10px;
left: 10px;
width: calc(100% - 20px);
padding: 14px;
}
h1 {
font-size: 26px;
}
.intro {
display: none;
}
.scenario-row {
margin: 12px 0 10px;
}
#tally {
top: auto;
right: 10px;
bottom: 88px;
width: calc(100% - 20px);
padding: 11px;
}
.tally-note {
display: none;
}
#candidateCards {
grid-template-columns: repeat(4, 1fr);
gap: 5px;
}
.candidate-card {
padding: 8px 7px;
}
.party-name {
font-size: 9px;
letter-spacing: 0.04em;
}
.count-row {
margin-left: 0;
}
.count-row strong {
font-size: 21px;
}
.count-row span {
display: none;
}
.winner-badge {
display: none !important;
}
#result {
bottom: 10px;
width: calc(100% - 20px);
padding: 13px 16px;
}
#resultTitle {
font-size: 20px;
}
#hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<main class="hud">
<section id="controls" class="panel">
<div class="eyebrow">A tiny civic experiment</div>
<h1>Voxel Vote</h1>
<p class="intro">
Every voxel resident gets exactly one ballot token. Tokens land in open
trays, so every finished vote remains visible and countable.
</p>
<div class="scenario-row">
<label for="scenario">District mood</label>
<select id="scenario">
<option value="mixed">Mixed district</option>
<option value="close">Close finish</option>
<option value="wave">Ember wave</option>
</select>
</div>
<div class="button-row">
<button id="voteButton" type="button">Cast 30 ballots</button>
<button id="resetButton" type="button">Reset</button>
</div>
<div class="status-line">
<span id="voteStatus">30 residents ready</span>
<span id="counted">0 / 30</span>
</div>
<div class="progress"><span id="progressBar"></span></div>
</section>
<section id="tally" class="panel">
<div class="tally-heading">
<strong>Visible ballot tokens</strong>
<span>Simple plurality</span>
</div>
<div id="candidateCards"></div>
<p class="tally-note">
Only tokens resting in the open trays are counted. The highest visible
total wins; ties are announced as co-winners.
</p>
</section>
<section id="result" role="status" aria-live="polite" aria-hidden="true">
<div id="resultKicker">Election result</div>
<h2 id="resultTitle"></h2>
<p id="resultText"></p>
</section>
<div id="hint">Drag to orbit · Scroll to zoom · Double-click resets camera</div>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const TOTAL_RESIDENTS = 30;
const candidates = [
{ name: "Ember", color: 0xff6b61, css: "#ff6b61" },
{ name: "Mint", color: 0x49d7a5, css: "#49d7a5" },
{ name: "Sky", color: 0x58a9ff, css: "#58a9ff" },
{ name: "Violet", color: 0xa77cff, css: "#a77cff" }
];
const ui = {
scenario: document.querySelector("#scenario"),
voteButton: document.querySelector("#voteButton"),
resetButton: document.querySelector("#resetButton"),
voteStatus: document.querySelector("#voteStatus"),
counted: document.querySelector("#counted"),
progressBar: document.querySelector("#progressBar"),
candidateCards: document.querySelector("#candidateCards"),
result: document.querySelector("#result"),
resultKicker: document.querySelector("#resultKicker"),
resultTitle: document.querySelector("#resultTitle"),
resultText: document.querySelector("#resultText")
};
candidates.forEach((candidate, index) => {
const card = document.createElement("div");
card.className = "candidate-card";
card.style.setProperty("--party", candidate.css);
card.innerHTML = `
<div class="candidate-top">
<span class="swatch"></span>
<span class="party-name">${candidate.name}</span>
<span class="winner-badge">First</span>
</div>
<div class="count-row">
<strong data-count="${index}">00</strong>
<span>visible tokens</span>
</div>
<div class="bar"><i data-bar="${index}"></i></div>
`;
ui.candidateCards.appendChild(card);
});
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.FogExp2(0x07101d, 0.013);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.domElement.setAttribute(
"aria-label",
"Interactive voxel city election visualization"
);
document.querySelector("#scene").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc5e5ff, 0x172033, 2.3);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.2);
sun.position.set(9, 25, 17);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -34;
sun.shadow.camera.right = 34;
sun.shadow.camera.top = 30;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 75;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x728dff, 1.3);
rimLight.position.set(-18, 12, -20);
scene.add(rimLight);
const geometryCache = new Map();
function getGeometry(width, height, depth) {
const key = `${width}:${height}:${depth}`;
if (!geometryCache.has(key)) {
geometryCache.set(
key,
new THREE.BoxGeometry(width, height, depth)
);
}
return geometryCache.get(key);
}
function addBox(
parent,
[width, height, depth],
[x, y, z],
material,
castShadow = true,
receiveShadow = false
) {
const mesh = new THREE.Mesh(
getGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
parent.add(mesh);
return mesh;
}
function standard(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.04,
...options
});
}
// Ground and plaza.
const groundMaterial = standard(0x091421, { roughness: 1 });
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(130, 130),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.08;
ground.receiveShadow = true;
scene.add(ground);
const plazaMaterial = standard(0x142238, { roughness: 0.94 });
const plaza = addBox(
scene,
[30, 0.2, 30],
[0, -0.02, -2.5],
plazaMaterial,
false,
true
);
const grid = new THREE.GridHelper(30, 30, 0x536c8c, 0x30425c);
grid.position.set(0, 0.09, -2.5);
grid.material.transparent = true;
grid.material.opacity = 0.22;
scene.add(grid);
// Small suspended particles add depth without obscuring the scene.
const particlePositions = new Float32Array(240 * 3);
for (let i = 0; i < 240; i++) {
particlePositions[i * 3] = (Math.random() - 0.5) * 72;
particlePositions[i * 3 + 1] = 3 + Math.random() * 25;
particlePositions[i * 3 + 2] = (Math.random() - 0.5) * 62;
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0xa7c9ee,
size: 0.075,
transparent: true,
opacity: 0.48,
depthWrite: false
})
);
scene.add(particles);
// Voxel city backdrop.
const buildingMaterials = [
standard(0x182940),
standard(0x20334d),
standard(0x17243a),
standard(0x263954)
];
const windowMaterials = [
standard(0xffd76a, {
emissive: 0xffb83d,
emissiveIntensity: 1.1,
roughness: 0.4
}),
standard(0x6fc8ff, {
emissive: 0x2789c7,
emissiveIntensity: 1.2,
roughness: 0.4
})
];
function addBuilding(x, z, width, height, depth, rotation = 0) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotation;
const building = addBox(
group,
[width, height, depth],
[0, height / 2, 0],
buildingMaterials[Math.floor(Math.random() * buildingMaterials.length)],
true,
true
);
const floors = Math.max(1, Math.floor((height - 0.6) / 0.8));
const columns = Math.max(1, Math.floor((width - 0.45) / 0.65));
for (let floor = 0; floor < floors; floor++) {
for (let column = 0; column < columns; column++) {
addBox(
group,
[0.24, 0.28, 0.035],
[
(column - (columns - 1) / 2) * 0.55,
0.72 + floor * 0.76,
-depth / 2 - 0.025
],
windowMaterials[Math.floor(Math.random() * windowMaterials.length)],
false
);
}
}
scene.add(group);
}
for (let i = 0; i < 8; i++) {
addBuilding(
-15 + i * 4.3,
12.7 + (i % 2) * 1.1,
2.4 + Math.random() * 1.1,
2.7 + Math.random() * 4.5,
2.4 + Math.random() * 0.8
);
}
for (let i = 0; i < 4; i++) {
addBuilding(
-17.5,
-9 + i * 6,
2.6,
3 + Math.random() * 4,
3,
Math.PI / 2
);
addBuilding(
17.5,
-9 + i * 6,
2.6,
3 + Math.random() * 4,
3,
-Math.PI / 2
);
}
// Street lamps.
const lampPostMaterial = standard(0x263b55, { metalness: 0.25 });
const lampGlowMaterial = standard(0xffe29a, {
emissive: 0xffbd4a,
emissiveIntensity: 1.8
});
function addLamp(x, z) {
const group = new THREE.Group();
group.position.set(x, 0, z);
addBox(group, [0.1, 2.7, 0.1], [0, 1.35, 0], lampPostMaterial);
addBox(group, [0.1, 0.1, 0.65], [0, 2.6, 0.25], lampPostMaterial);
addBox(
group,
[0.28, 0.22, 0.28],
[0, 2.48, 0.5],
lampGlowMaterial,
false
);
scene.add(group);
}
addLamp(-14, -6);
addLamp(14, -6);
addLamp(-14, 7);
addLamp(14, 7);
function createTextSprite(text, colorCss) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(7, 15, 28, 0.94)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = colorCss;
context.fillRect(0, 0, 12, canvas.height);
context.strokeStyle = "rgba(255,255,255,0.22)";
context.strokeRect(1, 1, canvas.width - 2, canvas.height - 2);
context.fillStyle = "#f4f8ff";
context.font = "800 45px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text.toUpperCase(), 266, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(3.4, 0.85, 1);
sprite.renderOrder = 20;
return sprite;
}
const goldMaterial = standard(0xffd76a, {
metalness: 0.48,
roughness: 0.25,
emissive: 0x8a4d00,
emissiveIntensity: 0.55
});
function createCrown() {
const crown = new THREE.Group();
addBox(crown, [1.02, 0.18, 0.32], [0, 0, 0], goldMaterial);
addBox(crown, [0.16, 0.3, 0.2], [-0.39, 0.2, 0], goldMaterial);
addBox(crown, [0.16, 0.38, 0.2], [-0.13, 0.24, 0], goldMaterial);
addBox(crown, [0.16, 0.48, 0.2], [0.13, 0.29, 0], goldMaterial);
addBox(crown, [0.16, 0.3, 0.2], [0.39, 0.2, 0], goldMaterial);
return crown;
}
function createHalo() {
const halo = new THREE.Group();
const pieces = [];
for (let i = 0; i < 6; i++) {
const x = -2.55 + i * 1.02;
pieces.push([x, -2.55], [x, 2.55]);
}
for (let i = 1; i < 5; i++) {
const z = -2.55 + i * 1.02;
pieces.push([-2.55, z], [2.55, z]);
}
pieces.forEach(([x, z]) => {
addBox(halo, [0.22, 0.16, 0.22], [x, 0.53, z], goldMaterial, false);
});
return halo;
}
const candidateStations = [];
const candidateX = [-10.5, -3.5, 3.5, 10.5];
candidates.forEach((candidate, index) => {
const group = new THREE.Group();
group.position.set(candidateX[index], 0, 5);
scene.add(group);
const baseMaterial = standard(0x1b2c43, {
roughness: 0.85,
emissive: 0x000000,
emissiveIntensity: 0
});
addBox(
group,
[5.2, 0.4, 5.2],
[0, 0.2, 0],
baseMaterial,
true,
true
);
const partyMaterial = standard(candidate.color, {
roughness: 0.46,
metalness: 0.1,
emissive: candidate.color,
emissiveIntensity: 0.08
});
// Open-top ballot tray.
addBox(
group,
[4.6, 0.12, 2.8],
[0, 0.49, -0.9],
standard(0x253750, { roughness: 0.65 }),
true,
true
);
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0xb8d8f4,
transparent: true,
opacity: 0.14,
roughness: 0.12,
metalness: 0,
depthWrite: false
});
addBox(
group,
[0.07, 0.42, 2.78],
[-2.3, 0.72, -0.9],
glassMaterial,
false
);
addBox(
group,
[0.07, 0.42, 2.78],
[2.3, 0.72, -0.9],
glassMaterial,
false
);
addBox(
group,
[4.65, 0.42, 0.07],
[0, 0.72, 0.5],
glassMaterial,
false
);
addBox(
group,
[4.6, 0.12, 0.16],
[0, 0.43, -2.36],
partyMaterial,
false
);
// Candidate voxel figure.
const avatar = new THREE.Group();
avatar.position.z = 1.55;
group.add(avatar);
addBox(avatar, [0.72, 1.0, 0.48], [0, 1.02, 0], partyMaterial);
addBox(avatar, [0.5, 0.52, 0.46], [0, 1.91, 0], standard(0xf1c6a3));
addBox(avatar, [0.22, 0.18, 0.24], [-0.19, 0.43, 0], standard(0x172132));
addBox(avatar, [0.22, 0.18, 0.24], [0.19, 0.43, 0], standard(0x172132));
addBox(avatar, [0.2, 0.65, 0.22], [-0.5, 1.02, 0], partyMaterial);
addBox(avatar, [0.2, 0.65, 0.22], [0.5, 1.02, 0], partyMaterial);
addBox(avatar, [0.54, 0.12, 0.5], [0, 2.2, 0], standard(0x273044));
const label = createTextSprite(candidate.name, candidate.css);
label.position.set(0, 3.65, 1.55);
group.add(label);
const crown = createCrown();
crown.position.set(0, 2.35, 1.55);
crown.visible = false;
group.add(crown);
const halo = createHalo();
halo.visible = false;
group.add(halo);
candidateStations.push({
group,
baseMaterial,
crown,
halo,
candidate
});
});
// Voxel residents and their one held token.
const residents = [];
const clothingMaterials = [
standard(0x49627f),
standard(0x6d587f),
standard(0x49766f),
standard(0x8a665a),
standard(0x596b99),
standard(0x77744d)
];
const skinMaterials = [
standard(0xf3c9a7),
standard(0xdba77f),
standard(0xa97050),
standard(0x81533e),
standard(0xe8b38f)
];
const hairMaterials = [
standard(0x241c20),
standard(0x493326),
standard(0x70492f),
standard(0x171a24)
];
const eyeMaterial = standard(0x111827);
const shoeMaterial = standard(0x172233);
const tokenTopMaterial = standard(0xfff4d2, {
roughness: 0.35,
metalness: 0.15
});
function createToken() {
const token = new THREE.Group();
const mainMaterial = standard(0xf7ca4d, {
roughness: 0.34,
metalness: 0.18,
emissive: 0x5a3a00,
emissiveIntensity: 0.2
});
const main = addBox(
token,
[0.38, 0.16, 0.38],
[0, 0, 0],
mainMaterial
);
addBox(
token,
[0.16, 0.035, 0.16],
[0, 0.096, 0],
tokenTopMaterial,
false
);
token.userData.mainMaterial = mainMaterial;
token.userData.mainMesh = main;
return token;
}
for (let row = 0; row < 5; row++) {
for (let column = 0; column < 6; column++) {
const index = row * 6 + column;
const group = new THREE.Group();
group.position.set(-10 + column * 4, 0.08, -1.5 - row * 2.7);
scene.add(group);
const clothing = clothingMaterials[index % clothingMaterials.length];
const skin = skinMaterials[index % skinMaterials.length];
const hair = hairMaterials[index % hairMaterials.length];
addBox(group, [0.21, 0.45, 0.26], [-0.18, 0.28, 0], shoeMaterial);
addBox(group, [0.21, 0.45, 0.26], [0.18, 0.28, 0], shoeMaterial);
addBox(group, [0.65, 0.75, 0.44], [0, 0.9, 0], clothing);
addBox(group, [0.18, 0.13, 0.2], [0, 1.32, 0], skin);
addBox(group, [0.48, 0.48, 0.46], [0, 1.59, 0], skin);
addBox(group, [0.52, 0.12, 0.49], [0, 1.85, 0], hair);
addBox(group, [0.18, 0.58, 0.22], [-0.43, 0.93, 0], clothing);
addBox(group, [0.18, 0.58, 0.22], [0.43, 0.93, 0], clothing);
addBox(group, [0.06, 0.07, 0.035], [-0.11, 1.63, 0.247], eyeMaterial, false);
addBox(group, [0.06, 0.07, 0.035], [0.11, 1.63, 0.247], eyeMaterial, false);
const token = createToken();
token.position.set(0.54, 1.01, 0.08);
token.scale.setScalar(0.82);
group.add(token);
residents.push({
group,
token,
baseY: group.position.y,
phase: index * 0.71,
cast: false
});
}
}
const winnerLight = new THREE.PointLight(0xffd76a, 0, 13, 2);
scene.add(winnerLight);
const visibleTokens = [[], [], [], []];
const slotCursor = [0, 0, 0, 0];
let voteQueue = [];
let flights = [];
let running = false;
let finished = false;
let castCount = 0;
let nextVoteAt = 0;
function countVisibleVotes() {
return candidates.map((_, index) =>
visibleTokens[index].filter(
(token) => token.visible && token.parent === scene
).length
);
}
function updateTally(counts = countVisibleVotes()) {
counts.forEach((count, index) => {
document.querySelector(`[data-count="${index}"]`).textContent =
String(count).padStart(2, "0");
document.querySelector(`[data-bar="${index}"]`).style.width =
`${(count / TOTAL_RESIDENTS) * 100}%`;
});
}
function updateStatus() {
const counts = countVisibleVotes();
const counted = counts.reduce((sum, value) => sum + value, 0);
updateTally(counts);
ui.counted.textContent = `${counted} / ${TOTAL_RESIDENTS}`;
ui.progressBar.style.width =
`${(counted / TOTAL_RESIDENTS) * 100}%`;
if (running) {
ui.voteStatus.textContent =
`${castCount} cast · ${counted} visible in trays`;
} else if (finished) {
ui.voteStatus.textContent =
`${counted} visible tokens counted · plurality complete`;
} else {
ui.voteStatus.textContent =
`${TOTAL_RESIDENTS} residents ready · one token each`;
}
}
function clearElection() {
running = false;
finished = false;
voteQueue = [];
flights = [];
castCount = 0;
residents.forEach((resident) => {
resident.group.add(resident.token);
resident.token.position.set(0.54, 1.01, 0.08);
resident.token.rotation.set(0, 0, 0);
resident.token.scale.setScalar(0.82);
resident.cast = false;
const material = resident.token.userData.mainMaterial;
material.color.setHex(0xf7ca4d);
material.emissive.setHex(0x5a3a00);
material.emissiveIntensity = 0.2;
});
visibleTokens.forEach((tokens) => {
tokens.length = 0;
});
slotCursor.fill(0);
candidateStations.forEach((station) => {
station.baseMaterial.emissive.setHex(0x000000);
station.baseMaterial.emissiveIntensity = 0;
station.crown.visible = false;
station.halo.visible = false;
});
winnerLight.intensity = 0;
ui.result.classList.remove("visible");
ui.result.setAttribute("aria-hidden", "true");
ui.voteButton.disabled = false;
ui.voteButton.textContent = "Cast 30 ballots";
ui.resetButton.textContent = "Reset";
ui.scenario.disabled = false;
document.querySelectorAll(".candidate-card").forEach((card) => {
card.classList.remove("winner");
});
updateStatus();
}
function shuffled(array) {
const copy = [...array];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
function createVotePlan() {
const mode = ui.scenario.value;
let counts;
if (mode === "close") {
counts = [9, 8, 7, 6];
} else if (mode === "wave") {
counts = [15, 7, 5, 3];
} else {
counts = [2, 2, 2, 2];
const weights = candidates.map(() => 0.7 + Math.random() * 0.6);
for (let i = 0; i < TOTAL_RESIDENTS - 4; i++) {
const totalWeight = weights.reduce((sum, value) => sum + value, 0);
let choice = Math.random() * totalWeight;
for (let candidate = 0; candidate < weights.length; candidate++) {
choice -= weights[candidate];
if (choice <= 0) {
counts[candidate]++;
break;
}
}
}
}
const plan = [];
counts.forEach((count, candidate) => {
for (let i = 0; i < count; i++) {
plan.push(candidate);
}
});
return shuffled(plan);
}
function getSlotPosition(candidateIndex, slotIndex) {
const column = slotIndex % 6;
const row = Math.floor(slotIndex / 6);
const local = new THREE.Vector3(
(column - 2.5) * 0.69,
0.67,
-0.9 + (row - 2.5) * 0.42
);
return candidateStations[candidateIndex].group.localToWorld(local);
}
function launchVote(vote, now) {
const { resident, candidate } = vote;
const station = candidateStations[candidate];
const token = resident.token;
const material = token.userData.mainMaterial;
material.color.setHex(station.candidate.color);
material.emissive.setHex(station.candidate.color);
material.emissiveIntensity = 0.12;
scene.attach(token);
token.scale.setScalar(1);
const start = token.position.clone();
const slotIndex = slotCursor[candidate]++;
const end = getSlotPosition(candidate, slotIndex);
const control = start.clone().lerp(end, 0.5);
control.y += 4.8 + Math.abs(end.x - start.x) * 0.08;
flights.push({
token,
resident,
candidate,
slotIndex,
curve: new THREE.QuadraticBezierCurve3(start, control, end),
startedAt: now,
duration: 820
});
resident.cast = true;
castCount++;
updateStatus();
}
function announceResult() {
const counts = countVisibleVotes();
const highest = Math.max(...counts);
const winners = counts
.map((count, index) => ({ count, index }))
.filter((entry) => entry.count === highest)
.map((entry) => entry.index);
finished = true;
running = false;
candidateStations.forEach((station, index) => {
const isWinner = winners.includes(index);
station.crown.visible = isWinner;
station.halo.visible = isWinner;
station.baseMaterial.emissive.setHex(
isWinner ? station.candidate.color : 0x000000
);
station.baseMaterial.emissiveIntensity = isWinner ? 0.28 : 0;
});
winnerLight.color.setHex(candidates[winners[0]].color);
winnerLight.position.set(
candidateStations[winners[0]].group.position.x,
5,
candidateStations[winners[0]].group.position.z
);
winnerLight.intensity = 35;
document.querySelectorAll(".candidate-card").forEach((card, index) => {
const isWinner = winners.includes(index);
card.classList.toggle("winner", isWinner);
if (isWinner) {
card.querySelector(".winner-badge").textContent =
winners.length > 1 ? "Tied first" : "First";
}
});
if (winners.length === 1) {
const winner = candidates[winners[0]];
ui.resultKicker.textContent = "Election result · plurality winner";
ui.resultTitle.textContent = `${winner.name} wins by plurality`;
ui.resultText.textContent =
`${winner.name} has the most visible tokens with ${highest}. ` +
`The count is ${counts.join("–")}. No runoff is used.`;
document.title = `${winner.name} wins — Voxel Vote`;
} else {
const names = winners.map((index) => candidates[index].name);
ui.resultKicker.textContent = "Election result · tied plurality";
ui.resultTitle.textContent = `${names.join(" and ")} tie for first`;
ui.resultText.textContent =
`Each co-winner has ${highest} visible tokens. ` +
`The count is ${counts.join("–")}. No runoff is used.`;
document.title = `${names.join(" & ")} tie — Voxel Vote`;
}
ui.result.classList.add("visible");
ui.result.setAttribute("aria-hidden", "false");
ui.voteButton.disabled = false;
ui.voteButton.textContent = "Run another vote";
ui.resetButton.textContent = "Reset";
ui.scenario.disabled = false;
updateStatus();
}
function startElection() {
if (running) return;
clearElection();
const plan = createVotePlan();
voteQueue = residents.map((resident, index) => ({
resident,
candidate: plan[index]
}));
running = true;
nextVoteAt = performance.now() + 350;
ui.voteButton.disabled = true;
ui.voteButton.textContent = "Casting ballots…";
ui.resetButton.textContent = "Cancel vote";
ui.scenario.disabled = true;
ui.result.classList.remove("visible");
ui.result.setAttribute("aria-hidden", "true");
updateStatus();
}
ui.voteButton.addEventListener("click", startElection);
ui.resetButton.addEventListener("click", clearElection);
ui.scenario.addEventListener("change", () => {
if (!running) clearElection();
});
// Camera controls implemented directly, without camera addons.
const cameraTarget = new THREE.Vector3(0, 0.25, -2.5);
let cameraDistance = 40;
let cameraAzimuth = 0;
let cameraPolar = 0.78;
let dragging = false;
let pointerX = 0;
let pointerY = 0;
let cameraTouched = false;
function updateCamera() {
const horizontal = Math.sin(cameraPolar) * cameraDistance;
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraAzimuth),
cameraTarget.y + Math.cos(cameraPolar) * cameraDistance,
cameraTarget.z + horizontal * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTouched = false;
cameraAzimuth = 0;
cameraPolar = 0.78;
cameraDistance = innerWidth < 760 ? 70 : 40;
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse" && event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
cameraTouched = true;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraAzimuth -= deltaX * 0.006;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar - deltaY * 0.005,
0.34,
1.34
);
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("pointerleave", () => {
if (dragging) endDrag({});
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraTouched = true;
cameraDistance = THREE.MathUtils.clamp(
cameraDistance * Math.exp(event.deltaY * 0.001),
24,
90
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
addEventListener("keydown", (event) => {
const tag = event.target?.tagName;
if (["INPUT", "SELECT", "BUTTON"].includes(tag)) return;
let changed = true;
if (event.key === "ArrowLeft") cameraAzimuth += 0.08;
else if (event.key === "ArrowRight") cameraAzimuth -= 0.08;
else if (event.key === "ArrowUp") cameraPolar -= 0.05;
else if (event.key === "ArrowDown") cameraPolar += 0.05;
else if (event.key === "+" || event.key === "=") cameraDistance -= 2;
else if (event.key === "-") cameraDistance += 2;
else changed = false;
if (changed) {
event.preventDefault();
cameraTouched = true;
cameraPolar = THREE.MathUtils.clamp(cameraPolar, 0.34, 1.34);
cameraDistance = THREE.MathUtils.clamp(cameraDistance, 24, 90);
updateCamera();
}
});
function onResize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
if (!cameraTouched) {
cameraDistance = innerWidth < 760 ? 70 : 40;
updateCamera();
}
}
addEventListener("resize", onResize);
resetCamera();
clearElection();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const elapsed = clock.getElapsedTime();
const now = performance.now();
// Launch queued ballots at a steady pace.
if (running) {
while (voteQueue.length && now >= nextVoteAt) {
launchVote(voteQueue.shift(), now);
nextVoteAt = now + 125;
}
}
// Animate tokens along visible arcing paths.
for (let index = flights.length - 1; index >= 0; index--) {
const flight = flights[index];
const progress = THREE.MathUtils.clamp(
(now - flight.startedAt) / flight.duration,
0,
1
);
if (progress >= 1) {
flight.token.position.copy(flight.curve.v2);
flight.token.rotation.set(0, 0, 0);
visibleTokens[flight.candidate].push(flight.token);
flights.splice(index, 1);
updateStatus();
} else {
flight.token.position.copy(flight.curve.getPoint(progress));
flight.token.rotation.set(
0,
progress * Math.PI * 4,
Math.sin(progress * Math.PI) * 0.34
);
}
}
if (
running &&
voteQueue.length === 0 &&
flights.length === 0 &&
castCount === TOTAL_RESIDENTS
) {
announceResult();
}
// Gentle voxel idle motion.
residents.forEach((resident) => {
const castBob = resident.cast ? 0.075 : 0.022;
resident.group.position.y =
resident.baseY +
Math.sin(elapsed * 1.8 + resident.phase) * castBob;
});
candidateStations.forEach((station) => {
if (station.crown.visible) {
station.crown.position.y =
2.35 + Math.sin(elapsed * 3.2) * 0.075;
station.crown.rotation.y = Math.sin(elapsed * 1.5) * 0.12;
}
if (station.halo.visible) {
const pulse = 1 + Math.sin(elapsed * 3.5) * 0.018;
station.halo.scale.set(pulse, 1, pulse);
}
});
winnerLight.intensity =
finished ? 30 + Math.sin(elapsed * 3.5) * 8 : 0;
particles.rotation.y = elapsed * 0.008;
renderer.render(scene, camera);
});
</script>
</body>
</html>
```