Prompt specification
Build or customize the Three.js 3D scene "Error-detection code playground" 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: Error-detection code playground
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/error-detection-code-playground-x1868
Scene Description Prompt:
Flip bits in voxel parity-coded messages and reveal both detected and missed errors without automatic correction. Standalone HTML, Three.js from cdnjs.
Working Three.js Starter (error-detection-code-playground-x1868):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Parity Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #070b12;
--panel: #0d131e;
--panel-2: #111a28;
--line: #1e2b3d;
--line-bright: #2b3c55;
--text: #eaf1ff;
--muted: #8291a8;
--cyan: #4de3c1;
--blue: #6d8cff;
--red: #ff6078;
--purple: #c16cff;
--amber: #ffc766;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
--sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: var(--sans);
}
body {
overflow: hidden;
}
button, textarea {
font: inherit;
}
button {
color: inherit;
}
.app {
height: 100vh;
display: grid;
grid-template-rows: 66px minmax(0, 1fr);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 20px;
border-bottom: 1px solid var(--line);
background:
linear-gradient(90deg, rgba(77, 227, 193, 0.05), transparent 35%),
#090e17;
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 30px;
height: 30px;
position: relative;
transform: rotate(30deg);
border: 1px solid rgba(77, 227, 193, 0.65);
border-radius: 7px;
box-shadow: inset 0 0 18px rgba(77, 227, 193, 0.08);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: var(--cyan);
opacity: 0.8;
}
.brand-mark::before {
width: 7px;
height: 7px;
left: 5px;
top: 5px;
box-shadow: 8px 8px 0 rgba(109, 140, 255, 0.9);
}
.brand-mark::after {
width: 7px;
height: 7px;
right: 5px;
bottom: 5px;
}
.brand h1 {
margin: 0;
font-size: 15px;
letter-spacing: 0.16em;
text-transform: uppercase;
white-space: nowrap;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font: 11px var(--mono);
letter-spacing: 0.06em;
}
.header-right {
display: flex;
align-items: center;
gap: 12px;
}
.no-correction {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 11px;
border: 1px solid rgba(255, 199, 102, 0.28);
border-radius: 999px;
color: var(--amber);
background: rgba(255, 199, 102, 0.06);
font: 10px var(--mono);
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
}
.no-correction::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 10px var(--amber);
}
.workspace {
min-height: 0;
display: grid;
grid-template-columns: 300px minmax(460px, 1fr) 340px;
overflow: hidden;
}
.panel {
min-height: 0;
overflow-y: auto;
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: var(--line-bright) transparent;
}
.left-panel {
border-right: 1px solid var(--line);
}
.right-panel {
border-left: 1px solid var(--line);
}
.section {
padding: 18px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
border-bottom: 0;
}
.eyebrow {
margin-bottom: 9px;
color: var(--cyan);
font: 10px var(--mono);
letter-spacing: 0.15em;
text-transform: uppercase;
}
h2 {
margin: 0 0 12px;
font-size: 14px;
font-weight: 650;
letter-spacing: 0.02em;
}
h3 {
margin: 0 0 10px;
font-size: 11px;
font-weight: 650;
letter-spacing: 0.09em;
text-transform: uppercase;
color: #b9c5d8;
}
p {
margin: 0;
}
.muted {
color: var(--muted);
}
.small {
font-size: 11px;
line-height: 1.55;
}
.mono {
font-family: var(--mono);
}
textarea {
width: 100%;
min-height: 106px;
resize: vertical;
padding: 12px;
color: var(--text);
background: #080d15;
border: 1px solid var(--line-bright);
border-radius: 8px;
outline: none;
line-height: 1.5;
font-size: 13px;
}
textarea:focus {
border-color: rgba(77, 227, 193, 0.55);
box-shadow: 0 0 0 3px rgba(77, 227, 193, 0.06);
}
.input-meta {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 8px;
color: var(--muted);
font: 10px var(--mono);
}
.notice {
margin-top: 9px;
padding: 8px 9px;
color: var(--amber);
background: rgba(255, 199, 102, 0.06);
border: 1px solid rgba(255, 199, 102, 0.2);
border-radius: 6px;
font-size: 10px;
line-height: 1.45;
}
.button {
width: 100%;
min-height: 38px;
padding: 9px 11px;
border: 1px solid var(--line-bright);
border-radius: 7px;
background: #141e2c;
cursor: pointer;
font-size: 11px;
font-weight: 650;
letter-spacing: 0.025em;
transition: border-color 120ms, background 120ms, transform 120ms;
}
.button:hover {
border-color: #49617e;
background: #192638;
}
.button:active {
transform: translateY(1px);
}
.button.primary {
margin-top: 12px;
color: #07110f;
border-color: transparent;
background: var(--cyan);
}
.button.primary:hover {
background: #6cebd0;
}
.button.danger {
color: #ff9cac;
border-color: rgba(255, 96, 120, 0.25);
background: rgba(255, 96, 120, 0.055);
}
.button.silent {
color: #d6b5ff;
border-color: rgba(193, 108, 255, 0.27);
background: rgba(193, 108, 255, 0.06);
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.code-facts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.fact {
padding: 10px;
border: 1px solid var(--line);
border-radius: 7px;
background: #0a1019;
}
.fact strong {
display: block;
margin-bottom: 3px;
color: #dbe7fa;
font: 12px var(--mono);
}
.fact span {
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.legend {
display: grid;
gap: 9px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
color: #aab7ca;
font-size: 10px;
}
.swatch {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 3px;
border: 1px solid rgba(255,255,255,0.14);
}
.swatch.data0 { background: #1b2a40; }
.swatch.data1 { background: #35d9aa; }
.swatch.parity { background: #6889ff; }
.swatch.detected { background: var(--red); }
.swatch.missed { background: var(--purple); }
.viewport {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: 52px minmax(0, 1fr);
background: #080d16;
}
.viewport-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 0 14px;
border-bottom: 1px solid var(--line);
background: rgba(13, 19, 30, 0.94);
z-index: 2;
}
.segmented {
display: inline-flex;
padding: 3px;
border: 1px solid var(--line);
border-radius: 7px;
background: #080d15;
}
.segmented button {
padding: 7px 10px;
color: var(--muted);
border: 0;
border-radius: 5px;
background: transparent;
cursor: pointer;
font: 10px var(--mono);
}
.segmented button.active {
color: var(--text);
background: #1a2638;
box-shadow: 0 1px 0 rgba(255,255,255,0.04) inset;
}
.toolbar-button {
padding: 7px 10px;
color: #aab8cc;
border: 1px solid var(--line);
border-radius: 6px;
background: #101824;
cursor: pointer;
font: 10px var(--mono);
}
.scene-wrap {
position: relative;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, rgba(41, 73, 105, 0.15), transparent 44%),
#070c14;
}
canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.scene-legend {
position: absolute;
left: 14px;
bottom: 14px;
display: flex;
flex-wrap: wrap;
gap: 7px;
max-width: calc(100% - 28px);
pointer-events: none;
}
.scene-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border: 1px solid rgba(51, 69, 94, 0.7);
border-radius: 5px;
color: #9baac0;
background: rgba(8, 13, 21, 0.78);
backdrop-filter: blur(8px);
font: 9px var(--mono);
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
}
.help {
position: absolute;
right: 14px;
bottom: 14px;
padding: 7px 9px;
color: #708097;
border: 1px solid rgba(43, 60, 85, 0.65);
border-radius: 5px;
background: rgba(8, 13, 21, 0.72);
pointer-events: none;
font: 9px var(--mono);
text-align: right;
line-height: 1.55;
}
.hover-card {
position: absolute;
top: 14px;
left: 14px;
display: none;
min-width: 210px;
padding: 10px 12px;
color: #c8d5e8;
border: 1px solid rgba(70, 92, 123, 0.8);
border-radius: 7px;
background: rgba(9, 15, 25, 0.88);
backdrop-filter: blur(10px);
pointer-events: none;
white-space: pre-line;
font: 10px/1.55 var(--mono);
z-index: 3;
}
.status-card {
display: flex;
align-items: flex-start;
gap: 11px;
padding: 13px;
border: 1px solid var(--line-bright);
border-radius: 8px;
background: #0a1019;
}
.status-card.clean {
border-color: rgba(77, 227, 193, 0.28);
}
.status-card.detected {
border-color: rgba(255, 96, 120, 0.32);
background: rgba(255, 96, 120, 0.035);
}
.status-card.missed {
border-color: rgba(193, 108, 255, 0.34);
background: rgba(193, 108, 255, 0.035);
}
.status-dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
margin-top: 3px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(77, 227, 193, 0.65);
}
.detected .status-dot {
background: var(--red);
box-shadow: 0 0 12px rgba(255, 96, 120, 0.65);
}
.missed .status-dot {
background: var(--purple);
box-shadow: 0 0 12px rgba(193, 108, 255, 0.65);
}
.status-title {
margin-bottom: 4px;
font: 11px var(--mono);
font-weight: 700;
letter-spacing: 0.07em;
}
.status-detail {
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 12px;
}
.metric {
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 6px;
background: #0a1019;
text-align: center;
}
.metric strong {
display: block;
font: 15px var(--mono);
}
.metric span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric.detected strong { color: var(--red); }
.metric.missed strong { color: var(--purple); }
.syndrome-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.syndrome-value {
color: #a7b7cc;
font: 10px var(--mono);
}
.syndrome-bits {
display: grid;
grid-template-columns: repeat(9, 1fr);
gap: 4px;
}
.syndrome-bit {
min-width: 0;
padding: 7px 1px;
border: 1px solid var(--line);
border-radius: 5px;
color: #526177;
background: #090e16;
text-align: center;
font: 8px var(--mono);
}
.syndrome-bit.fail {
color: #ff9cac;
border-color: rgba(255, 96, 120, 0.35);
background: rgba(255, 96, 120, 0.08);
}
.error-list {
display: grid;
gap: 5px;
max-height: 152px;
overflow-y: auto;
}
.error-chip {
display: block;
padding: 7px 8px;
border: 1px solid var(--line);
border-radius: 5px;
background: #0a1019;
font: 9px var(--mono);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.error-chip.detected {
color: #ff9cac;
border-color: rgba(255, 96, 120, 0.23);
}
.error-chip.missed {
color: #d2a8ff;
border-color: rgba(193, 108, 255, 0.25);
}
.empty {
padding: 9px;
color: #5d6d84;
border: 1px dashed var(--line);
border-radius: 6px;
font: 9px var(--mono);
text-align: center;
}
.payload-box {
margin-top: 10px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 6px;
background: #080d15;
}
.payload-box pre {
min-height: 22px;
margin: 0;
overflow-wrap: anywhere;
white-space: pre-wrap;
color: #d8e4f5;
font: 11px/1.5 var(--mono);
}
.payload-box.received pre {
color: #b9c8dc;
}
.payload-label {
margin-bottom: 6px;
color: #64748b;
font: 8px var(--mono);
letter-spacing: 0.09em;
text-transform: uppercase;
}
.oracle-note {
margin-top: 10px;
padding: 9px;
color: #8493a9;
border-left: 2px solid var(--line-bright);
background: rgba(255,255,255,0.015);
font-size: 9px;
line-height: 1.55;
}
@media (max-width: 1100px) {
body { overflow: auto; }
.app { height: auto; min-height: 100vh; }
.workspace {
grid-template-columns: 285px minmax(500px, 1fr);
overflow: visible;
}
.viewport { height: 720px; }
.right-panel {
grid-column: 1 / -1;
display: grid;
grid-template-columns: repeat(3, 1fr);
border-top: 1px solid var(--line);
border-left: 0;
}
.right-panel .section { border-right: 1px solid var(--line); }
}
@media (max-width: 720px) {
body { overflow: auto; }
header { padding: 0 12px; }
.brand p { display: none; }
.no-correction { padding: 7px; font-size: 8px; }
.workspace { display: block; }
.left-panel, .right-panel { display: block; }
.viewport { height: 620px; }
.right-panel { display: block; }
.help { display: none; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Voxel Parity Lab</h1>
<p>Extended Hamming / 256-bit visual channel</p>
</div>
</div>
<div class="header-right">
<div class="no-correction">Detection only · no automatic correction</div>
</div>
</header>
<main class="workspace">
<aside class="panel left-panel">
<section class="section">
<div class="eyebrow">01 / Source</div>
<h2>Payload message</h2>
<textarea id="message" spellcheck="false">Hello, voxel world!</textarea>
<div class="input-meta">
<span>UTF-8</span>
<span id="byteCount">0 / 29 bytes</span>
</div>
<div id="truncateNotice" class="notice" hidden>
The payload exceeds 29 UTF-8 bytes and will be truncated at the next encoding.
</div>
<button id="encodeButton" class="button primary">Encode and reset channel</button>
</section>
<section class="section">
<div class="eyebrow">02 / Fault injection</div>
<h2>Flip protected bits</h2>
<p class="small muted">
Click any voxel to toggle its received bit. Presets replace the current
fault set so the two outcomes are easy to compare.
</p>
<div class="button-grid">
<button id="singleFaultButton" class="button danger">Inject 1-bit fault</button>
<button id="silentFaultButton" class="button silent">Inject silent fault</button>
<button id="randomFaultButton" class="button">Flip random bit</button>
<button id="clearButton" class="button">Clear all faults</button>
</div>
<div class="code-facts">
<div class="fact">
<strong>247</strong>
<span>Data bits</span>
</div>
<div class="fact">
<strong>8 + 1</strong>
<span>Parity bits</span>
</div>
<div class="fact">
<strong>256</strong>
<span>Voxel symbols</span>
</div>
<div class="fact">
<strong>9</strong>
<span>Check equations</span>
</div>
</div>
</section>
<section class="section">
<div class="eyebrow">03 / Key</div>
<h2>Voxel colors</h2>
<div class="legend">
<div class="legend-row">
<span class="swatch data0"></span>
<span>Received data bit = 0</span>
</div>
<div class="legend-row">
<span class="swatch data1"></span>
<span>Received data bit = 1</span>
</div>
<div class="legend-row">
<span class="swatch parity"></span>
<span>Hamming or extended parity bit = 1</span>
</div>
<div class="legend-row">
<span class="swatch detected"></span>
<span>Detected corruption</span>
</div>
<div class="legend-row">
<span class="swatch missed"></span>
<span>Missed / parity-masked corruption</span>
</div>
</div>
</section>
<section class="section">
<div class="eyebrow">Code note</div>
<p class="small muted">
This is an extended Hamming-style <span class="mono">[256,247]</span>
binary code. It detects every single-bit fault and every two-bit
fault, but selected multi-bit patterns can still produce a zero
syndrome. Those failures are intentionally exposed rather than repaired.
</p>
</section>
</aside>
<section class="viewport">
<div class="viewport-toolbar">
<div class="segmented" aria-label="Visualization mode">
<button class="active" data-view="received">Received</button>
<button data-view="original">Original</button>
<button data-view="difference">Difference</button>
</div>
<button id="resetCameraButton" class="toolbar-button">Reset camera</button>
</div>
<div class="scene-wrap">
<canvas id="scene" aria-label="Interactive three-dimensional voxel bit field"></canvas>
<div id="hoverInfo" class="hover-card"></div>
<div class="scene-legend">
<span class="scene-chip"><i class="dot" style="background:#35d9aa"></i>DATA 1</span>
<span class="scene-chip"><i class="dot" style="background:#6889ff"></i>PARITY 1</span>
<span class="scene-chip"><i class="dot" style="background:#ff6078"></i>DETECTED</span>
<span class="scene-chip"><i class="dot" style="background:#c16cff"></i>MISSED</span>
</div>
<div class="help">
drag: orbit · shift/right drag: pan · wheel: zoom<br>
click voxel: flip one received bit
</div>
</div>
</section>
<aside class="panel right-panel">
<section class="section">
<div class="eyebrow">Receiver</div>
<h2>Integrity report</h2>
<div id="statusCard" class="status-card clean">
<div class="status-dot"></div>
<div>
<div id="statusTitle" class="status-title">CLEAN FRAME</div>
<div id="statusDetail" class="status-detail">
All parity equations pass.
</div>
</div>
</div>
<div class="metrics">
<div class="metric">
<strong id="changedMetric">0</strong>
<span>Changed</span>
</div>
<div class="metric detected">
<strong id="detectedMetric">0</strong>
<span>Detected</span>
</div>
<div class="metric missed">
<strong id="missedMetric">0</strong>
<span>Missed</span>
</div>
</div>
</section>
<section class="section">
<div class="syndrome-head">
<h3 style="margin:0">Parity syndrome</h3>
<span id="syndromeValue" class="syndrome-value">0x000</span>
</div>
<div id="syndromeBits" class="syndrome-bits"></div>
<div class="oracle-note">
A real receiver sees only the syndrome, not the saved original.
The exact error lists below use the original frame as a simulation
oracle. No received bit is automatically restored.
</div>
</section>
<section class="section">
<h3>Detected errors</h3>
<div id="detectedList" class="error-list"></div>
<h3 style="margin-top:17px">Missed errors</h3>
<div id="missedList" class="error-list"></div>
</section>
<section class="section">
<h3>Diagnostic payload view</h3>
<div class="payload-box">
<div class="payload-label">Original payload</div>
<pre id="originalPayload"></pre>
</div>
<div class="payload-box received">
<div class="payload-label">Raw received payload — not corrected</div>
<pre id="receivedPayload"></pre>
</div>
<div id="payloadState" class="oracle-note"></div>
</section>
</aside>
</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 GRID_X = 8;
const GRID_Y = 8;
const GRID_Z = 4;
const CODE_BITS = 256;
const MAX_BYTES = 29;
const PARITY_POSITIONS = [1, 2, 4, 8, 16, 32, 64, 128];
const PARITY_SET = new Set(PARITY_POSITIONS);
const DATA_POSITIONS = [];
for (let position = 1; position <= 255; position++) {
if (!PARITY_SET.has(position)) {
DATA_POSITIONS.push(position);
}
}
const messageInput = document.getElementById("message");
const byteCount = document.getElementById("byteCount");
const truncateNotice = document.getElementById("truncateNotice");
const encodeButton = document.getElementById("encodeButton");
const singleFaultButton = document.getElementById("singleFaultButton");
const silentFaultButton = document.getElementById("silentFaultButton");
const randomFaultButton = document.getElementById("randomFaultButton");
const clearButton = document.getElementById("clearButton");
const resetCameraButton = document.getElementById("resetCameraButton");
const statusCard = document.getElementById("statusCard");
const statusTitle = document.getElementById("statusTitle");
const statusDetail = document.getElementById("statusDetail");
const changedMetric = document.getElementById("changedMetric");
const detectedMetric = document.getElementById("detectedMetric");
const missedMetric = document.getElementById("missedMetric");
const syndromeValue = document.getElementById("syndromeValue");
const syndromeBits = document.getElementById("syndromeBits");
const detectedList = document.getElementById("detectedList");
const missedList = document.getElementById("missedList");
const originalPayload = document.getElementById("originalPayload");
const receivedPayload = document.getElementById("receivedPayload");
const payloadState = document.getElementById("payloadState");
const hoverInfo = document.getElementById("hoverInfo");
const canvas = document.getElementById("scene");
const encoder = new TextEncoder();
const decoder = new TextDecoder("utf-8", { fatal: false });
let original = new Uint8Array(CODE_BITS);
let received = new Uint8Array(CODE_BITS);
let currentDiagnostics = null;
let viewMode = "received";
const COLORS = {
dataZero: new THREE.Color("#1b2a40"),
dataOne: new THREE.Color("#35d9aa"),
parityZero: new THREE.Color("#1a3155"),
parityOne: new THREE.Color("#6889ff"),
detected: new THREE.Color("#ff6078"),
missed: new THREE.Color("#c16cff"),
diffZero: new THREE.Color("#0c1421"),
diffOne: new THREE.Color("#102b32")
};
let renderer;
let scene;
let camera;
let cubeMesh;
let statusMesh;
let hoverMesh;
let raycaster;
let pointer;
let cameraYaw = 0.72;
let cameraPitch = 0.55;
let cameraRadius = 20.5;
const cameraTarget = new THREE.Vector3();
const dummy = new THREE.Object3D();
function positionToXYZ(position) {
const index = position - 1;
return {
x: index % GRID_X,
y: Math.floor(index / GRID_X) % GRID_Y,
z: Math.floor(index / (GRID_X * GRID_Y))
};
}
function positionToWorld(position) {
const { x, y, z } = positionToXYZ(position);
return {
x: (x - (GRID_X - 1) / 2) * 1.08,
y: (y - (GRID_Y - 1) / 2) * 1.08,
z: (z - (GRID_Z - 1) / 2) * 1.08
};
}
function roleForPosition(position) {
if (position === 256) return "Extended even parity";
if (PARITY_SET.has(position)) return "Hamming parity";
return "Payload data";
}
function utf8Length(text) {
return encoder.encode(text).length;
}
function updateInputMeta() {
const length = utf8Length(messageInput.value);
byteCount.textContent = `${length} / ${MAX_BYTES} bytes`;
truncateNotice.hidden = length <= MAX_BYTES;
}
function encodeMessage(text) {
const encoded = encoder.encode(text);
const bytes = encoded.slice(0, MAX_BYTES);
const payloadLength = bytes.length;
const code = new Uint8Array(CODE_BITS);
const payloadBits = [];
// Eight-bit length prefix.
for (let bit = 7; bit >= 0; bit--) {
payloadBits.push((payloadLength >> bit) & 1);
}
// UTF-8 payload bits.
for (const byte of bytes) {
for (let bit = 7; bit >= 0; bit--) {
payloadBits.push((byte >> bit) & 1);
}
}
while (payloadBits.length < DATA_POSITIONS.length) {
payloadBits.push(0);
}
DATA_POSITIONS.forEach((position, index) => {
code[position - 1] = payloadBits[index] & 1;
});
// Standard Hamming parity equations.
for (const parityPosition of PARITY_POSITIONS) {
let parity = 0;
for (const dataPosition of DATA_POSITIONS) {
if (dataPosition & parityPosition) {
parity ^= code[dataPosition - 1];
}
}
code[parityPosition - 1] = parity;
}
// One additional global parity bit makes the code extended.
let overallParity = 0;
for (let index = 0; index < 255; index++) {
overallParity ^= code[index];
}
code[255] = overallParity;
return code;
}
function decodePayload(code) {
const payloadBits = DATA_POSITIONS.map(position => code[position - 1]);
let length = 0;
for (let bit = 0; bit < 8; bit++) {
length = (length << 1) | payloadBits[bit];
}
length = Math.max(0, Math.min(length, MAX_BYTES));
const bytes = [];
for (let byteIndex = 0; byteIndex < length; byteIndex++) {
let value = 0;
const offset = 8 + byteIndex * 8;
for (let bit = 0; bit < 8; bit++) {
value = (value << 1) | (payloadBits[offset + bit] || 0);
}
bytes.push(value);
}
return decoder.decode(new Uint8Array(bytes));
}
function signatureForPosition(position) {
// Bit 8 is the global even-parity check.
let signature = 1 << 8;
if (position <= 255) {
if (PARITY_SET.has(position)) {
const checkIndex = PARITY_POSITIONS.indexOf(position);
signature |= 1 << checkIndex;
} else {
PARITY_POSITIONS.forEach((parityPosition, checkIndex) => {
if (position & parityPosition) {
signature |= 1 << checkIndex;
}
});
}
}
return signature;
}
function classifyErrors(errors) {
/*
* Each changed bit contributes a 9-bit parity signature.
*
* A zero XOR of signatures is an undetectable error component. The
* dynamic program finds the largest zero-signature subset. This lets
* the simulation distinguish individually masked bits from the
* remaining detectable component.
*/
let states = new Array(512).fill(null);
states[0] = { count: 0, mask: 0n };
for (let errorIndex = 0; errorIndex < errors.length; errorIndex++) {
const signature = signatureForPosition(errors[errorIndex].position);
const nextStates = states.slice();
for (let state = 0; state < states.length; state++) {
const current = states[state];
if (!current) continue;
const newState = state ^ signature;
const candidate = {
count: current.count + 1,
mask: current.mask | (1n << BigInt(errorIndex))
};
if (!nextStates[newState] || candidate.count > nextStates[newState].count) {
nextStates[newState] = candidate;
}
}
states = nextStates;
}
const missedMask = states[0] ? states[0].mask : 0n;
const missed = [];
const detected = [];
errors.forEach((error, index) => {
const bit = 1n << BigInt(index);
if (missedMask & bit) {
missed.push(error);
} else {
detected.push(error);
}
});
return { detected, missed };
}
function computeDiagnostics() {
const changed = [];
for (let index = 0; index < CODE_BITS; index++) {
if (received[index] !== original[index]) {
changed.push({
position: index + 1,
original: original[index],
received: received[index]
});
}
}
let hammingSyndrome = 0;
for (let checkIndex = 0; checkIndex < PARITY_POSITIONS.length; checkIndex++) {
const parityPosition = PARITY_POSITIONS[checkIndex];
let check = received[parityPosition - 1];
for (const dataPosition of DATA_POSITIONS) {
if (dataPosition & parityPosition) {
check ^= received[dataPosition - 1];
}
}
if (check) {
hammingSyndrome |= 1 << checkIndex;
}
}
let globalParity = 0;
for (const bit of received) {
globalParity ^= bit;
}
const combinedSyndrome = hammingSyndrome | (globalParity << 8);
const classification = classifyErrors(changed);
return {
changed,
detected: classification.detected,
missed: classification.missed,
hammingSyndrome,
globalParity,
combinedSyndrome,
failed: combinedSyndrome !== 0
};
}
function clearReceived() {
received = original.slice();
}
function setReceivedToOpposite(position) {
received[position - 1] = original[position - 1] ^ 1;
}
function encodeCurrentMessage() {
original = encodeMessage(messageInput.value);
clearReceived();
updateAll();
}
function injectSingleFault() {
clearReceived();
setReceivedToOpposite(3);
updateAll();
}
function injectSilentFault() {
clearReceived();
/*
* The XOR of these four parity signatures is zero.
* All eight Hamming checks and the global parity check therefore pass.
*/
for (const position of [4, 7, 8, 11]) {
setReceivedToOpposite(position);
}
updateAll();
}
function injectRandomFault() {
const alreadyChanged = new Set(
Array.from({ length: CODE_BITS }, (_, index) => index + 1)
.filter(position => received[position - 1] !== original[position - 1])
);
const available = [];
for (let position = 1; position <= CODE_BITS; position++) {
if (!alreadyChanged.has(position)) available.push(position);
}
if (available.length) {
const choice = available[Math.floor(Math.random() * available.length)];
setReceivedToOpposite(choice);
}
updateAll();
}
function createErrorChip(error, kind) {
const element = document.createElement("div");
element.className = `error-chip ${kind}`;
const { x, y, z } = positionToXYZ(error.position);
element.textContent =
`#${String(error.position).padStart(3, "0")} ` +
`X${x} Y${y} Z${z} · ` +
`${error.original}→${error.received} · ${roleForPosition(error.position)}`;
return element;
}
function renderErrorList(container, errors, kind) {
container.replaceChildren();
if (!errors.length) {
const empty = document.createElement("div");
empty.className = "empty";
empty.textContent = kind === "detected"
? "NO DETECTED FAULTS"
: "NO MASKED FAULTS";
container.appendChild(empty);
return;
}
for (const error of errors) {
container.appendChild(createErrorChip(error, kind));
}
}
function renderSyndrome(diagnostics) {
syndromeBits.replaceChildren();
const labels = [
"P1", "P2", "P4", "P8", "P16", "P32", "P64", "P128", "EXT"
];
labels.forEach((label, index) => {
const bit = document.createElement("div");
const failed = index === 8
? diagnostics.globalParity !== 0
: (diagnostics.hammingSyndrome & (1 << index)) !== 0;
bit.className = `syndrome-bit${failed ? " fail" : ""}`;
bit.textContent = label;
bit.title = failed ? "Check failed" : "Check passed";
syndromeBits.appendChild(bit);
});
syndromeValue.textContent =
`0x${diagnostics.combinedSyndrome.toString(16).padStart(3, "0").toUpperCase()}`;
}
function renderDiagnostics(diagnostics) {
changedMetric.textContent = diagnostics.changed.length;
detectedMetric.textContent = diagnostics.detected.length;
missedMetric.textContent = diagnostics.missed.length;
statusCard.classList.remove("clean", "detected", "missed");
if (!diagnostics.changed.length) {
statusCard.classList.add("clean");
statusTitle.textContent = "CLEAN FRAME";
statusDetail.textContent =
"All 256 bits agree with the original and all parity equations pass.";
} else if (diagnostics.failed) {
statusCard.classList.add("detected");
statusTitle.textContent = "ERROR DETECTED";
statusDetail.textContent =
"The receiver can flag corruption from its syndrome. It cannot identify or repair the exact bits.";
} else {
statusCard.classList.add("missed");
statusTitle.textContent = "SILENT CORRUPTION";
statusDetail.textContent =
"The received bits differ from the original, but every parity equation passes. The fault is invisible to this code.";
}
renderSyndrome(diagnostics);
renderErrorList(detectedList, diagnostics.detected, "detected");
renderErrorList(missedList, diagnostics.missed, "missed");
const originalText = decodePayload(original);
const rawReceivedText = decodePayload(received);
originalPayload.textContent = originalText.length ? originalText : "(empty message)";
receivedPayload.textContent = rawReceivedText.length ? rawReceivedText : "(empty message)";
if (originalText === rawReceivedText) {
payloadState.textContent =
"The raw payload happens to read correctly. This does not imply that the complete codeword is intact; parity-only faults can still exist.";
} else {
payloadState.textContent =
"The raw payload differs from the original. It is shown for diagnosis only and is never written back into the received frame.";
}
}
function getStatusMap(diagnostics) {
const map = new Map();
for (const error of diagnostics.detected) {
map.set(error.position, "detected");
}
for (const error of diagnostics.missed) {
map.set(error.position, "missed");
}
return map;
}
function baseColor(position, bit) {
if (PARITY_SET.has(position) || position === 256) {
return bit ? COLORS.parityOne : COLORS.parityZero;
}
return bit ? COLORS.dataOne : COLORS.dataZero;
}
function updateCubes(diagnostics) {
if (!cubeMesh) return;
const statusMap = getStatusMap(diagnostics);
for (let index = 0; index < CODE_BITS; index++) {
const position = index + 1;
const world = positionToWorld(position);
const changedStatus = statusMap.get(position);
dummy.position.set(world.x, world.y, world.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(1);
dummy.updateMatrix();
cubeMesh.setMatrixAt(index, dummy.matrix);
let color;
if (viewMode === "original") {
color = baseColor(position, original[index]);
} else if (viewMode === "difference") {
color = changedStatus
? (changedStatus === "detected" ? COLORS.detected : COLORS.missed)
: (original[index] ? COLORS.diffOne : COLORS.diffZero);
} else {
color = changedStatus
? (changedStatus === "detected" ? COLORS.detected : COLORS.missed)
: baseColor(position, received[index]);
}
cubeMesh.setColorAt(index, color);
if (changedStatus && viewMode !== "original") {
dummy.scale.setScalar(1.24);
dummy.updateMatrix();
statusMesh.setMatrixAt(index, dummy.matrix);
statusMesh.setColorAt(
index,
changedStatus === "detected" ? COLORS.detected : COLORS.missed
);
} else {
dummy.scale.setScalar(0.0001);
dummy.updateMatrix();
statusMesh.setMatrixAt(index, dummy.matrix);
statusMesh.setColorAt(index, COLORS.diffZero);
}
}
cubeMesh.instanceMatrix.needsUpdate = true;
cubeMesh.instanceColor.needsUpdate = true;
statusMesh.instanceMatrix.needsUpdate = true;
statusMesh.instanceColor.needsUpdate = true;
}
function updateAll() {
currentDiagnostics = computeDiagnostics();
renderDiagnostics(currentDiagnostics);
updateCubes(currentDiagnostics);
}
function makeStaticEdges() {
const edgePositions = [];
const half = 0.43;
const edges = [
[0, 1], [1, 3], [3, 2], [2, 0],
[4, 5], [5, 7], [7, 6], [6, 4],
[0, 4], [1, 5], [2, 6], [3, 7]
];
for (let position = 1; position <= CODE_BITS; position++) {
const world = positionToWorld(position);
const corners = [
[world.x - half, world.y - half, world.z - half],
[world.x + half, world.y - half, world.z - half],
[world.x - half, world.y + half, world.z - half],
[world.x + half, world.y + half, world.z - half],
[world.x - half, world.y - half, world.z + half],
[world.x + half, world.y - half, world.z + half],
[world.x - half, world.y + half, world.z + half],
[world.x + half, world.y + half, world.z + half]
];
for (const [a, b] of edges) {
edgePositions.push(...corners[a], ...corners[b]);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(edgePositions, 3)
);
const material = new THREE.LineBasicMaterial({
color: 0x7791b5,
transparent: true,
opacity: 0.16
});
const lines = new THREE.LineSegments(geometry, material);
scene.add(lines);
}
function initThree() {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
scene = new THREE.Scene();
scene.background = new THREE.Color("#070c14");
scene.fog = new THREE.FogExp2("#070c14", 0.024);
camera = new THREE.PerspectiveCamera(43, 1, 0.1, 120);
const hemisphere = new THREE.HemisphereLight(0x9fc8ff, 0x111827, 1.5);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd9f7ff, 2.8);
keyLight.position.set(8, 12, 10);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x6c63ff, 1.8);
rimLight.position.set(-10, 5, -8);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0x35d9aa, 18, 30, 2);
warmLight.position.set(6, -2, 7);
scene.add(warmLight);
const cubeGeometry = new THREE.BoxGeometry(0.82, 0.82, 0.82);
const cubeMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.34,
metalness: 0.12,
vertexColors: true
});
cubeMesh = new THREE.InstancedMesh(cubeGeometry, cubeMaterial, CODE_BITS);
cubeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
cubeMesh.frustumCulled = false;
scene.add(cubeMesh);
const statusGeometry = new THREE.BoxGeometry(0.82, 0.82, 0.82);
const statusMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.24,
depthWrite: false,
blending: THREE.AdditiveBlending,
vertexColors: true
});
statusMesh = new THREE.InstancedMesh(statusGeometry, statusMaterial, CODE_BITS);
statusMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
statusMesh.frustumCulled = false;
scene.add(statusMesh);
makeStaticEdges();
const hoverGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(1.02, 1.02, 1.02)
);
const hoverMaterial = new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.9
});
hoverMesh = new THREE.LineSegments(hoverGeometry, hoverMaterial);
hoverMesh.visible = false;
scene.add(hoverMesh);
const grid = new THREE.GridHelper(10, 10, 0x284761, 0x132236);
grid.position.y = -4.34;
grid.material.transparent = true;
grid.material.opacity = 0.44;
scene.add(grid);
raycaster = new THREE.Raycaster();
pointer = new THREE.Vector2();
resetCamera();
resizeRenderer();
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(canvas.parentElement);
setupCameraControls();
animate();
}
function resizeRenderer() {
if (!renderer || !camera) return;
const width = Math.max(1, Math.floor(canvas.clientWidth));
const height = Math.max(1, Math.floor(canvas.clientHeight));
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraYaw = 0.72;
cameraPitch = 0.55;
cameraRadius = 20.5;
cameraTarget.set(0, 0, 0);
updateCamera();
}
function updateCamera() {
if (!camera) return;
const sinPitch = Math.sin(cameraPitch);
camera.position.set(
cameraTarget.x + cameraRadius * sinPitch * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.cos(cameraPitch),
cameraTarget.z + cameraRadius * sinPitch * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
function panCamera(deltaX, deltaY) {
const forward = cameraTarget.clone().sub(camera.position).normalize();
const right = forward.clone().cross(camera.up).normalize();
const up = right.clone().cross(forward).normalize();
const scale = cameraRadius * 0.0015;
cameraTarget.addScaledVector(right, -deltaX * scale);
cameraTarget.addScaledVector(up, deltaY * scale);
}
function raycastAt(clientX, clientY) {
if (!renderer || !camera) return null;
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(cubeMesh, false);
return hits.length ? hits[0] : null;
}
function updateHover(clientX, clientY) {
const hit = raycastAt(clientX, clientY);
if (!hit || hit.instanceId === undefined) {
hoverMesh.visible = false;
hoverInfo.style.display = "none";
canvas.style.cursor = "grab";
return;
}
const position = hit.instanceId + 1;
const world = positionToWorld(position);
const { x, y, z } = positionToXYZ(position);
const status = getStatusMap(currentDiagnostics).get(position);
hoverMesh.position.set(world.x, world.y, world.z);
hoverMesh.visible = true;
canvas.style.cursor = "pointer";
const statusText = status
? `\nSTATUS: ${status.toUpperCase()}`
: "";
hoverInfo.textContent =
`CODE #${String(position).padStart(3, "0")} · ${roleForPosition(position)}\n` +
`X${x} Y${y} Z${z}\n` +
`ORIGINAL ${original[position - 1]} RECEIVED ${received[position - 1]}` +
statusText;
hoverInfo.style.display = "block";
}
function flipReceived(position) {
received[position - 1] ^= 1;
updateAll();
}
function setupCameraControls() {
const pointers = new Map();
let gestureMoved = false;
let pinchDistance = 0;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
mode: event.button === 2 || event.shiftKey ? "pan" : "orbit"
});
if (pointers.size === 1) {
gestureMoved = false;
canvas.style.cursor = "grabbing";
}
if (pointers.size === 2) {
const values = [...pointers.values()];
pinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
canvas.addEventListener("pointermove", event => {
const current = pointers.get(event.pointerId);
if (!current) {
updateHover(event.clientX, event.clientY);
return;
}
const deltaX = event.clientX - current.x;
const deltaY = event.clientY - current.y;
current.x = event.clientX;
current.y = event.clientY;
if (Math.abs(deltaX) + Math.abs(deltaY) > 1) {
gestureMoved = true;
}
if (pointers.size === 1) {
if (current.mode === "pan") {
panCamera(deltaX, deltaY);
} else {
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + deltaY * 0.006,
0.18,
1.42
);
}
updateCamera();
} else if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (pinchDistance > 0) {
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * (pinchDistance / Math.max(distance, 1)),
10,
36
);
updateCamera();
}
pinchDistance = distance;
}
});
canvas.addEventListener("pointerup", event => {
const wasClick = !gestureMoved && pointers.size === 1 && event.button === 0;
pointers.delete(event.pointerId);
if (wasClick) {
const hit = raycastAt(event.clientX, event.clientY);
if (hit && hit.instanceId !== undefined) {
flipReceived(hit.instanceId + 1);
}
}
if (pointers.size === 0) {
canvas.style.cursor = "grab";
updateHover(event.clientX, event.clientY);
}
});
canvas.addEventListener("pointercancel", event => {
pointers.delete(event.pointerId);
gestureMoved = false;
});
canvas.addEventListener("pointerleave", () => {
if (!pointers.size) {
hoverMesh.visible = false;
hoverInfo.style.display = "none";
}
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
10,
36
);
updateCamera();
}, { passive: false });
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
messageInput.addEventListener("input", updateInputMeta);
encodeButton.addEventListener("click", encodeCurrentMessage);
singleFaultButton.addEventListener("click", injectSingleFault);
silentFaultButton.addEventListener("click", injectSilentFault);
randomFaultButton.addEventListener("click", injectRandomFault);
clearButton.addEventListener("click", () => {
clearReceived();
updateAll();
});
resetCameraButton.addEventListener("click", resetCamera);
document.querySelectorAll("[data-view]").forEach(button => {
button.addEventListener("click", () => {
viewMode = button.dataset.view;
document.querySelectorAll("[data-view]").forEach(candidate => {
candidate.classList.toggle("active", candidate === button);
});
if (currentDiagnostics) updateCubes(currentDiagnostics);
});
});
initThree();
updateInputMeta();
encodeCurrentMessage();
</script>
</body>
</html>
```