Prompt specification
Build or customize the Three.js 3D scene "Translate Between Maps and Route Instructions" 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: Translate Between Maps and Route Instructions
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/translate-between-maps-and-route-instructions-x3432
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Create a bounded navigation puzzle converting a marked path into turn instructions and back. Detect information lost by either representation and preserve explicit start orientation.
Working Three.js Starter (translate-between-maps-and-route-instructions-x3432):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Turn — Navigation Representation Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: #0d1829;
--panel-2: #111f33;
--line: #263a54;
--text: #e8f1ff;
--muted: #91a5bf;
--cyan: #56e0ff;
--purple: #a879ff;
--gold: #ffd166;
--green: #62e6a7;
--red: #ff7185;
--amber: #ffbd66;
}
* {
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,
textarea {
font: inherit;
}
button {
border: 1px solid var(--line);
border-radius: 9px;
padding: 9px 11px;
color: var(--text);
background: #17263b;
cursor: pointer;
transition:
background 120ms ease,
border-color 120ms ease,
transform 120ms ease;
}
button:hover {
background: #20334d;
border-color: #3e5876;
}
button:active {
transform: translateY(1px);
}
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
button.primary {
color: #05111d;
font-weight: 750;
background: var(--cyan);
border-color: var(--cyan);
}
button.primary:hover {
background: #8beaff;
}
button.ghost {
background: transparent;
}
button.small {
padding: 6px 9px;
font-size: 12px;
}
input,
select,
textarea {
color: var(--text);
background: #081321;
border: 1px solid var(--line);
border-radius: 8px;
}
input,
select {
height: 36px;
padding: 6px 8px;
}
textarea {
width: 100%;
min-height: 116px;
resize: vertical;
padding: 10px;
line-height: 1.5;
font-family:
"SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 12px;
white-space: pre-wrap;
}
#app {
display: grid;
grid-template-columns: 390px minmax(0, 1fr);
grid-template-rows: 64px minmax(0, 1fr);
width: 100%;
height: 100%;
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 20px;
background: rgba(9, 18, 31, 0.96);
border-bottom: 1px solid var(--line);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-icon {
position: relative;
width: 34px;
height: 34px;
flex: 0 0 auto;
transform: rotate(45deg);
border: 2px solid var(--cyan);
border-radius: 7px;
box-shadow:
0 0 18px rgba(86, 224, 255, 0.18),
inset 0 0 12px rgba(86, 224, 255, 0.1);
}
.brand-icon::after {
content: "";
position: absolute;
inset: 8px;
border-radius: 3px;
background: var(--purple);
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: 0.01em;
}
.subtitle {
margin-top: 3px;
color: var(--muted);
font-size: 11px;
}
.header-status {
display: flex;
align-items: center;
gap: 10px;
flex: 0 0 auto;
}
#routeStatus {
color: var(--muted);
font-size: 12px;
}
#goalBadge {
padding: 6px 9px;
border: 1px solid #425064;
border-radius: 999px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
#goalBadge.reached {
color: #102016;
background: var(--green);
border-color: var(--green);
}
aside {
min-height: 0;
overflow: auto;
padding: 16px;
background: linear-gradient(180deg, #0d1829 0%, #0a1524 100%);
border-right: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #314861 transparent;
}
section {
padding-bottom: 16px;
margin-bottom: 16px;
border-bottom: 1px solid var(--line);
}
section:last-child {
margin-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
h2 {
margin: 0;
font-size: 13px;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
p {
margin: 0;
}
.hint {
margin-top: 7px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.pose-grid {
display: grid;
grid-template-columns: 1fr 1fr 1.35fr;
gap: 8px;
margin-top: 10px;
}
.field label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.field input,
.field select {
width: 100%;
}
.orientation-note {
display: flex;
gap: 9px;
align-items: flex-start;
margin-top: 10px;
padding: 9px 10px;
color: #c9d8ea;
background: rgba(168, 121, 255, 0.08);
border: 1px solid rgba(168, 121, 255, 0.24);
border-radius: 8px;
font-size: 11px;
line-height: 1.45;
}
.orientation-note strong {
color: #d7c5ff;
}
.rep-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 13px 0 7px;
}
.rep-label span:first-child {
font-size: 12px;
font-weight: 750;
}
.rep-label span:last-child {
color: var(--muted);
font-size: 10px;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 8px;
}
.button-row > button {
flex: 1;
}
.micro-actions {
display: flex;
gap: 7px;
margin-top: 8px;
}
.micro-actions button {
flex: 1;
}
.audit-list {
display: grid;
gap: 9px;
margin-top: 10px;
}
.audit-item {
padding: 10px;
background: rgba(17, 31, 51, 0.75);
border: 1px solid var(--line);
border-radius: 9px;
}
.audit-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 5px;
}
.audit-head strong {
font-size: 11px;
}
.audit-item p {
color: var(--muted);
font-size: 10.5px;
line-height: 1.48;
}
.badge {
flex: 0 0 auto;
padding: 3px 6px;
border: 1px solid #46566a;
border-radius: 999px;
color: #becce0;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.035em;
text-transform: uppercase;
}
.badge.ok {
color: #9af1c8;
background: rgba(98, 230, 167, 0.09);
border-color: rgba(98, 230, 167, 0.34);
}
.badge.warn {
color: #ffd49a;
background: rgba(255, 189, 102, 0.09);
border-color: rgba(255, 189, 102, 0.34);
}
.badge.bad {
color: #ffacb8;
background: rgba(255, 113, 133, 0.09);
border-color: rgba(255, 113, 133, 0.36);
}
.limit-box {
margin-top: 9px;
padding: 10px;
color: #d8c29f;
background: rgba(255, 189, 102, 0.065);
border: 1px solid rgba(255, 189, 102, 0.22);
border-radius: 8px;
font-size: 10.5px;
line-height: 1.48;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #172b43 0%, #091321 56%, #060d17 100%);
}
#viewport canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-overlay {
position: absolute;
z-index: 2;
pointer-events: none;
}
.scene-card {
padding: 10px 12px;
color: #c7d6e8;
background: rgba(7, 16, 29, 0.78);
border: 1px solid rgba(71, 97, 126, 0.7);
border-radius: 10px;
backdrop-filter: blur(8px);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.18);
}
.scene-top-left {
top: 16px;
left: 16px;
}
.scene-top-right {
top: 16px;
right: 16px;
pointer-events: auto;
}
.scene-bottom {
left: 50%;
bottom: 15px;
transform: translateX(-50%);
width: max-content;
max-width: calc(100% - 30px);
text-align: center;
font-size: 11px;
}
.scene-title {
color: var(--text);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 8px;
font-size: 10px;
}
.legend span {
display: flex;
align-items: center;
gap: 5px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 2px;
box-shadow: 0 0 8px currentColor;
}
.dot.start {
color: var(--purple);
background: var(--purple);
}
.dot.path {
color: var(--cyan);
background: var(--cyan);
}
.dot.goal {
color: var(--gold);
background: var(--gold);
}
.dot.block {
color: #52657e;
background: #52657e;
}
#toast {
position: absolute;
left: 50%;
top: 72px;
z-index: 10;
max-width: min(440px, calc(100% - 30px));
padding: 10px 13px;
color: var(--text);
background: rgba(8, 18, 31, 0.94);
border: 1px solid var(--line);
border-radius: 9px;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
font-size: 12px;
line-height: 1.4;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition:
opacity 160ms ease,
transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
border-color: rgba(255, 113, 133, 0.6);
}
#toast.success {
border-color: rgba(98, 230, 167, 0.6);
}
@media (max-width: 860px) {
html,
body {
overflow: auto;
}
#app {
grid-template-columns: 1fr;
grid-template-rows: 58px minmax(390px, 52vh) auto;
height: auto;
min-height: 100%;
}
header {
grid-column: 1;
padding: 0 13px;
}
.header-status #routeStatus {
display: none;
}
#viewport {
grid-row: 2;
}
aside {
grid-row: 3;
overflow: visible;
border-right: 0;
border-top: 1px solid var(--line);
}
.scene-bottom {
font-size: 10px;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-icon" aria-hidden="true"></div>
<div>
<h1>Voxel Turn</h1>
<div class="subtitle">Navigation representation lab</div>
</div>
</div>
<div class="header-status">
<span id="routeStatus">0 steps</span>
<span id="goalBadge">Goal not reached</span>
</div>
</header>
<aside>
<section>
<div class="section-title">
<h2>Explicit Start Pose</h2>
<span class="eyebrow">Shared metadata</span>
</div>
<p class="hint">
The start position and facing are stored separately from both route
representations. The arrow in the scene shows the active heading.
</p>
<div class="pose-grid">
<div class="field">
<label for="startX">Start X</label>
<input id="startX" type="number" min="0" max="7" value="1">
</div>
<div class="field">
<label for="startZ">Start Z</label>
<input id="startZ" type="number" min="0" max="7" value="6">
</div>
<div class="field">
<label for="startHeading">Facing</label>
<select id="startHeading">
<option value="N">North</option>
<option value="E">East</option>
<option value="S">South</option>
<option value="W">West</option>
</select>
</div>
</div>
<div class="orientation-note">
<span aria-hidden="true">↻</span>
<div>
<strong>Orientation is explicit.</strong> A path does not encode its
initial facing, and relative turns cannot be placed on the board
without it.
</div>
</div>
</section>
<section>
<div class="section-title">
<h2>Marked Path</h2>
<span class="eyebrow">Ordered cells</span>
</div>
<div class="rep-label">
<span>Path representation</span>
<span>one “x,z” per line</span>
</div>
<textarea
id="pathText"
spellcheck="false"
aria-label="Ordered path cells"
></textarea>
<div class="button-row">
<button id="pathToTurns" class="primary">Path → turns</button>
<button id="turnsToPath" class="primary">Turns → path</button>
</div>
<div class="micro-actions">
<button id="undo" class="ghost small">Undo cell</button>
<button id="clear" class="ghost small">Clear</button>
<button id="solve" class="ghost small">Load solution</button>
</div>
<p class="hint">
Click an adjacent floor tile to extend the marked path. Click an
existing path tile to trim the route back to it.
</p>
</section>
<section>
<div class="section-title">
<h2>Turn Program</h2>
<span class="eyebrow">Relative commands</span>
</div>
<div class="rep-label">
<span>Turn representation</span>
<span>F · L · R · U</span>
</div>
<textarea
id="turnText"
spellcheck="false"
aria-label="Turn instructions"
></textarea>
<p class="hint">
<strong>F</strong> moves one cell. <strong>L</strong>, <strong>R</strong>,
and <strong>U</strong> turn in place; U means a 180° turn. Each move is
preceded by the turn needed from the explicit heading.
</p>
<div class="button-row">
<button id="copyPath" class="ghost">Copy path bundle</button>
<button id="copyTurn" class="ghost">Copy turn bundle</button>
</div>
<p class="hint">
Bundles include the shared start pose, preventing either representation
from silently losing absolute placement or initial facing.
</p>
</section>
<section>
<div class="section-title">
<h2>Representation-Loss Audit</h2>
<span class="eyebrow">Live</span>
</div>
<div class="audit-list">
<div class="audit-item">
<div class="audit-head">
<strong>Path representation</strong>
<span id="auditPathBadge" class="badge">Checking</span>
</div>
<p id="auditPathText"></p>
</div>
<div class="audit-item">
<div class="audit-head">
<strong>Turn representation</strong>
<span id="auditTurnBadge" class="badge">Checking</span>
</div>
<p id="auditTurnText"></p>
</div>
<div class="audit-item">
<div class="audit-head">
<strong>Round-trip check</strong>
<span id="auditRoundBadge" class="badge">Checking</span>
</div>
<p id="auditRoundText"></p>
</div>
</div>
<div id="auditLimitText" class="limit-box"></div>
</section>
</aside>
<main id="viewport" aria-label="Interactive voxel navigation board">
<div class="scene-overlay scene-card scene-top-left">
<div class="scene-title">Bounded 8 × 8 voxel field</div>
<div class="legend">
<span><i class="dot start"></i>Start</span>
<span><i class="dot path"></i>Path</span>
<span><i class="dot goal"></i>Goal</span>
<span><i class="dot block"></i>Obstacle</span>
</div>
</div>
<div class="scene-overlay scene-top-right">
<button id="cameraReset" class="small">Reset camera</button>
</div>
<div class="scene-overlay scene-card scene-bottom">
Click a neighboring tile to mark · click a path tile to trim ·
drag to orbit · wheel to zoom
</div>
<div id="toast" role="status" aria-live="polite"></div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const ui = {
viewport: $("viewport"),
startX: $("startX"),
startZ: $("startZ"),
startHeading: $("startHeading"),
pathText: $("pathText"),
turnText: $("turnText"),
routeStatus: $("routeStatus"),
goalBadge: $("goalBadge"),
toast: $("toast")
};
const GRID = 8;
const CELL = 1;
const GOAL = { x: 6, z: 1 };
const BLOCKED = new Set([
"2,6",
"3,6",
"3,5",
"3,4",
"3,3",
"2,3",
"4,3",
"5,3",
"4,2",
"5,2",
"6,5",
"5,5",
"6,6"
]);
const DIRECTIONS = {
N: { x: 0, z: -1 },
E: { x: 1, z: 0 },
S: { x: 0, z: 1 },
W: { x: -1, z: 0 }
};
const LEFT = {
N: "W",
E: "N",
S: "E",
W: "S"
};
const RIGHT = {
N: "E",
E: "S",
S: "W",
W: "N"
};
const OPPOSITE = {
N: "S",
E: "W",
S: "N",
W: "E"
};
const HEADING_NAMES = {
N: "North",
E: "East",
S: "South",
W: "West"
};
const defaultPath = () => [
{ x: 1, z: 6 },
{ x: 1, z: 5 },
{ x: 1, z: 4 },
{ x: 1, z: 3 },
{ x: 1, z: 2 },
{ x: 1, z: 1 },
{ x: 2, z: 1 },
{ x: 3, z: 1 },
{ x: 4, z: 1 },
{ x: 5, z: 1 },
{ x: 6, z: 1 }
];
const state = {
start: {
x: 1,
z: 6,
heading: "N"
},
path: defaultPath(),
turnTokens: [],
pathDirty: false,
turnDirty: false
};
// -------------------------------------------------------------------------
// Representation helpers
// -------------------------------------------------------------------------
const sameCell = (a, b) => a.x === b.x && a.z === b.z;
const samePath = (a, b) =>
a.length === b.length && a.every((cell, index) => sameCell(cell, b[index]));
const cellKey = (cell) => `${cell.x},${cell.z}`;
const isBlocked = (cell) => BLOCKED.has(cellKey(cell));
const inBounds = (cell) =>
cell.x >= 0 &&
cell.x < GRID &&
cell.z >= 0 &&
cell.z < GRID;
const serializePath = (path) =>
path.map((cell) => `${cell.x},${cell.z}`).join("\n");
const serializeTurns = (tokens) => tokens.join(" ");
function parsePathText(text) {
const lines = text
.split(/\n+/)
.map((line) => line.trim())
.filter(Boolean);
if (!lines.length) {
return { error: "The path is empty." };
}
const path = [];
for (let index = 0; index < lines.length; index++) {
const match = lines[index].match(
/^\(?\s*(-?\d+)\s*,\s*(-?\d+)\s*\)?$/
);
if (!match) {
return {
error: `Invalid path line ${index + 1}: expected “x,z”.`
};
}
path.push({
x: Number(match[1]),
z: Number(match[2])
});
}
return { path };
}
function parseTurnText(text) {
const raw = text
.trim()
.split(/[\s,;]+/)
.filter(Boolean);
const tokens = [];
for (const rawToken of raw) {
const token = rawToken.toUpperCase();
if (!/^[FLRU]$/.test(token)) {
return {
error: `Unknown command “${rawToken}”. Use only F, L, R, or U.`
};
}
tokens.push(token);
}
return { tokens };
}
function validatePath(path) {
const errors = [];
const warnings = [];
if (!path.length) {
errors.push("The path has no cells.");
return { errors, warnings };
}
if (!sameCell(path[0], state.start)) {
errors.push(
`The path must begin at the explicit start cell (${state.start.x},${state.start.z}).`
);
}
const seen = new Map();
path.forEach((cell, index) => {
if (!inBounds(cell)) {
errors.push(`Cell ${index + 1} is outside the bounded board.`);
}
if (isBlocked(cell)) {
errors.push(`Cell ${index + 1} enters an obstacle at ${cellKey(cell)}.`);
}
const key = cellKey(cell);
if (seen.has(key)) {
warnings.push(
`Cell ${cellKey(cell)} is repeated. The ordered path still represents the loop, but the marker cannot show its history by position alone.`
);
} else {
seen.set(key, index);
}
if (index > 0) {
const previous = path[index - 1];
const distance =
Math.abs(cell.x - previous.x) + Math.abs(cell.z - previous.z);
if (distance !== 1) {
errors.push(
`Cells ${index} and ${index + 1} are not orthogonally adjacent.`
);
}
}
});
return { errors, warnings };
}
function relativeTurn(fromHeading, toHeading) {
if (fromHeading === toHeading) return "";
if (LEFT[fromHeading] === toHeading) return "L";
if (RIGHT[fromHeading] === toHeading) return "R";
if (OPPOSITE[fromHeading] === toHeading) return "U";
return "";
}
function deriveTurns(path) {
const tokens = [];
let heading = state.start.heading;
for (let index = 1; index < path.length; index++) {
const previous = path[index - 1];
const current = path[index];
const dx = current.x - previous.x;
const dz = current.z - previous.z;
let nextHeading;
if (dx === 1) nextHeading = "E";
else if (dx === -1) nextHeading = "W";
else if (dz === 1) nextHeading = "S";
else nextHeading = "N";
const turn = relativeTurn(heading, nextHeading);
if (turn) tokens.push(turn);
tokens.push("F");
heading = nextHeading;
}
return tokens;
}
function applyTurns(tokens) {
let heading = state.start.heading;
let cell = { x: state.start.x, z: state.start.z };
const path = [{ ...cell }];
for (let index = 0; index < tokens.length; index++) {
const token = tokens[index];
if (token === "L") {
heading = LEFT[heading];
} else if (token === "R") {
heading = RIGHT[heading];
} else if (token === "U") {
heading = OPPOSITE[heading];
} else if (token === "F") {
const direction = DIRECTIONS[heading];
cell = {
x: cell.x + direction.x,
z: cell.z + direction.z
};
if (!inBounds(cell)) {
return {
error: `Command ${index + 1} leaves the bounded board.`
};
}
if (isBlocked(cell)) {
return {
error: `Command ${index + 1} enters an obstacle at ${cellKey(cell)}.`
};
}
path.push({ ...cell });
}
}
return { path, tokens: [...tokens] };
}
// -------------------------------------------------------------------------
// UI synchronization and audit
// -------------------------------------------------------------------------
let toastTimer = 0;
function showToast(message, type = "") {
clearTimeout(toastTimer);
ui.toast.textContent = message;
ui.toast.className = `show ${type}`.trim();
toastTimer = window.setTimeout(() => {
ui.toast.className = "";
}, 2800);
}
function setBadge(element, text, type = "") {
element.textContent = text;
element.className = `badge ${type}`.trim();
}
function updateRouteStatus() {
const steps = Math.max(0, state.path.length - 1);
ui.routeStatus.textContent = `${steps} step${steps === 1 ? "" : "s"}`;
const endpoint = state.path[state.path.length - 1];
const reached = endpoint && sameCell(endpoint, GOAL);
ui.goalBadge.textContent = reached ? "Goal reached" : "Goal not reached";
ui.goalBadge.classList.toggle("reached", Boolean(reached));
}
function syncFromPath() {
state.turnTokens = deriveTurns(state.path);
ui.pathText.value = serializePath(state.path);
ui.turnText.value = serializeTurns(state.turnTokens);
state.pathDirty = false;
state.turnDirty = false;
renderPath();
renderAudit();
updateRouteStatus();
}
function syncFromTurns(path, tokens) {
state.path = path.map((cell) => ({ ...cell }));
state.turnTokens = [...tokens];
ui.pathText.value = serializePath(state.path);
ui.turnText.value = serializeTurns(state.turnTokens);
state.pathDirty = false;
state.turnDirty = false;
renderPath();
renderAudit();
updateRouteStatus();
}
function renderAudit() {
const pathCheck = validatePath(state.path);
if (pathCheck.errors.length) {
setBadge($("auditPathBadge"), "Invalid path", "bad");
$("auditPathText").textContent = pathCheck.errors[0];
} else {
const canonicalTurns = deriveTurns(state.path);
const roundTrip = applyTurns(canonicalTurns);
const exact =
!roundTrip.error && samePath(roundTrip.path, state.path);
if (exact) {
setBadge($("auditPathBadge"), "Exact round-trip", "ok");
$("auditPathText").textContent =
`The ${state.path.length} ordered cells convert to F/L/R/U and back without changing a cell. The path itself omits initial facing; the shared heading restores it.`;
} else {
setBadge($("auditPathBadge"), "Mismatch", "bad");
$("auditPathText").textContent =
"The path could not be reconstructed exactly from its derived turn program.";
}
}
const turnParse = parseTurnText(ui.turnText.value);
if (turnParse.error) {
setBadge($("auditTurnBadge"), "Invalid commands", "bad");
$("auditTurnText").textContent = turnParse.error;
} else {
const turnResult = applyTurns(turnParse.tokens);
if (turnResult.error) {
setBadge($("auditTurnBadge"), "Invalid route", "bad");
$("auditTurnText").textContent = turnResult.error;
} else {
const exact = samePath(turnResult.path, state.path);
if (exact) {
setBadge($("auditTurnBadge"), "Lossless with pose", "ok");
$("auditTurnText").textContent =
`“${serializeTurns(turnParse.tokens) || "empty program"}” reconstructs the exact path when paired with the start cell and heading. The token stream alone omits that absolute pose.`;
} else {
setBadge($("auditTurnBadge"), "Different route", "warn");
$("auditTurnText").textContent =
"The edited turn program describes a different route from the currently marked path. Apply one of the conversion buttons to synchronize them.";
}
}
}
const canonicalTurns = deriveTurns(state.path);
const canonicalResult = applyTurns(canonicalTurns);
const canonicalExact =
!canonicalResult.error && samePath(canonicalResult.path, state.path);
if (canonicalExact) {
setBadge($("auditRoundBadge"), "No route loss", "ok");
$("auditRoundText").textContent =
"Path → turns → path preserves every marked cell. U-turns are encoded explicitly as U rather than being approximated by two turns.";
} else {
setBadge($("auditRoundBadge"), "Needs attention", "bad");
$("auditRoundText").textContent =
"A round-trip discrepancy was detected. Check the start cell, heading, adjacency, and obstacles.";
}
const warnings = pathCheck.warnings.length
? ` ${pathCheck.warnings[0]}`
: "";
$("auditLimitText").textContent =
`Detected representation limits: path cells alone omit the initial facing; ` +
`turn tokens alone omit the absolute start cell and facing. The shared start ` +
`pose is retained, so the combined bundle remains reversible.` +
warnings;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x081321);
scene.fog = new THREE.Fog(0x081321, 19, 34);
const camera = new THREE.OrthographicCamera(-7, 7, 5, -5, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
ui.viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb9dcff, 0x182033, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(5, 11, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x55dfff, 22, 18, 2);
rimLight.position.set(-5, 4, -4);
scene.add(rimLight);
const boardGroup = new THREE.Group();
const pathGroup = new THREE.Group();
scene.add(boardGroup, pathGroup);
const tileMeshes = new Map();
const worldX = (x) => x - (GRID - 1) / 2;
const worldZ = (z) => z - (GRID - 1) / 2;
const foundation = new THREE.Mesh(
new THREE.BoxGeometry(GRID + 0.55, 0.55, GRID + 0.55),
new THREE.MeshStandardMaterial({
color: 0x101d2e,
roughness: 0.7,
metalness: 0.2
})
);
foundation.position.y = -0.34;
foundation.receiveShadow = true;
boardGroup.add(foundation);
const tileGeometry = new THREE.BoxGeometry(0.92, 0.22, 0.92);
for (let z = 0; z < GRID; z++) {
for (let x = 0; x < GRID; x++) {
const baseColor = (x + z) % 2 === 0 ? 0x253b55 : 0x20354d;
const material = new THREE.MeshStandardMaterial({
color: baseColor,
roughness: 0.82,
metalness: 0.08,
emissive: 0x000000,
emissiveIntensity: 0.3
});
const tile = new THREE.Mesh(tileGeometry, material);
tile.position.set(worldX(x), 0, worldZ(z));
tile.receiveShadow = true;
tile.userData.cell = { x, z };
boardGroup.add(tile);
tileMeshes.set(cellKey({ x, z }), tile);
}
}
const borderMaterial = new THREE.MeshStandardMaterial({
color: 0x304966,
roughness: 0.62,
metalness: 0.25
});
const horizontalBorderGeometry = new THREE.BoxGeometry(
GRID + 0.5,
0.58,
0.22
);
const verticalBorderGeometry = new THREE.BoxGeometry(
0.22,
0.58,
GRID + 0.5
);
for (const z of [-GRID / 2 - 0.08, GRID / 2 + 0.08]) {
const border = new THREE.Mesh(horizontalBorderGeometry, borderMaterial);
border.position.set(0, 0.18, z);
border.castShadow = true;
border.receiveShadow = true;
boardGroup.add(border);
}
for (const x of [-GRID / 2 - 0.08, GRID / 2 + 0.08]) {
const border = new THREE.Mesh(verticalBorderGeometry, borderMaterial);
border.position.set(x, 0.18, 0);
border.castShadow = true;
border.receiveShadow = true;
boardGroup.add(border);
}
const obstacleGeometry = new THREE.BoxGeometry(0.86, 1.12, 0.86);
for (const key of BLOCKED) {
const [x, z] = key.split(",").map(Number);
const obstacle = new THREE.Mesh(
obstacleGeometry,
new THREE.MeshStandardMaterial({
color: 0x465a72,
roughness: 0.58,
metalness: 0.28,
emissive: 0x0a1522,
emissiveIntensity: 0.25
})
);
obstacle.position.set(worldX(x), 0.57, worldZ(z));
obstacle.castShadow = true;
obstacle.receiveShadow = true;
boardGroup.add(obstacle);
}
function makeLabel(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 96;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(6, 14, 25, 0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = color;
context.lineWidth = 6;
context.strokeRect(3, 3, canvas.width - 6, canvas.height - 6);
context.fillStyle = color;
context.font = "bold 34px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
})
);
sprite.scale.set(1.45, 0.54, 1);
return sprite;
}
const goalMarker = new THREE.Group();
goalMarker.position.set(worldX(GOAL.x), 0, worldZ(GOAL.z));
const goalBase = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.39, 0.13, 24),
new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x7a4c00,
emissiveIntensity: 0.8,
metalness: 0.35,
roughness: 0.35
})
);
goalBase.position.y = 0.26;
goalBase.castShadow = true;
goalMarker.add(goalBase);
const goalRing = new THREE.Mesh(
new THREE.TorusGeometry(0.29, 0.055, 12, 32),
new THREE.MeshBasicMaterial({ color: 0xffe39a })
);
goalRing.rotation.x = Math.PI / 2;
goalRing.position.y = 0.37;
goalMarker.add(goalRing);
const goalBeam = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.16, 1.35, 18),
new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.22,
depthWrite: false
})
);
goalBeam.position.y = 0.95;
goalMarker.add(goalBeam);
const goalLabel = makeLabel("GOAL", "#ffd166");
goalLabel.position.y = 1.7;
goalMarker.add(goalLabel);
boardGroup.add(goalMarker);
const startArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 0, -1),
new THREE.Vector3(),
0.95,
0xb487ff,
0.34,
0.24
);
scene.add(startArrow);
function updateStartArrow() {
const direction = DIRECTIONS[state.start.heading];
startArrow.position.set(
worldX(state.start.x),
0.52,
worldZ(state.start.z)
);
startArrow.setDirection(
new THREE.Vector3(direction.x, 0, direction.z).normalize()
);
}
function clearPathGroup() {
for (const child of [...pathGroup.children]) {
pathGroup.remove(child);
child.geometry?.dispose();
if (Array.isArray(child.material)) {
child.material.forEach((material) => material.dispose());
} else {
child.material?.dispose();
}
}
}
function renderPath() {
clearPathGroup();
const endpoint = state.path[state.path.length - 1];
state.path.forEach((cell, index) => {
let color = 0x56e0ff;
let emissive = 0x0b5062;
if (index === 0) {
color = 0xa879ff;
emissive = 0x41216f;
}
if (endpoint && index === state.path.length - 1 && sameCell(cell, GOAL)) {
color = 0x62e6a7;
emissive = 0x176b46;
}
const marker = new THREE.Mesh(
new THREE.BoxGeometry(0.57, 0.13, 0.57),
new THREE.MeshStandardMaterial({
color,
emissive,
emissiveIntensity: 1.15,
roughness: 0.28,
metalness: 0.18
})
);
marker.position.set(worldX(cell.x), 0.28, worldZ(cell.z));
marker.castShadow = true;
marker.receiveShadow = true;
pathGroup.add(marker);
});
if (state.path.length > 1) {
const points = state.path.map(
(cell) =>
new THREE.Vector3(worldX(cell.x), 0.38, worldZ(cell.z))
);
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color: 0x83efff,
transparent: true,
opacity: 0.72
})
);
pathGroup.add(line);
}
updateStartArrow();
updateRouteStatus();
}
// -------------------------------------------------------------------------
// Direct camera controls: no addons
// -------------------------------------------------------------------------
const cameraState = {
yaw: 0.58,
pitch: 0.79,
zoom: 1
};
function updateCamera() {
const radius = 20;
const horizontal = Math.cos(cameraState.pitch) * radius;
camera.position.set(
Math.sin(cameraState.yaw) * horizontal,
Math.sin(cameraState.pitch) * radius,
Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(0, 0, 0);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.yaw = 0.58;
cameraState.pitch = 0.79;
cameraState.zoom = 1;
updateCamera();
}
function resizeRenderer() {
const width = Math.max(1, ui.viewport.clientWidth);
const height = Math.max(1, ui.viewport.clientHeight);
const aspect = width / height;
renderer.setSize(width, height, false);
const viewHeight = Math.max(9.8, 11.8 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
}
new ResizeObserver(resizeRenderer).observe(ui.viewport);
resizeRenderer();
updateCamera();
// -------------------------------------------------------------------------
// Raycasting and pointer interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let hoveredTile = null;
let pointerDown = null;
function raycastTile(event) {
const rect = renderer.domElement.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(
[...tileMeshes.values()],
false
);
return hits.length ? hits[0].object.userData.cell : null;
}
function setHoveredTile(tile) {
if (hoveredTile === tile) return;
if (hoveredTile) {
hoveredTile.material.emissive.setHex(0x000000);
hoveredTile.material.emissiveIntensity = 0.3;
}
hoveredTile = tile;
if (hoveredTile) {
hoveredTile.material.emissive.setHex(0x17445c);
hoveredTile.material.emissiveIntensity = 0.65;
}
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointerDown = {
x: event.clientX,
y: event.clientY,
moved: false
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - pointerDown.x;
const dy = event.clientY - pointerDown.y;
if (Math.hypot(dx, dy) > 4) {
pointerDown.moved = true;
}
if (pointerDown.moved) {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.34,
1.36
);
updateCamera();
}
}
if (!pointerDown || !pointerDown.moved) {
setHoveredTile(raycastTile(event));
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
const wasClick = pointerDown && !pointerDown.moved;
pointerDown = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (wasClick) {
const cell = raycastTile(event);
if (cell) handleBoardClick(cell);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * (event.deltaY > 0 ? 0.92 : 1.08),
0.68,
2.2
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("pointerleave", () => {
setHoveredTile(null);
});
function handleBoardClick(cell) {
if (isBlocked(cell)) {
showToast(`That tile is blocked at ${cellKey(cell)}.`, "error");
return;
}
const existingIndex = state.path.findIndex((item) => sameCell(item, cell));
if (existingIndex >= 0) {
state.path = state.path.slice(0, existingIndex + 1);
syncFromPath();
showToast(`Path trimmed to ${cellKey(cell)}.`);
return;
}
const last = state.path[state.path.length - 1];
if (!last) {
showToast("The path needs a start cell.", "error");
return;
}
const distance =
Math.abs(cell.x - last.x) + Math.abs(cell.z - last.z);
if (distance !== 1) {
showToast(
"Marked path cells must be orthogonally adjacent. Click a path tile to trim first.",
"error"
);
return;
}
state.path.push({ ...cell });
syncFromPath();
showToast(`Added ${cellKey(cell)} to the marked path.`, "success");
}
// -------------------------------------------------------------------------
// UI actions
// -------------------------------------------------------------------------
$("pathToTurns").addEventListener("click", () => {
const parsed = parsePathText(ui.pathText.value);
if (parsed.error) {
showToast(parsed.error, "error");
return;
}
const check = validatePath(parsed.path);
if (check.errors.length) {
showToast(check.errors[0], "error");
return;
}
state.path = parsed.path;
syncFromPath();
showToast("Path converted to an exact relative turn program.", "success");
});
$("turnsToPath").addEventListener("click", () => {
const parsed = parseTurnText(ui.turnText.value);
if (parsed.error) {
showToast(parsed.error, "error");
return;
}
const result = applyTurns(parsed.tokens);
if (result.error) {
showToast(result.error, "error");
return;
}
syncFromTurns(result.path, result.tokens);
showToast("Turn program converted to the exact marked path.", "success");
});
$("undo").addEventListener("click", () => {
if (state.path.length <= 1) {
showToast("The route already contains only its start cell.");
return;
}
state.path.pop();
syncFromPath();
});
$("clear").addEventListener("click", () => {
state.path = [{ x: state.start.x, z: state.start.z }];
syncFromPath();
showToast("Path cleared.");
});
$("solve").addEventListener("click", () => {
state.start.x = 1;
state.start.z = 6;
state.start.heading = "N";
ui.startX.value = "1";
ui.startZ.value = "6";
ui.startHeading.value = "N";
state.path = defaultPath();
syncFromPath();
showToast("Example solution loaded.", "success");
});
$("cameraReset").addEventListener("click", resetCamera);
function updateStartPosition() {
const x = Number(ui.startX.value);
const z = Number(ui.startZ.value);
if (
!Number.isInteger(x) ||
!Number.isInteger(z) ||
x < 0 ||
x >= GRID ||
z < 0 ||
z >= GRID
) {
showToast("Start coordinates must be integers from 0 through 7.", "error");
ui.startX.value = state.start.x;
ui.startZ.value = state.start.z;
return;
}
const dx = x - state.start.x;
const dz = z - state.start.z;
const movedPath = state.path.map((cell) => ({
x: cell.x + dx,
z: cell.z + dz
}));
if (
movedPath.some((cell) => !inBounds(cell) || isBlocked(cell))
) {
showToast(
"The whole marked route cannot be shifted onto that start because it would leave the board or enter an obstacle.",
"error"
);
ui.startX.value = state.start.x;
ui.startZ.value = state.start.z;
return;
}
state.start.x = x;
state.start.z = z;
state.path = movedPath.length
? movedPath
: [{ x, z }];
syncFromPath();
showToast("Start position and route shifted together.", "success");
}
ui.startX.addEventListener("change", updateStartPosition);
ui.startZ.addEventListener("change", updateStartPosition);
ui.startHeading.addEventListener("change", () => {
state.start.heading = ui.startHeading.value;
syncFromPath();
showToast(
`Start heading set to ${HEADING_NAMES[state.start.heading]}; the turn program was recomputed.`,
"success"
);
});
ui.pathText.addEventListener("input", () => {
state.pathDirty = ui.pathText.value !== serializePath(state.path);
renderAudit();
});
ui.turnText.addEventListener("input", () => {
state.turnDirty = ui.turnText.value !== serializeTurns(state.turnTokens);
renderAudit();
});
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
} catch {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
textarea.remove();
}
}
$("copyPath").addEventListener("click", async () => {
const bundle = {
format: "voxel-path-v1",
grid: GRID,
start: {
cell: { x: state.start.x, z: state.start.z },
heading: state.start.heading
},
path: state.path.map((cell) => ({ ...cell }))
};
await copyText(JSON.stringify(bundle, null, 2));
showToast("Path bundle copied with its required start pose.", "success");
});
$("copyTurn").addEventListener("click", async () => {
const bundle = {
format: "voxel-turn-v1",
grid: GRID,
start: {
cell: { x: state.start.x, z: state.start.z },
heading: state.start.heading
},
commands: serializeTurns(state.turnTokens),
commandSemantics: {
F: "move one cell",
L: "turn left in place",
R: "turn right in place",
U: "turn 180 degrees in place"
}
};
await copyText(JSON.stringify(bundle, null, 2));
showToast("Turn bundle copied with its required start pose.", "success");
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement ||
event.target instanceof HTMLSelectElement
) {
return;
}
if (event.key.toLowerCase() === "r") {
resetCamera();
}
if (event.key.toLowerCase() === "u") {
$("undo").click();
}
});
// -------------------------------------------------------------------------
// Initial state and render loop
// -------------------------------------------------------------------------
ui.startX.value = String(state.start.x);
ui.startZ.value = String(state.start.z);
ui.startHeading.value = state.start.heading;
syncFromPath();
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
goalRing.rotation.z = elapsed * 0.55;
goalBeam.material.opacity = 0.18 + Math.sin(elapsed * 2.2) * 0.05;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```