Prompt specification
Build or customize the Three.js 3D scene "Generate a Connected Tiny Maze" 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: Generate a Connected Tiny Maze
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/generate-a-connected-tiny-maze-x3490
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring generated levels with guaranteed connected routes. Create a seeded maze on a small grid and show its construction steps. Confirm that every carved cell remains reachable from the start under the declared algorithm. Voxel style.
Working Three.js Starter (generate-a-connected-tiny-maze-x3490):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Maze — Seeded Connected Levels</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(8, 18, 32, 0.86);
--panel-border: rgba(119, 169, 216, 0.2);
--text: #e8f3ff;
--muted: #8ea7bf;
--cyan: #5ee7ff;
--green: #53e39b;
--orange: #ffb454;
--red: #ff6b7d;
}
* {
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;
}
button,
input,
select {
font: inherit;
}
button {
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
z-index: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 35%, rgba(0, 5, 13, 0.28) 100%),
linear-gradient(180deg, rgba(3, 9, 17, 0.15), transparent 25%, transparent 72%, rgba(3, 9, 17, 0.38));
}
.hud {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 15px;
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.brand {
position: absolute;
top: 24px;
left: 25px;
max-width: 430px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.65);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 4px;
font-size: clamp(29px, 3.6vw, 52px);
line-height: 0.95;
letter-spacing: -0.055em;
font-weight: 900;
}
h1 span {
color: var(--cyan);
margin-left: 0.22em;
}
.brand p {
margin: 10px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
max-width: 390px;
}
.algorithm-chip {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 12px;
padding: 6px 9px;
border: 1px solid rgba(94, 231, 255, 0.22);
border-radius: 7px;
color: #bcefff;
background: rgba(26, 83, 105, 0.24);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.algorithm-chip::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.controls {
position: absolute;
top: 22px;
right: 22px;
width: 310px;
padding: 16px;
max-height: calc(100vh - 44px);
overflow: auto;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
color: #c7d9ea;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.section-title span {
color: var(--muted);
font-weight: 600;
letter-spacing: 0.03em;
text-transform: none;
}
.seed-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 7px;
}
input[type="text"],
select {
min-width: 0;
border: 1px solid rgba(133, 176, 214, 0.22);
border-radius: 8px;
background: rgba(1, 8, 17, 0.58);
color: var(--text);
padding: 9px 10px;
outline: none;
}
input[type="text"]:focus,
select:focus {
border-color: rgba(94, 231, 255, 0.7);
box-shadow: 0 0 0 3px rgba(94, 231, 255, 0.08);
}
.button-row {
display: flex;
gap: 7px;
margin-top: 8px;
}
button {
border: 1px solid rgba(137, 180, 218, 0.2);
border-radius: 8px;
background: rgba(31, 57, 83, 0.55);
padding: 8px 10px;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
}
button:hover {
background: rgba(48, 83, 116, 0.7);
border-color: rgba(94, 231, 255, 0.42);
}
button:active {
transform: translateY(1px);
}
.primary {
color: #03202a;
border-color: transparent;
background: var(--cyan);
font-weight: 800;
}
.primary:hover {
background: #8beeff;
}
.small {
flex: 1;
font-size: 11px;
}
.route-toggle {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
color: #b8cadd;
font-size: 11px;
cursor: pointer;
user-select: none;
}
.route-toggle input {
accent-color: var(--cyan);
}
.camera-row {
display: flex;
align-items: center;
gap: 7px;
margin-top: 12px;
}
.camera-row button {
flex: 1;
font-size: 10px;
padding: 7px;
}
.camera-hint {
margin-left: auto;
color: var(--muted);
font-size: 9px;
}
#eventLog {
display: grid;
gap: 3px;
margin-top: 8px;
max-height: 164px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #28465e transparent;
}
.log-row {
display: grid;
grid-template-columns: 34px 1fr;
gap: 7px;
width: 100%;
padding: 6px 7px;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: #8199b0;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-align: left;
}
.log-row.current {
color: #d8f9ff;
border-color: rgba(94, 231, 255, 0.26);
background: rgba(37, 106, 128, 0.22);
}
.log-row.future {
opacity: 0.48;
}
.log-row b {
color: var(--cyan);
font-weight: 700;
}
.status {
position: absolute;
left: 22px;
bottom: 22px;
width: 350px;
padding: 16px;
}
.metrics {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
}
.metric {
min-width: 0;
padding: 8px 7px;
border-radius: 8px;
background: rgba(18, 42, 66, 0.45);
}
.metric span {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric b {
display: block;
margin-top: 4px;
overflow: hidden;
color: #eaf7ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.progress {
height: 5px;
margin: 13px 0 10px;
overflow: hidden;
border-radius: 99px;
background: rgba(99, 133, 165, 0.16);
}
.progress i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #368dff, var(--cyan));
box-shadow: 0 0 15px rgba(94, 231, 255, 0.6);
transition: width 180ms ease;
}
.audit-badge {
display: block;
padding: 8px 10px;
border: 1px solid rgba(83, 227, 155, 0.25);
border-radius: 8px;
color: #a8f4cd;
background: rgba(30, 113, 75, 0.16);
font-size: 10px;
font-weight: 800;
line-height: 1.4;
}
.audit-badge.fail {
color: #ffc0c8;
border-color: rgba(255, 107, 125, 0.35);
background: rgba(135, 29, 47, 0.25);
}
.proof {
margin-top: 10px;
color: #91a9bf;
font-size: 10px;
line-height: 1.55;
}
.proof strong {
color: #d5e9f8;
}
.proof code {
color: #b8ecff;
font-size: 9px;
}
.timeline {
position: absolute;
left: 50%;
bottom: 22px;
width: min(590px, calc(100vw - 810px));
min-width: 420px;
transform: translateX(-50%);
padding: 13px 15px;
}
.timeline-top {
display: flex;
align-items: center;
gap: 10px;
}
#playButton {
width: 78px;
flex: 0 0 auto;
}
#timelineRange {
flex: 1;
min-width: 80px;
accent-color: var(--cyan);
cursor: pointer;
}
#stepCount {
min-width: 75px;
color: #a9bed1;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-align: right;
}
.timeline-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 9px;
}
#eventDescription {
min-width: 0;
overflow: hidden;
color: #b8ccdc;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.speed-control {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 6px;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
}
.speed-control select {
padding: 5px 7px;
font-size: 10px;
}
@media (max-width: 1050px) {
.timeline {
left: auto;
right: 22px;
width: 430px;
min-width: 0;
transform: none;
}
.status {
width: 310px;
}
}
@media (max-width: 780px) {
.brand p,
.camera-hint {
display: none;
}
.controls {
top: 16px;
right: 14px;
width: 260px;
max-height: 58vh;
}
.status {
display: none;
}
.timeline {
right: 14px;
bottom: 14px;
left: 14px;
width: auto;
}
}
@media (max-width: 520px) {
.brand {
top: 15px;
left: 15px;
}
h1 {
font-size: 27px;
}
.brand .eyebrow,
.algorithm-chip {
display: none;
}
.controls {
top: auto;
right: 12px;
bottom: 112px;
width: 220px;
max-height: 43vh;
}
.timeline {
right: 12px;
bottom: 12px;
left: 12px;
}
#eventDescription {
max-width: 55vw;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<main class="hud">
<header class="brand">
<div class="eyebrow">Connected Level Generator</div>
<h1>VOXEL<span>MAZE</span></h1>
<p>
A seeded, perfect maze built one carved edge at a time.
Scrub the timeline to inspect every DFS construction state.
</p>
<div class="algorithm-chip">Randomized depth-first search</div>
</header>
<section class="panel controls">
<div class="section-title">
Level controls
<span id="goalStatus">Goal pending</span>
</div>
<form id="seedForm" class="seed-row">
<input
id="seedInput"
type="text"
value="VOXEL-2049"
maxlength="28"
aria-label="Maze seed"
spellcheck="false"
>
<button class="primary" type="submit">Build</button>
</form>
<div class="button-row">
<button id="newSeedButton" class="small" type="button">New seed</button>
<button id="nextLevelButton" class="small" type="button">Next level</button>
</div>
<label class="route-toggle">
<input id="routeToggle" type="checkbox" checked>
Show shortest start-to-goal route
</label>
<div class="camera-row">
<button id="isoButton" type="button">Isometric</button>
<button id="topButton" type="button">Top</button>
<button id="resetCameraButton" type="button">Reset</button>
<span class="camera-hint">Drag / wheel</span>
</div>
<div class="section-title" style="margin-top: 15px;">
Construction log
<span>Click a step</span>
</div>
<div id="eventLog"></div>
</section>
<section class="panel status">
<div class="section-title">
Connectivity monitor
<span>Runtime BFS audit</span>
</div>
<div class="metrics">
<div class="metric">
<span>Level</span>
<b id="levelValue">01</b>
</div>
<div class="metric">
<span>Seed</span>
<b id="seedValue">—</b>
</div>
<div class="metric">
<span>Reachable</span>
<b id="reachableValue">1/1</b>
</div>
<div class="metric">
<span>Edges</span>
<b id="edgeValue">0</b>
</div>
</div>
<div class="progress"><i id="progressBar"></i></div>
<div id="auditBadge" class="audit-badge">Running reachability audit…</div>
<div class="proof">
<strong>Declared algorithm:</strong>
mark the start visited; repeatedly select a random unvisited orthogonal
neighbor of the DFS stack top and carve one edge to it; otherwise pop
the stack. Carved edges are never removed.
<br><br>
<strong>Reachability invariant:</strong>
a newly carved cell is attached by one edge to an already reachable
parent. Backtracking only moves the cursor. Therefore every carved
cell remains reachable from the start at every construction prefix.
The BFS audit checks all prefixes, not only the completed level.
</div>
<div class="button-row">
<button id="verifyButton" class="small" type="button">Run BFS audit again</button>
</div>
</section>
<section class="panel timeline">
<div class="timeline-top">
<button id="playButton" class="primary" type="button">▶ Play</button>
<button id="restartButton" type="button" aria-label="Restart construction">↺</button>
<input
id="timelineRange"
type="range"
min="0"
max="1"
value="0"
aria-label="Construction step"
>
<span id="stepCount">0 / 0</span>
</div>
<div class="timeline-bottom">
<span id="eventDescription">Seeded start at A1</span>
<label class="speed-control">
Speed
<select id="speedSelect">
<option value="2">2×</option>
<option value="5" selected>5×</option>
<option value="10">10×</option>
<option value="20">20×</option>
</select>
</label>
</div>
</section>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const GRID_SIZE = 9;
const TOTAL_CELLS = GRID_SIZE * GRID_SIZE;
const CELL_SPACING = 1.12;
const WALL_THICKNESS = 0.14;
const WALL_HEIGHT = 0.82;
const START = 0;
const GOAL = TOTAL_CELLS - 1;
const COLORS = {
background: 0x07101d,
visited: new THREE.Color(0x466987),
stack: new THREE.Color(0x53c8ef),
current: new THREE.Color(0x6ee7ff),
start: new THREE.Color(0x53e39b),
goal: new THREE.Color(0xffb454),
route: new THREE.Color(0x73f2ff)
};
const mount = document.getElementById("scene");
// -------------------------------------------------------------------------
// Renderer, camera, lights, and scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 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.12;
mount.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
scene.fog = new THREE.Fog(COLORS.background, 27, 52);
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
const cameraTarget = new THREE.Vector3();
let cameraAzimuth = 0.72;
let cameraPolar = 0.82;
const cameraRadius = 25;
const hemisphere = new THREE.HemisphereLight(0xaed5ff, 0x07101a, 1.65);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 2.45);
sun.position.set(8, 14, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0003;
scene.add(sun);
const coolRim = new THREE.DirectionalLight(0x4cc9ff, 0.8);
coolRim.position.set(-8, 5, -10);
scene.add(coolRim);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x07101b,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.24;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(
GRID_SIZE * CELL_SPACING + 10,
GRID_SIZE + 10,
0x17334c,
0x0d1d2d
);
grid.position.y = -0.22;
grid.material.transparent = true;
grid.material.opacity = 0.28;
grid.material.depthWrite = false;
scene.add(grid);
const base = new THREE.Mesh(
new THREE.BoxGeometry(
GRID_SIZE * CELL_SPACING + 0.65,
0.18,
GRID_SIZE * CELL_SPACING + 0.65
),
new THREE.MeshStandardMaterial({
color: 0x0b1725,
roughness: 0.92,
metalness: 0.04
})
);
base.position.y = -0.12;
base.receiveShadow = true;
scene.add(base);
// -------------------------------------------------------------------------
// Maze coordinate helpers
// -------------------------------------------------------------------------
function cellX(x) {
return (x - (GRID_SIZE - 1) / 2) * CELL_SPACING;
}
function cellZ(z) {
return (z - (GRID_SIZE - 1) / 2) * CELL_SPACING;
}
function cellPosition(id) {
const x = id % GRID_SIZE;
const z = Math.floor(id / GRID_SIZE);
return new THREE.Vector3(cellX(x), 0, cellZ(z));
}
function edgeKey(a, b) {
return a < b ? `${a}:${b}` : `${b}:${a}`;
}
function cellLabel(id) {
const x = id % GRID_SIZE;
const z = Math.floor(id / GRID_SIZE);
return `${String.fromCharCode(65 + x)}${z + 1}`;
}
function orthogonalNeighbors(id) {
const x = id % GRID_SIZE;
const z = Math.floor(id / GRID_SIZE);
const neighbors = [];
if (x > 0) neighbors.push(id - 1);
if (x < GRID_SIZE - 1) neighbors.push(id + 1);
if (z > 0) neighbors.push(id - GRID_SIZE);
if (z < GRID_SIZE - 1) neighbors.push(id + GRID_SIZE);
return neighbors;
}
// -------------------------------------------------------------------------
// Seeded RNG and maze generation
//
// Algorithm:
// 1. Mark the start visited.
// 2. Keep a DFS stack beginning with the start.
// 3. At the stack top, choose a random unvisited orthogonal neighbor.
// 4. Carve one edge to that neighbor, mark it visited, and push it.
// 5. If none exists, pop the stack. Edges are never removed.
//
// Invariant:
// Each newly visited cell receives exactly one edge from an already
// visited, reachable parent. Thus every visited/carved cell is reachable
// from the start at every construction prefix.
// -------------------------------------------------------------------------
function hashSeed(text) {
let hash = 2166136261;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function mulberry32(seed) {
let value = seed >>> 0;
return function random() {
value += 0x6d2b79f5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
function generateMaze(seedText) {
const random = mulberry32(hashSeed(seedText));
const visited = new Uint8Array(TOTAL_CELLS);
const edges = [];
const stack = [START];
const states = [];
visited[START] = 1;
states.push({
visited: Array.from(visited),
edges: edges.map(edge => edge.slice()),
stack: stack.slice(),
current: START,
event: { type: "start", from: START, to: START }
});
while (stack.length > 0) {
const current = stack[stack.length - 1];
const candidates = orthogonalNeighbors(current).filter(id => !visited[id]);
if (candidates.length > 0) {
const next = candidates[Math.floor(random() * candidates.length)];
visited[next] = 1;
edges.push([current, next]);
stack.push(next);
states.push({
visited: Array.from(visited),
edges: edges.map(edge => edge.slice()),
stack: stack.slice(),
current: next,
event: { type: "carve", from: current, to: next }
});
} else {
stack.pop();
const next = stack.length > 0 ? stack[stack.length - 1] : START;
states.push({
visited: Array.from(visited),
edges: edges.map(edge => edge.slice()),
stack: stack.slice(),
current: next,
event: { type: "backtrack", from: current, to: next }
});
}
}
return states;
}
// -------------------------------------------------------------------------
// BFS audit and shortest route
// -------------------------------------------------------------------------
function breadthFirstSearch(state) {
const adjacency = Array.from({ length: TOTAL_CELLS }, () => []);
const parent = new Int32Array(TOTAL_CELLS);
parent.fill(-1);
const seen = new Uint8Array(TOTAL_CELLS);
const queue = new Int32Array(TOTAL_CELLS);
let head = 0;
let tail = 0;
for (const [a, b] of state.edges) {
adjacency[a].push(b);
adjacency[b].push(a);
}
queue[tail++] = START;
seen[START] = 1;
let count = 1;
while (head < tail) {
const current = queue[head++];
for (const next of adjacency[current]) {
if (seen[next]) continue;
seen[next] = 1;
parent[next] = current;
queue[tail++] = next;
count++;
}
}
return { seen, parent, count };
}
function shortestRoute(state) {
const { seen, parent } = breadthFirstSearch(state);
if (!seen[GOAL]) return [];
const route = [];
let current = GOAL;
while (current !== -1) {
route.push(current);
if (current === START) break;
current = parent[current];
}
route.reverse();
return route;
}
function auditMaze(states) {
const failures = [];
for (let i = 0; i < states.length; i++) {
const state = states[i];
const visitedCount = state.visited.reduce((sum, value) => sum + value, 0);
const result = breadthFirstSearch(state);
if (result.count !== visitedCount) {
failures.push(i);
}
}
const finalState = states[states.length - 1];
const finalVisited = finalState.visited.reduce((sum, value) => sum + value, 0);
const finalReachable = breadthFirstSearch(finalState).count;
const finalEdges = finalState.edges.length;
const perfectTree =
finalVisited === TOTAL_CELLS &&
finalReachable === TOTAL_CELLS &&
finalEdges === TOTAL_CELLS - 1;
return {
pass: failures.length === 0 && perfectTree,
failures,
finalVisited,
finalReachable,
finalEdges
};
}
// -------------------------------------------------------------------------
// Instanced voxel geometry
// -------------------------------------------------------------------------
const floorMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.82,
metalness: 0.06
}),
TOTAL_CELLS
);
floorMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
floorMesh.receiveShadow = true;
floorMesh.frustumCulled = false;
scene.add(floorMesh);
const wallSpecs = [];
for (let z = 0; z < GRID_SIZE; z++) {
for (let x = 0; x < GRID_SIZE; x++) {
const id = z * GRID_SIZE + x;
if (x < GRID_SIZE - 1) {
wallSpecs.push({
key: edgeKey(id, id + 1),
x: cellX(x) + CELL_SPACING / 2,
z: cellZ(z),
sx: WALL_THICKNESS,
sy: WALL_HEIGHT,
sz: CELL_SPACING * 1.01,
outer: false
});
}
if (z < GRID_SIZE - 1) {
wallSpecs.push({
key: edgeKey(id, id + GRID_SIZE),
x: cellX(x),
z: cellZ(z) + CELL_SPACING / 2,
sx: CELL_SPACING * 1.01,
sy: WALL_HEIGHT,
sz: WALL_THICKNESS,
outer: false
});
}
}
}
for (let z = 0; z < GRID_SIZE; z++) {
wallSpecs.push({
key: null,
x: cellX(0) - CELL_SPACING / 2,
z: cellZ(z),
sx: WALL_THICKNESS,
sy: WALL_HEIGHT,
sz: CELL_SPACING * 1.01,
outer: true
});
wallSpecs.push({
key: null,
x: cellX(GRID_SIZE - 1) + CELL_SPACING / 2,
z: cellZ(z),
sx: WALL_THICKNESS,
sy: WALL_HEIGHT,
sz: CELL_SPACING * 1.01,
outer: true
});
}
for (let x = 0; x < GRID_SIZE; x++) {
wallSpecs.push({
key: null,
x: cellX(x),
z: cellZ(0) - CELL_SPACING / 2,
sx: CELL_SPACING * 1.01,
sy: WALL_HEIGHT,
sz: WALL_THICKNESS,
outer: true
});
wallSpecs.push({
key: null,
x: cellX(x),
z: cellZ(GRID_SIZE - 1) + CELL_SPACING / 2,
sx: CELL_SPACING * 1.01,
sy: WALL_HEIGHT,
sz: WALL_THICKNESS,
outer: true
});
}
const wallMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.76,
metalness: 0.09
}),
wallSpecs.length
);
wallMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
wallMesh.castShadow = true;
wallMesh.receiveShadow = true;
wallMesh.frustumCulled = false;
scene.add(wallMesh);
const routeMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: COLORS.route,
emissive: 0x176b80,
emissiveIntensity: 1.25,
roughness: 0.35,
metalness: 0.12
}),
TOTAL_CELLS
);
routeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
routeMesh.frustumCulled = false;
scene.add(routeMesh);
const currentMarker = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(
CELL_SPACING * 0.57,
0.25,
CELL_SPACING * 0.57
)
),
new THREE.LineBasicMaterial({
color: 0x7cf1ff,
transparent: true,
opacity: 0.95
})
);
currentMarker.position.y = 0.27;
scene.add(currentMarker);
const carvePulse = new THREE.Mesh(
new THREE.BoxGeometry(0.26, 0.26, 0.26),
new THREE.MeshBasicMaterial({
color: 0xffc06a,
transparent: true,
opacity: 0.8,
depthWrite: false
})
);
carvePulse.visible = false;
scene.add(carvePulse);
const startMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.25, 0.25),
new THREE.MeshStandardMaterial({
color: COLORS.start,
emissive: 0x187f51,
emissiveIntensity: 0.8,
roughness: 0.4
})
);
startMarker.position.copy(cellPosition(START));
startMarker.position.y = 0.35;
startMarker.castShadow = true;
scene.add(startMarker);
const goalMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.28, 0.28),
new THREE.MeshStandardMaterial({
color: COLORS.goal,
emissive: 0xa8580b,
emissiveIntensity: 0.95,
transparent: true,
opacity: 0.3,
roughness: 0.35
})
);
goalMarker.position.copy(cellPosition(GOAL));
goalMarker.position.y = 0.36;
goalMarker.castShadow = true;
scene.add(goalMarker);
const goalLight = new THREE.PointLight(COLORS.goal, 0.8, 3.5, 2);
goalLight.position.copy(goalMarker.position);
scene.add(goalLight);
function createLabel(text, color) {
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(4, 12, 23, 0.82)";
context.fillRect(20, 22, 472, 84);
context.strokeStyle = color;
context.lineWidth = 5;
context.strokeRect(20, 22, 472, 84);
context.fillStyle = color;
context.font = "bold 48px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.65, 0.41, 1);
sprite.renderOrder = 20;
return sprite;
}
const startLabel = createLabel("START", "#53e39b");
startLabel.position.copy(cellPosition(START));
startLabel.position.y = 1.25;
scene.add(startLabel);
const goalLabel = createLabel("GOAL", "#ffb454");
goalLabel.position.copy(cellPosition(GOAL));
goalLabel.position.y = 1.25;
scene.add(goalLabel);
const dummy = new THREE.Object3D();
// -------------------------------------------------------------------------
// UI state
// -------------------------------------------------------------------------
const seedInput = document.getElementById("seedInput");
const seedForm = document.getElementById("seedForm");
const newSeedButton = document.getElementById("newSeedButton");
const nextLevelButton = document.getElementById("nextLevelButton");
const verifyButton = document.getElementById("verifyButton");
const playButton = document.getElementById("playButton");
const restartButton = document.getElementById("restartButton");
const timelineRange = document.getElementById("timelineRange");
const speedSelect = document.getElementById("speedSelect");
const routeToggle = document.getElementById("routeToggle");
const eventLog = document.getElementById("eventLog");
const eventDescription = document.getElementById("eventDescription");
const stepCount = document.getElementById("stepCount");
const levelValue = document.getElementById("levelValue");
const seedValue = document.getElementById("seedValue");
const reachableValue = document.getElementById("reachableValue");
const edgeValue = document.getElementById("edgeValue");
const progressBar = document.getElementById("progressBar");
const auditBadge = document.getElementById("auditBadge");
const goalStatus = document.getElementById("goalStatus");
let mazeStates = [];
let currentStep = 0;
let currentLevel = 1;
let currentSeed = "VOXEL-2049";
let playing = false;
let playbackAccumulator = 0;
let goalFoundStep = -1;
function describeState(index, state) {
if (index === 0) return `Seeded start at ${cellLabel(START)}`;
const event = state.event;
if (event.type === "carve") {
return `Carve ${cellLabel(event.to)} ← ${cellLabel(event.from)}`;
}
return `Backtrack ${cellLabel(event.from)} → ${cellLabel(event.to)}`;
}
function renderEventLog() {
eventLog.replaceChildren();
const first = Math.max(0, currentStep - 5);
const last = Math.min(mazeStates.length, first + 10);
for (let i = first; i < last; i++) {
const row = document.createElement("button");
row.type = "button";
row.className = "log-row";
if (i === currentStep) row.classList.add("current");
if (i > currentStep) row.classList.add("future");
const number = document.createElement("b");
number.textContent = String(i).padStart(3, "0");
const description = document.createElement("span");
description.textContent = describeState(i, mazeStates[i]);
row.append(number, description);
row.addEventListener("click", () => {
setPlaying(false);
setStep(i);
});
eventLog.appendChild(row);
}
const currentRow = eventLog.querySelector(".current");
if (currentRow) {
eventLog.scrollTop = Math.max(
0,
currentRow.offsetTop - eventLog.clientHeight / 2 + currentRow.clientHeight / 2
);
}
}
function applyStateVisuals(state) {
const openedEdges = new Set(
state.edges.map(([a, b]) => edgeKey(a, b))
);
const stackCells = new Set(state.stack);
const visitedCount = state.visited.reduce((sum, value) => sum + value, 0);
// Floors: only carved/visited cells receive a room floor.
for (let id = 0; id < TOTAL_CELLS; id++) {
const x = id % GRID_SIZE;
const z = Math.floor(id / GRID_SIZE);
dummy.rotation.set(0, 0, 0);
if (state.visited[id]) {
dummy.position.set(cellX(x), 0.045, cellZ(z));
dummy.scale.set(
CELL_SPACING * 0.94,
0.12,
CELL_SPACING * 0.94
);
let color = COLORS.visited;
if (id === START) color = COLORS.start;
else if (id === GOAL) color = COLORS.goal;
else if (stackCells.has(id)) color = COLORS.stack;
else if (id === state.current) color = COLORS.current;
floorMesh.setColorAt(id, color);
} else {
dummy.position.set(cellX(x), -4, cellZ(z));
dummy.scale.set(0.001, 0.001, 0.001);
floorMesh.setColorAt(id, COLORS.visited);
}
dummy.updateMatrix();
floorMesh.setMatrixAt(id, dummy.matrix);
}
floorMesh.instanceMatrix.needsUpdate = true;
if (floorMesh.instanceColor) floorMesh.instanceColor.needsUpdate = true;
// Walls: removing a carved edge physically removes its wall segment.
let wallCount = 0;
for (const spec of wallSpecs) {
if (spec.key && openedEdges.has(spec.key)) continue;
dummy.position.set(spec.x, WALL_HEIGHT / 2, spec.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(spec.sx, spec.sy, spec.sz);
dummy.updateMatrix();
wallMesh.setMatrixAt(wallCount, dummy.matrix);
const variation = ((hashSeed(spec.key || `outer-${wallCount}`) % 9) - 4) * 0.006;
const wallColor = new THREE.Color(
spec.outer ? 0x1c3c5b : 0x294e6d
);
wallColor.offsetHSL(0, 0, variation);
wallMesh.setColorAt(wallCount, wallColor);
wallCount++;
}
wallMesh.count = wallCount;
wallMesh.instanceMatrix.needsUpdate = true;
if (wallMesh.instanceColor) wallMesh.instanceColor.needsUpdate = true;
// Current DFS cursor.
currentMarker.position.copy(cellPosition(state.current));
currentMarker.position.y = 0.27;
// A small gold voxel marks the most recently carved doorway.
if (state.event.type === "carve") {
const from = cellPosition(state.event.from);
const to = cellPosition(state.event.to);
carvePulse.position.set(
(from.x + to.x) / 2,
0.34,
(from.z + to.z) / 2
);
carvePulse.visible = true;
} else {
carvePulse.visible = false;
}
// The goal marker becomes solid once the goal has been carved.
const goalReached = Boolean(state.visited[GOAL]);
goalMarker.material.opacity = goalReached ? 1 : 0.28;
goalLight.intensity = goalReached ? 1.15 : 0.3;
// Shortest route through the currently carved graph.
const route = shortestRoute(state);
routeMesh.count = route.length;
route.forEach((id, index) => {
const position = cellPosition(id);
dummy.position.set(position.x, 0.19, position.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(0.15, 0.1, 0.15);
dummy.updateMatrix();
routeMesh.setMatrixAt(index, dummy.matrix);
});
routeMesh.instanceMatrix.needsUpdate = true;
routeMesh.visible = routeToggle.checked && route.length > 0;
// Readouts.
const bfs = breadthFirstSearch(state);
reachableValue.textContent = `${bfs.count}/${visitedCount}`;
edgeValue.textContent = String(state.edges.length);
progressBar.style.width = `${(visitedCount / TOTAL_CELLS) * 100}%`;
eventDescription.textContent = describeState(currentStep, state);
stepCount.textContent = `${currentStep} / ${mazeStates.length - 1}`;
timelineRange.value = String(currentStep);
goalStatus.textContent =
goalFoundStep >= 0 && currentStep >= goalFoundStep
? `Goal reached @ ${goalFoundStep}`
: "Goal pending";
}
function setStep(index) {
currentStep = Math.max(0, Math.min(index, mazeStates.length - 1));
applyStateVisuals(mazeStates[currentStep]);
renderEventLog();
}
function updateAuditBadge(result) {
auditBadge.classList.toggle("fail", !result.pass);
if (result.pass) {
auditBadge.textContent =
`✓ BFS PASS · ${mazeStates.length}/${mazeStates.length} construction prefixes verified`;
} else {
auditBadge.textContent =
`✕ Connectivity failure at construction prefixes: ${result.failures.join(", ")}`;
}
}
function buildLevel(seedText, level) {
currentSeed = String(seedText).trim() || "VOXEL-2049";
currentLevel = level;
seedInput.value = currentSeed;
levelValue.textContent = String(currentLevel).padStart(2, "0");
seedValue.textContent = currentSeed;
seedValue.title = currentSeed;
mazeStates = generateMaze(currentSeed);
goalFoundStep = mazeStates.findIndex(state => Boolean(state.visited[GOAL]));
timelineRange.max = String(mazeStates.length - 1);
setPlaying(false);
setStep(0);
const audit = auditMaze(mazeStates);
updateAuditBadge(audit);
}
// -------------------------------------------------------------------------
// Playback and controls
// -------------------------------------------------------------------------
function setPlaying(value) {
playing = value;
playbackAccumulator = 0;
playButton.textContent = playing ? "❚❚ Pause" : "▶ Play";
}
seedForm.addEventListener("submit", event => {
event.preventDefault();
buildLevel(seedInput.value, currentLevel);
});
newSeedButton.addEventListener("click", () => {
const randomValues = new Uint32Array(1);
crypto.getRandomValues(randomValues);
const seed = `S-${randomValues[0].toString(36).toUpperCase()}`;
buildLevel(seed, currentLevel + 1);
});
nextLevelButton.addEventListener("click", () => {
const numeric = Number.parseInt(currentSeed, 10);
const nextSeed = Number.isFinite(numeric)
? String(numeric + 1)
: (hashSeed(currentSeed) + currentLevel + 1).toString(36).toUpperCase();
buildLevel(nextSeed, currentLevel + 1);
});
verifyButton.addEventListener("click", () => {
const result = auditMaze(mazeStates);
updateAuditBadge(result);
if (typeof auditBadge.animate === "function") {
auditBadge.animate(
[
{ transform: "scale(1)", filter: "brightness(1)" },
{ transform: "scale(1.025)", filter: "brightness(1.4)" },
{ transform: "scale(1)", filter: "brightness(1)" }
],
{ duration: 480, easing: "ease-out" }
);
}
});
playButton.addEventListener("click", () => {
if (!playing && currentStep >= mazeStates.length - 1) {
setStep(0);
}
setPlaying(!playing);
});
restartButton.addEventListener("click", () => {
setPlaying(false);
setStep(0);
});
timelineRange.addEventListener("input", () => {
setPlaying(false);
setStep(Number(timelineRange.value));
});
routeToggle.addEventListener("change", () => {
if (mazeStates.length > 0) {
applyStateVisuals(mazeStates[currentStep]);
}
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, and zoom without external addons
// -------------------------------------------------------------------------
function updateCamera() {
const sinPolar = Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + cameraRadius * sinPolar * Math.sin(cameraAzimuth),
cameraTarget.y + cameraRadius * Math.cos(cameraPolar),
cameraTarget.z + cameraRadius * sinPolar * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resetCamera(isometric = true) {
cameraTarget.set(0, 0, 0);
cameraAzimuth = isometric ? 0.72 : 0;
cameraPolar = isometric ? 0.82 : 0.025;
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
}
document.getElementById("isoButton").addEventListener("click", () => {
resetCamera(true);
});
document.getElementById("topButton").addEventListener("click", () => {
resetCamera(false);
});
document.getElementById("resetCameraButton").addEventListener("click", () => {
resetCamera(true);
});
const canvas = renderer.domElement;
let drag = null;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0 && event.button !== 2) return;
drag = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
mode: event.button === 2 || event.shiftKey ? "pan" : "orbit"
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!drag || drag.id !== event.pointerId) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
if (drag.mode === "orbit") {
cameraAzimuth -= dx * 0.007;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar + dy * 0.006,
0.12,
1.38
);
} else {
const worldPerPixel =
(camera.top - camera.bottom) / camera.zoom / canvas.clientHeight;
const right = new THREE.Vector3(1, 0, 0)
.applyQuaternion(camera.quaternion);
right.y = 0;
right.normalize();
const forward = new THREE.Vector3(0, 0, -1)
.applyQuaternion(camera.quaternion);
forward.y = 0;
forward.normalize();
cameraTarget
.addScaledVector(right, -dx * worldPerPixel)
.addScaledVector(forward, -dy * worldPerPixel);
}
updateCamera();
});
function endDrag(event) {
if (!drag || drag.id !== event.pointerId) return;
drag = null;
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * Math.exp(-event.deltaY * 0.001),
0.55,
3.2
);
camera.updateProjectionMatrix();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
const verticalSize = aspect < 1 ? 13 / aspect : 13;
camera.left = (-verticalSize * aspect) / 2;
camera.right = (verticalSize * aspect) / 2;
camera.top = verticalSize / 2;
camera.bottom = -verticalSize / 2;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
resetCamera(true);
buildLevel("VOXEL-2049", 1);
let previousTime = performance.now();
function animate(time) {
requestAnimationFrame(animate);
const delta = Math.min(0.05, (time - previousTime) / 1000);
previousTime = time;
if (playing && mazeStates.length > 0) {
playbackAccumulator += delta * 1000;
const interval = 1000 / Number(speedSelect.value);
while (
playbackAccumulator >= interval &&
currentStep < mazeStates.length - 1
) {
playbackAccumulator -= interval;
setStep(currentStep + 1);
}
if (currentStep >= mazeStates.length - 1) {
setPlaying(false);
}
}
currentMarker.position.y = 0.27 + Math.sin(time * 0.004) * 0.025;
goalMarker.rotation.y += delta * 1.15;
goalMarker.rotation.x += delta * 0.43;
goalMarker.position.y = 0.36 + Math.sin(time * 0.0032) * 0.045;
goalLight.position.y = goalMarker.position.y;
if (carvePulse.visible) {
carvePulse.rotation.y += delta * 2.2;
const pulse = 1 + Math.sin(time * 0.009) * 0.12;
carvePulse.scale.setScalar(pulse);
carvePulse.material.opacity = 0.52 + Math.sin(time * 0.009) * 0.18;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```