Prompt specification
Build or customize the Three.js 3D scene "Tile Map Storage Workshop" 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: Tile Map Storage Workshop
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/tile-map-storage-workshop-x3371
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring repeated patterns and data compression. Build two small terrain maps, one repetitive and one irregular, with visible encodings. Compare storage under the same toy scheme without claiming all data compresses equally. Voxel style.
Working Three.js Starter (tile-map-storage-workshop-x3371):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Byte Atlas — Voxel Compression Comparison</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: rgba(12, 18, 31, 0.88);
--panel-soft: rgba(16, 24, 40, 0.74);
--border: rgba(160, 190, 235, 0.16);
--text: #edf4ff;
--muted: #8d9bb2;
--blue: #5b7cff;
--teal: #34d8bd;
--amber: #ffbd59;
--pink: #ff637d;
--green: #67e8a7;
--red: #ff7c91;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", "Courier New", monospace;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 40%, transparent 35%, rgba(0,0,0,.32) 100%),
linear-gradient(180deg, rgba(7,11,20,.12), transparent 45%, rgba(7,11,20,.38));
z-index: 1;
}
.masthead {
position: fixed;
z-index: 3;
top: 24px;
left: 28px;
right: 28px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
pointer-events: none;
}
.eyebrow {
display: block;
margin-bottom: 7px;
color: var(--teal);
font: 700 11px/1 var(--mono);
letter-spacing: .19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(23px, 2.4vw, 39px);
line-height: 1.06;
letter-spacing: -.035em;
text-wrap: balance;
}
.subtitle {
max-width: 720px;
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.controls {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 13px;
background: rgba(13, 20, 35, .86);
color: var(--text);
font: 650 12px/1 var(--mono);
cursor: pointer;
transition: border-color .2s, background .2s, transform .2s;
backdrop-filter: blur(12px);
}
button:hover {
border-color: rgba(91, 124, 255, .65);
background: rgba(25, 35, 58, .92);
transform: translateY(-1px);
}
button[aria-pressed="true"] {
border-color: var(--teal);
color: var(--teal);
background: rgba(22, 54, 55, .86);
}
.legend {
position: fixed;
z-index: 3;
top: 122px;
right: 28px;
display: flex;
gap: 12px;
align-items: center;
padding: 9px 12px;
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(10, 16, 28, .72);
backdrop-filter: blur(12px);
pointer-events: none;
}
.legend-title {
margin-right: 3px;
color: var(--muted);
font: 650 10px/1 var(--mono);
letter-spacing: .1em;
}
.token {
display: inline-flex;
align-items: center;
gap: 5px;
color: #cbd6e8;
font: 700 11px/1 var(--mono);
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: 0 0 12px currentColor;
}
.hint {
position: fixed;
z-index: 3;
left: 28px;
bottom: 278px;
color: rgba(180, 195, 220, .66);
font: 11px/1.4 var(--mono);
pointer-events: none;
}
.readouts {
position: fixed;
z-index: 3;
left: 18px;
right: 18px;
bottom: 16px;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
pointer-events: none;
}
.card {
min-width: 0;
padding: 14px 15px 12px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, .28);
backdrop-filter: blur(18px);
pointer-events: auto;
}
.card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.card-title {
margin: 0;
font-size: 16px;
letter-spacing: -.015em;
}
.card-subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
}
.badge {
flex: none;
padding: 6px 8px;
border: 1px solid currentColor;
border-radius: 999px;
font: 750 9px/1 var(--mono);
letter-spacing: .08em;
text-transform: uppercase;
}
.badge.good {
color: var(--green);
background: rgba(52, 211, 153, .08);
}
.badge.bad {
color: var(--red);
background: rgba(255, 99, 125, .08);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 10px;
}
.metric {
min-width: 0;
padding: 8px 9px;
border: 1px solid rgba(160,190,235,.10);
border-radius: 10px;
background: var(--panel-soft);
}
.metric span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font: 9px/1 var(--mono);
letter-spacing: .08em;
text-transform: uppercase;
}
.metric strong {
display: block;
overflow: hidden;
font: 700 16px/1 var(--mono);
text-overflow: ellipsis;
white-space: nowrap;
}
.metric strong.good { color: var(--green); }
.metric strong.bad { color: var(--red); }
.encoding {
margin-top: 8px;
}
.encoding-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 5px;
color: var(--muted);
font: 9px/1 var(--mono);
letter-spacing: .06em;
text-transform: uppercase;
}
.encoding-head b {
color: #d8e3f5;
font-weight: 700;
}
.stream {
display: block;
min-height: 31px;
padding: 8px 9px;
overflow: hidden;
border: 1px solid rgba(160,190,235,.09);
border-radius: 9px;
background: rgba(3, 7, 14, .58);
color: #c9d8ee;
font: 11px/1.42 var(--mono);
letter-spacing: .08em;
word-break: break-all;
}
.stream.rle {
color: #b9c8ff;
}
.bars {
display: grid;
grid-template-columns: 46px 1fr 58px;
align-items: center;
gap: 8px;
margin-top: 9px;
}
.bars span,
.bars b {
color: var(--muted);
font: 9px/1 var(--mono);
}
.bars b {
color: #dce6f7;
text-align: right;
}
.track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255,255,255,.055);
}
.track i {
display: block;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #617cff, #8da5ff);
}
.track i.rle-pattern {
background: linear-gradient(90deg, #22bda5, #67e8a7);
}
.track i.rle-irregular {
background: linear-gradient(90deg, #e44f69, #ff9d79);
}
.caveat {
grid-column: 1 / -1;
padding: 9px 12px;
border: 1px solid rgba(255, 189, 89, .18);
border-radius: 12px;
background: rgba(43, 34, 22, .60);
color: #c8bfae;
font-size: 11px;
line-height: 1.45;
backdrop-filter: blur(12px);
}
.caveat b {
color: #ffd28c;
}
#tooltip {
position: fixed;
z-index: 5;
display: none;
min-width: 170px;
padding: 9px 11px;
border: 1px solid rgba(160,190,235,.22);
border-radius: 9px;
background: rgba(7, 11, 20, .94);
box-shadow: 0 10px 30px rgba(0,0,0,.35);
color: #e7efff;
font: 11px/1.55 var(--mono);
pointer-events: none;
}
#tooltip strong {
color: var(--teal);
}
@media (max-width: 900px) {
.masthead {
top: 17px;
left: 18px;
right: 18px;
}
.subtitle {
max-width: 470px;
font-size: 11px;
}
.legend {
top: 112px;
right: 18px;
}
.hint {
display: none;
}
.readouts {
grid-template-columns: 1fr;
max-height: 46vh;
overflow: auto;
}
.caveat {
grid-column: 1;
}
}
@media (max-width: 580px) {
.masthead {
display: block;
}
.controls {
justify-content: flex-start;
margin-top: 12px;
}
.legend {
top: 176px;
left: 18px;
right: auto;
}
.readouts {
left: 10px;
right: 10px;
bottom: 10px;
}
.card {
padding: 12px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel terrain compression comparison"></canvas>
<div class="vignette"></div>
<header class="masthead">
<div>
<span class="eyebrow">Byte Atlas / Experiment 01</span>
<h1>Same voxels. Different compressibility.</h1>
<p class="subtitle">
Two 8×8 height fields pass through one toy run-length encoder.
Drag to orbit, shift-drag to pan, scroll to zoom, and hover a cell to inspect its token.
</p>
</div>
<div class="controls">
<button id="explode" type="button" aria-pressed="false">Explode voxels</button>
<button id="reset" type="button">Reset view</button>
</div>
</header>
<div class="legend" aria-label="Height token legend">
<span class="legend-title">TOKEN / HEIGHT</span>
<span class="token"><i class="swatch" style="background:#5b7cff;color:#5b7cff"></i>A / 0</span>
<span class="token"><i class="swatch" style="background:#34d8bd;color:#34d8bd"></i>B / 1</span>
<span class="token"><i class="swatch" style="background:#ffbd59;color:#ffbd59"></i>C / 2</span>
<span class="token"><i class="swatch" style="background:#ff637d;color:#ff637d"></i>D / 3</span>
</div>
<div class="hint">DRAG orbit · SHIFT / RIGHT-DRAG pan · WHEEL zoom · HOVER cells</div>
<section class="readouts" id="readouts" aria-label="Storage comparison"></section>
<div id="tooltip" role="status"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Toy encoding
//
// Raw: one ASCII token per cell: A, B, C, or D.
// RLE: two decimal digits for the run length + one height token.
//
// These counts use ASCII characters as a simple byte proxy. This is not a
// claim about general-purpose compression or every kind of data.
// -------------------------------------------------------------------------
const TOKENS = ["A", "B", "C", "D"];
const COLORS = [0x5b7cff, 0x34d8bd, 0xffbd59, 0xff637d];
function rawEncode(values) {
return values.map(value => TOKENS[value]).join("");
}
function rleEncode(values) {
const output = [];
for (let i = 0; i < values.length;) {
let j = i + 1;
while (j < values.length && values[j] === values[i]) {
j++;
}
const count = j - i;
output.push(String(count).padStart(2, "0") + TOKENS[values[i]]);
i = j;
}
return output.join("");
}
function countRuns(values) {
let runs = values.length ? 1 : 0;
for (let i = 1; i < values.length; i++) {
if (values[i] !== values[i - 1]) runs++;
}
return runs;
}
function makePattern() {
const values = [];
// An 8×8 field made from a 4×4 motif repeated in a 2×2 arrangement.
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
values.push(Math.floor(row / 4) % 4);
}
}
return values;
}
function makeIrregular() {
const values = [];
let state = 0x51f15e;
let previous = -1;
// Deterministic pseudo-random field. Neighboring values are deliberately
// different, producing many short runs.
function random() {
state ^= state << 13;
state ^= state >>> 17;
state ^= state << 5;
return (state >>> 0) / 4294967296;
}
for (let i = 0; i < 64; i++) {
let value = Math.floor(random() * 4);
if (value === previous) {
value = (value + 1 + Math.floor(random() * 3)) % 4;
}
values.push(value);
previous = value;
}
return values;
}
const mapDefinitions = [
{
title: "Repeated motif",
subtitle: "4×4 tile repeated 4 times",
values: makePattern(),
accent: 0x67e8a7,
cssAccent: "#67e8a7"
},
{
title: "Irregular field",
subtitle: "Deterministic neighboring variation",
values: makeIrregular(),
accent: 0xff7c91,
cssAccent: "#ff7c91"
}
];
for (const map of mapDefinitions) {
map.raw = rawEncode(map.values);
map.rle = rleEncode(map.values);
map.rawBytes = map.raw.length;
map.rleBytes = map.rle.length;
map.runs = countRuns(map.values);
map.change = ((map.rleBytes - map.rawBytes) / map.rawBytes) * 100;
}
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const tooltip = document.querySelector("#tooltip");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b14);
scene.fog = new THREE.Fog(0x070b14, 24, 52);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const desiredView = {
yaw: 0.17,
pitch: 0.60,
distance: 23,
target: new THREE.Vector3(0, 1.35, 0)
};
const currentView = {
yaw: desiredView.yaw,
pitch: desiredView.pitch,
distance: desiredView.distance,
target: desiredView.target.clone()
};
const hemisphere = new THREE.HemisphereLight(0xa9c8ff, 0x101522, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(6, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -16;
keyLight.shadow.camera.right = 16;
keyLight.shadow.camera.top = 16;
keyLight.shadow.camera.bottom = -16;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const blueLight = new THREE.PointLight(0x4267ff, 24, 18, 2);
blueLight.position.set(-7, 5, 2);
scene.add(blueLight);
const pinkLight = new THREE.PointLight(0xff496c, 20, 18, 2);
pinkLight.position.set(7, 4, 1);
scene.add(pinkLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0x080d18,
roughness: 0.98,
metalness: 0.03
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.17;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(40, 40, 0x263550, 0x111a2b);
grid.position.y = -0.155;
grid.material.transparent = true;
grid.material.opacity = 0.44;
scene.add(grid);
const particleGeometry = new THREE.BufferGeometry();
const particlePositions = new Float32Array(150 * 3);
for (let i = 0; i < 150; i++) {
particlePositions[i * 3] = (Math.random() - 0.5) * 36;
particlePositions[i * 3 + 1] = Math.random() * 15 + 0.3;
particlePositions[i * 3 + 2] = (Math.random() - 0.5) * 30;
}
particleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0x91a9d1,
size: 0.035,
transparent: true,
opacity: 0.34,
depthWrite: false
})
);
scene.add(particles);
const GRID_SIZE = 8;
const CELL_SIZE = 0.86;
const SPAN = GRID_SIZE * CELL_SIZE;
const maps = [];
// -------------------------------------------------------------------------
// Helpers for label textures
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function fitText(ctx, text, maxWidth, initialSize, minimumSize = 15) {
let size = initialSize;
ctx.font = `600 ${size}px ui-monospace, monospace`;
while (ctx.measureText(text).width > maxWidth && size > minimumSize) {
size -= 1;
ctx.font = `600 ${size}px ui-monospace, monospace`;
}
return size;
}
function makeLabelSprite(map, index) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 1400;
labelCanvas.height = 260;
const ctx = labelCanvas.getContext("2d");
roundedRect(ctx, 8, 8, 1384, 244, 24);
ctx.fillStyle = "rgba(8, 13, 24, 0.94)";
ctx.fill();
ctx.strokeStyle = map.cssAccent;
ctx.lineWidth = 4;
ctx.stroke();
ctx.fillStyle = map.cssAccent;
ctx.fillRect(35, 34, 7, 192);
ctx.fillStyle = "#eef4ff";
ctx.font = "700 43px ui-sans-serif, system-ui, sans-serif";
ctx.fillText(
`${String(index + 1).padStart(2, "0")} / ${map.title.toUpperCase()}`,
67,
76
);
ctx.fillStyle = "#93a4bf";
ctx.font = "400 25px ui-sans-serif, system-ui, sans-serif";
ctx.fillText(map.subtitle, 68, 116);
ctx.fillStyle = "#8292ac";
ctx.font = "600 20px ui-monospace, monospace";
ctx.fillText("TOY RLE", 68, 169);
ctx.fillStyle = map.cssAccent;
const codeSize = fitText(ctx, map.rle, 1190, 29, 16);
ctx.fillText(map.rle, 215, 171);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.position.set(0, 4.72, 0);
sprite.scale.set(7.35, 1.365, 1);
sprite.renderOrder = 20;
return sprite;
}
function addPedestalEdges(mesh, color) {
const edges = new THREE.EdgesGeometry(mesh.geometry);
const lines = new THREE.LineSegments(
edges,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.28
})
);
lines.position.copy(mesh.position);
return lines;
}
function addMotifFrames(group, accent) {
const quadrantSize = 4 * CELL_SIZE;
const quadrantOffset = 2 * CELL_SIZE;
const material = new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.66
});
for (const x of [-quadrantOffset, quadrantOffset]) {
for (const z of [-quadrantOffset, quadrantOffset]) {
const half = quadrantSize / 2;
const points = [
new THREE.Vector3(x - half, 0.285, z - half),
new THREE.Vector3(x + half, 0.285, z - half),
new THREE.Vector3(x + half, 0.285, z + half),
new THREE.Vector3(x - half, 0.285, z + half)
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const frame = new THREE.LineLoop(geometry, material);
group.add(frame);
}
}
}
// -------------------------------------------------------------------------
// Build the two voxel maps
// -------------------------------------------------------------------------
function buildMap(definition, index) {
const group = new THREE.Group();
group.position.x = index === 0 ? -5.05 : 5.05;
scene.add(group);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(SPAN + 0.85, 0.28, SPAN + 0.85),
new THREE.MeshStandardMaterial({
color: 0x111a2a,
roughness: 0.78,
metalness: 0.18
})
);
pedestal.position.y = 0;
pedestal.castShadow = true;
pedestal.receiveShadow = true;
group.add(pedestal);
const edgeColor = index === 0 ? 0x4169d8 : 0xb74259;
group.add(addPedestalEdges(pedestal, edgeColor));
const frontAccent = new THREE.Mesh(
new THREE.BoxGeometry(SPAN * 0.66, 0.045, 0.055),
new THREE.MeshBasicMaterial({ color: definition.accent })
);
frontAccent.position.set(0, 0.16, SPAN / 2 + 0.435);
group.add(frontAccent);
const tileGeometry = new THREE.BoxGeometry(
CELL_SIZE - 0.10,
0.075,
CELL_SIZE - 0.10
);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.86,
metalness: 0.08
});
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
GRID_SIZE * GRID_SIZE
);
tiles.receiveShadow = true;
tiles.userData.mapIndex = index;
const dummy = new THREE.Object3D();
for (let row = 0; row < GRID_SIZE; row++) {
for (let col = 0; col < GRID_SIZE; col++) {
const instance = row * GRID_SIZE + col;
const value = definition.values[instance];
dummy.position.set(
(col - (GRID_SIZE - 1) / 2) * CELL_SIZE,
0.205,
(row - (GRID_SIZE - 1) / 2) * CELL_SIZE
);
dummy.updateMatrix();
tiles.setMatrixAt(instance, dummy.matrix);
const baseColor = new THREE.Color(COLORS[value]).multiplyScalar(0.30);
tiles.setColorAt(instance, baseColor);
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
group.add(tiles);
const voxelInstances = [];
for (const value of definition.values) {
for (let level = 0; level < value; level++) {
voxelInstances.push({ level });
}
}
const voxelGeometry = new THREE.BoxGeometry(
CELL_SIZE - 0.16,
0.38,
CELL_SIZE - 0.16
);
const voxelMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.66,
metalness: 0.10
});
const voxels = new THREE.InstancedMesh(
voxelGeometry,
voxelMaterial,
voxelInstances.length
);
voxels.castShadow = true;
voxels.receiveShadow = true;
const voxelData = [];
let voxelIndex = 0;
for (let row = 0; row < GRID_SIZE; row++) {
for (let col = 0; col < GRID_SIZE; col++) {
const cellIndex = row * GRID_SIZE + col;
const value = definition.values[cellIndex];
for (let level = 0; level < value; level++) {
const x = (col - (GRID_SIZE - 1) / 2) * CELL_SIZE;
const z = (row - (GRID_SIZE - 1) / 2) * CELL_SIZE;
const y = 0.46 + level * 0.42;
voxelData.push({ x, y, z, level });
dummy.position.set(x, y, z);
dummy.updateMatrix();
voxels.setMatrixAt(voxelIndex, dummy.matrix);
const color = new THREE.Color(COLORS[value]);
color.offsetHSL(0, 0, level * 0.035);
voxels.setColorAt(voxelIndex, color);
voxelIndex++;
}
}
}
voxels.instanceMatrix.needsUpdate = true;
voxels.instanceColor.needsUpdate = true;
group.add(voxels);
if (index === 0) {
addMotifFrames(group, definition.accent);
}
const label = makeLabelSprite(definition, index);
group.add(label);
return {
...definition,
index,
group,
tiles,
voxels,
voxelData,
explosion: 0,
explosionTarget: 0
};
}
mapDefinitions.forEach((definition, index) => {
maps.push(buildMap(definition, index));
});
// -------------------------------------------------------------------------
// HTML readouts
// -------------------------------------------------------------------------
const maximumBytes = Math.max(
...maps.flatMap(map => [map.rawBytes, map.rleBytes])
);
function bar(label, bytes, className = "") {
const width = (bytes / maximumBytes) * 100;
return `
<div class="bars">
<span>${label}</span>
<div class="track"><i class="${className}" style="width:${width}%"></i></div>
<b>${bytes} B</b>
</div>
`;
}
document.querySelector("#readouts").innerHTML = `
${maps.map((map, index) => {
const improves = map.change < 0;
const badgeClass = improves ? "good" : "bad";
const metricClass = improves ? "good" : "bad";
const changeText = `${map.change > 0 ? "+" : ""}${map.change.toFixed(1)}%`;
const barClass = index === 0 ? "rle-pattern" : "rle-irregular";
return `
<article class="card">
<div class="card-head">
<div>
<h2 class="card-title">${map.title}</h2>
<div class="card-subtitle">${map.subtitle}</div>
</div>
<span class="badge ${badgeClass}">
${improves ? "RLE compresses" : "RLE expands"}
</span>
</div>
<div class="metrics">
<div class="metric">
<span>Raw</span>
<strong>${map.rawBytes} B</strong>
</div>
<div class="metric">
<span>Toy RLE</span>
<strong>${map.rleBytes} B</strong>
</div>
<div class="metric">
<span>Vs raw</span>
<strong class="${metricClass}">${changeText}</strong>
</div>
</div>
<div class="encoding">
<div class="encoding-head">
<span>Raw · one token per cell</span>
<b>${map.rawBytes} chars</b>
</div>
<code class="stream">${map.raw}</code>
</div>
<div class="encoding">
<div class="encoding-head">
<span>RLE · 2-digit count + token · ${map.runs} runs</span>
<b>${map.rleBytes} chars</b>
</div>
<code class="stream rle">${map.rle}</code>
</div>
${bar("RAW", map.rawBytes)}
${bar("RLE", map.rleBytes, barClass)}
</article>
`;
}).join("")}
<div class="caveat">
<b>One scheme, two outcomes:</b>
run-length encoding favors long equal-value runs and can make irregular data larger.
Real codecs may add dictionaries, probability models, or entropy coding; their gains
depend on the data. ASCII characters are used here only as a toy byte proxy.
</div>
`;
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, wheel zoom, and touch pinch
// -------------------------------------------------------------------------
const pointers = new Map();
let dragMode = "orbit";
let dragLast = null;
let pinchStartDistance = 0;
let pinchStartCameraDistance = desiredView.distance;
const clamp = THREE.MathUtils.clamp;
function pointerDistance() {
const points = [...pointers.values()];
if (points.length < 2) return 0;
return Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
}
function panView(dx, dy) {
const scale = desiredView.distance * 0.00135;
const rightX = Math.cos(desiredView.yaw);
const rightZ = -Math.sin(desiredView.yaw);
desiredView.target.x -= dx * scale * rightX;
desiredView.target.z -= dx * scale * rightZ;
desiredView.target.y += dy * scale;
}
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
dragMode = event.shiftKey || event.button === 2 ? "pan" : "orbit";
dragLast = { x: event.clientX, y: event.clientY };
} else if (pointers.size === 2) {
dragMode = "pinch";
pinchStartDistance = pointerDistance();
pinchStartCameraDistance = desiredView.distance;
}
});
canvas.addEventListener("pointermove", event => {
if (pointers.has(event.pointerId)) {
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
}
if (pointers.size === 1 && dragLast) {
const dx = event.clientX - dragLast.x;
const dy = event.clientY - dragLast.y;
if (dragMode === "pan") {
panView(dx, dy);
} else {
desiredView.yaw -= dx * 0.006;
desiredView.pitch = clamp(
desiredView.pitch + dy * 0.005,
0.20,
1.25
);
}
dragLast = { x: event.clientX, y: event.clientY };
} else if (pointers.size >= 2 && pinchStartDistance > 0) {
const distance = pointerDistance();
if (distance > 0) {
desiredView.distance = clamp(
pinchStartCameraDistance * pinchStartDistance / distance,
12,
38
);
}
}
updateHover(event);
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 1) {
const remaining = [...pointers.values()][0];
dragLast = remaining;
dragMode = "orbit";
pinchStartDistance = 0;
} else if (pointers.size === 0) {
dragLast = null;
pinchStartDistance = 0;
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
desiredView.distance = clamp(
desiredView.distance * Math.exp(event.deltaY * 0.001),
12,
38
);
},
{ passive: false }
);
canvas.addEventListener("contextmenu", event => event.preventDefault());
document.querySelector("#reset").addEventListener("click", () => {
desiredView.yaw = 0.17;
desiredView.pitch = 0.60;
desiredView.distance = 23;
desiredView.target.set(0, 1.35, 0);
});
const explodeButton = document.querySelector("#explode");
explodeButton.addEventListener("click", () => {
const enabled = explodeButton.getAttribute("aria-pressed") !== "true";
explodeButton.setAttribute("aria-pressed", String(enabled));
explodeButton.textContent = enabled ? "Stack voxels" : "Explode voxels";
maps.forEach(map => {
map.explosionTarget = enabled ? 1 : 0;
});
});
// -------------------------------------------------------------------------
// Cell inspection
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updateHover(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(
maps.map(map => map.tiles),
false
);
if (!hits.length) {
tooltip.style.display = "none";
return;
}
const hit = hits[0];
const map = maps[hit.object.userData.mapIndex];
const cell = hit.instanceId;
const row = Math.floor(cell / GRID_SIZE);
const col = cell % GRID_SIZE;
const value = map.values[cell];
tooltip.innerHTML = `
<strong>${map.title}</strong><br>
row ${row}, column ${col}<br>
token ${TOKENS[value]} → height ${value}
`;
tooltip.style.display = "block";
tooltip.style.left = `${Math.min(event.clientX + 15, window.innerWidth - 195)}px`;
tooltip.style.top = `${Math.min(event.clientY + 15, window.innerHeight - 90)}px`;
}
canvas.addEventListener("pointerleave", () => {
if (!pointers.size) tooltip.style.display = "none";
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (width < 700) {
desiredView.distance = Math.max(25, 13 / camera.aspect);
}
}
window.addEventListener("resize", resize);
resize();
const clock = new THREE.Clock();
const dummy = new THREE.Object3D();
function updateVoxelStack(map) {
const previous = map.explosion;
map.explosion +=
(map.explosionTarget - map.explosion) * (1 - Math.exp(-clock.getDelta() * 8));
if (Math.abs(map.explosion - previous) < 0.0001 &&
Math.abs(map.explosion - map.explosionTarget) < 0.001) {
map.explosion = map.explosionTarget;
}
for (let i = 0; i < map.voxelData.length; i++) {
const item = map.voxelData[i];
dummy.position.set(
item.x,
item.y + item.level * map.explosion * 1.12,
item.z
);
dummy.updateMatrix();
map.voxels.setMatrixAt(i, dummy.matrix);
}
map.voxels.instanceMatrix.needsUpdate = true;
}
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const damping = 1 - Math.exp(-dt * 8);
currentView.yaw += (desiredView.yaw - currentView.yaw) * damping;
currentView.pitch += (desiredView.pitch - currentView.pitch) * damping;
currentView.distance +=
(desiredView.distance - currentView.distance) * damping;
currentView.target.lerp(desiredView.target, damping);
const horizontal = Math.cos(currentView.pitch) * currentView.distance;
camera.position.set(
currentView.target.x + Math.sin(currentView.yaw) * horizontal,
currentView.target.y + Math.sin(currentView.pitch) * currentView.distance,
currentView.target.z + Math.cos(currentView.yaw) * horizontal
);
camera.lookAt(currentView.target);
particles.rotation.y += dt * 0.008;
maps.forEach(updateVoxelStack);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```