Prompt specification
Build or customize the Three.js 3D scene "Light and Object Degrees of Freedom" 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: Light and Object Degrees of Freedom
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/light-and-object-degrees-of-freedom-x3500
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a shadow puzzle offering both object rotation and light translation. Display several valid solutions when they produce the same silhouette under the chosen tolerance. Low-poly.
Working Three.js Starter (light-and-object-degrees-of-freedom-x3500):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shadow Form — Low-Poly Shadow Puzzle</title>
<style>
:root {
--bg: #080b11;
--panel: #10151e;
--panel-2: #151b26;
--line: #273142;
--text: #edf3fb;
--muted: #8c9aae;
--cyan: #67e6ff;
--amber: #ffb45f;
--green: #77efb1;
--red: #ff7285;
--shadow: 0 20px 55px rgba(0, 0, 0, .32);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background:
radial-gradient(circle at 50% -20%, #1c2940 0, transparent 48%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, input { font: inherit; }
button { color: inherit; }
.app {
width: min(1600px, 100%);
margin: 0 auto;
padding: 18px;
}
header {
min-height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 4px 4px 18px;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border: 1px solid #3d536c;
background: linear-gradient(145deg, #1c293b, #0e141e);
box-shadow: inset 0 0 0 4px #0a0f17;
transform: rotate(45deg);
border-radius: 10px;
}
.brand-mark::after {
content: "";
width: 13px;
height: 13px;
background: var(--cyan);
box-shadow: 0 0 18px rgba(103, 230, 255, .55);
border-radius: 3px;
}
h1 {
margin: 0;
font-size: clamp(20px, 2vw, 30px);
letter-spacing: -.04em;
line-height: 1;
}
.eyebrow {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
letter-spacing: .19em;
text-transform: uppercase;
}
.header-status {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(15, 20, 29, .8);
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 12px currentColor;
}
.status-dot.good {
color: var(--green);
background: var(--green);
}
.workspace {
display: grid;
grid-template-columns: 286px minmax(460px, 1fr) 342px;
grid-template-areas: "controls stage analysis";
gap: 14px;
align-items: stretch;
}
.panel {
border: 1px solid var(--line);
border-radius: 18px;
background: linear-gradient(160deg, rgba(22, 29, 41, .96), rgba(12, 17, 25, .98));
box-shadow: var(--shadow);
}
.controls-panel {
grid-area: controls;
padding: 18px;
}
.analysis-panel {
grid-area: analysis;
padding: 18px;
overflow: hidden;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 17px;
}
.panel-title h2 {
margin: 0;
font-size: 13px;
letter-spacing: .08em;
text-transform: uppercase;
}
.tiny {
color: var(--muted);
font-size: 10px;
letter-spacing: .06em;
text-transform: uppercase;
}
.section {
padding: 16px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type { border-top: 0; padding-top: 0; }
.section-heading {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 15px;
font-size: 12px;
font-weight: 750;
letter-spacing: .07em;
text-transform: uppercase;
}
.section-heading .icon {
width: 25px;
height: 25px;
display: grid;
place-items: center;
border: 1px solid #33445a;
border-radius: 7px;
color: var(--cyan);
font-size: 12px;
background: #101a27;
}
.control { margin: 0 0 15px; }
.control:last-child { margin-bottom: 0; }
.control-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 7px;
color: #cbd5e4;
font-size: 11px;
}
output {
min-width: 51px;
padding: 3px 7px;
border: 1px solid #2c394b;
border-radius: 6px;
background: #0a1018;
color: var(--amber);
font: 10px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
text-align: center;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 7px 0;
appearance: none;
background: #2a3444;
border-radius: 99px;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
appearance: none;
border: 2px solid #0c121b;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px #67e6ff66, 0 0 12px rgba(103, 230, 255, .28);
cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #0c121b;
border-radius: 50%;
background: var(--cyan);
cursor: pointer;
}
.tolerance-box {
padding: 13px;
border: 1px solid #304158;
border-radius: 12px;
background: linear-gradient(145deg, #121d2b, #0c121b);
}
.tolerance-value {
color: var(--cyan);
font: 700 18px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
border: 1px solid #334258;
border-radius: 10px;
background: #141c28;
padding: 9px 11px;
color: #d9e3f1;
cursor: pointer;
transition: background .16s ease, border-color .16s ease, transform .16s ease;
}
button:hover {
background: #1b2736;
border-color: #526983;
}
button:active { transform: translateY(1px); }
button.primary {
border-color: #51cde5;
background: var(--cyan);
color: #071018;
font-weight: 800;
}
button.primary:hover { background: #91efff; }
button.ghost {
background: transparent;
}
.stage {
grid-area: stage;
position: relative;
min-height: 680px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 18px;
background: #0c1119;
box-shadow: var(--shadow);
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.stage-top {
position: absolute;
z-index: 2;
top: 14px;
left: 14px;
right: 14px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
pointer-events: none;
}
.mode-switch {
display: flex;
padding: 4px;
border: 1px solid #344155;
border-radius: 11px;
background: rgba(10, 15, 23, .88);
backdrop-filter: blur(10px);
pointer-events: auto;
}
.mode-switch button {
padding: 7px 10px;
border: 0;
background: transparent;
font-size: 11px;
}
.mode-switch button.active {
background: #24364a;
color: var(--cyan);
box-shadow: inset 0 0 0 1px #426078;
}
.stage-label {
padding: 8px 11px;
border: 1px solid #344155;
border-radius: 10px;
background: rgba(10, 15, 23, .8);
color: var(--muted);
font: 10px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .08em;
text-transform: uppercase;
}
.stage-bottom {
position: absolute;
z-index: 2;
left: 14px;
right: 14px;
bottom: 14px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
padding: 9px 11px;
border: 1px solid #344155;
border-radius: 10px;
background: rgba(10, 15, 23, .82);
color: var(--muted);
font-size: 10px;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 15px;
height: 3px;
border-radius: 4px;
background: var(--cyan);
}
.swatch.current { background: var(--amber); }
.hint {
max-width: 210px;
color: #8e9caf;
font-size: 10px;
line-height: 1.45;
text-align: right;
}
.silhouette-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.shape-card {
overflow: hidden;
border: 1px solid #2d394b;
border-radius: 12px;
background: #0a0f16;
}
.shape-head {
display: flex;
justify-content: space-between;
padding: 9px 10px 6px;
border-bottom: 1px solid #202a38;
color: var(--muted);
font-size: 9px;
letter-spacing: .11em;
text-transform: uppercase;
}
.shape-card canvas {
width: 100%;
height: 118px;
display: block;
}
.shape-foot {
padding: 7px 10px 9px;
border-top: 1px solid #202a38;
color: #bec9d8;
font: 10px ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
}
.match-card {
margin-top: 12px;
padding: 13px;
border: 1px solid #304158;
border-radius: 12px;
background: #0b1119;
}
.match-row {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 10px;
}
.match-score {
color: var(--amber);
font: 750 21px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.match-score.good { color: var(--green); }
.meter {
height: 5px;
margin-top: 10px;
overflow: hidden;
border-radius: 99px;
background: #263142;
}
.meter-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--amber);
transition: width .2s ease, background .2s ease;
}
.meter-fill.good { background: var(--green); }
.solutions-head {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 10px;
margin: 17px 0 11px;
}
.solutions-head h3 {
margin: 0 0 3px;
font-size: 12px;
letter-spacing: .08em;
text-transform: uppercase;
}
.solution-count {
color: var(--cyan);
font: 10px ui-monospace, SFMono-Regular, Menlo, monospace;
}
#solutions {
display: grid;
gap: 9px;
max-height: 495px;
overflow: auto;
padding-right: 3px;
scrollbar-width: thin;
scrollbar-color: #3b4b61 #111722;
}
.solution {
display: grid;
grid-template-columns: 88px 1fr;
gap: 10px;
padding: 10px;
border: 1px solid #2b3748;
border-radius: 12px;
background: linear-gradient(145deg, #111923, #0c121b);
transition: border-color .16s ease, transform .16s ease;
}
.solution:hover {
border-color: #4f6d87;
transform: translateY(-1px);
}
.solution canvas {
width: 88px;
height: 76px;
border-radius: 8px;
background: #080d14;
}
.solution-info {
min-width: 0;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 7px;
}
.solution-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
}
.valid {
color: var(--green);
font-size: 8px;
font-weight: 850;
letter-spacing: .1em;
text-transform: uppercase;
}
.error {
color: var(--muted);
font: 9px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.solution-values {
color: #aebaca;
font: 9px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.solution button {
width: 100%;
padding: 5px 8px;
border-radius: 7px;
font-size: 9px;
letter-spacing: .08em;
text-transform: uppercase;
}
.loading {
padding: 22px 12px;
border: 1px dashed #34445a;
border-radius: 12px;
color: var(--muted);
font-size: 11px;
text-align: center;
}
footer {
padding: 13px 4px 0;
color: #627087;
font-size: 10px;
text-align: center;
}
@media (max-width: 1180px) {
.workspace {
grid-template-columns: 1fr 1fr;
grid-template-areas:
"stage stage"
"controls analysis";
}
.stage { min-height: 610px; }
}
@media (max-width: 720px) {
.app { padding: 10px; }
header { align-items: flex-start; }
.header-status { display: none; }
.workspace {
grid-template-columns: 1fr;
grid-template-areas: "stage" "controls" "analysis";
}
.stage { min-height: 500px; }
.stage-top { flex-direction: column; }
.hint { display: none; }
.silhouette-grid { grid-template-columns: 1fr 1fr; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Shadow Form</h1>
<div class="eyebrow">Low-poly optical puzzle</div>
</div>
</div>
<div class="header-status">
<span class="status-dot" id="statusDot"></span>
<span id="headerStatus">Search for a matching silhouette</span>
</div>
</header>
<main class="workspace">
<aside class="panel controls-panel">
<div class="panel-title">
<h2>Controls</h2>
<span class="tiny">Live</span>
</div>
<section class="section">
<div class="section-heading">
<span class="icon">◇</span>
Object rotation
</div>
<div class="control">
<div class="control-head"><label for="rotY">Yaw · vertical axis</label><output id="rotYOut"></output></div>
<input id="rotY" type="range" min="-180" max="180" step="1" value="-34">
</div>
<div class="control">
<div class="control-head"><label for="rotX">Tilt · horizontal axis</label><output id="rotXOut"></output></div>
<input id="rotX" type="range" min="-60" max="60" step="1" value="21">
</div>
<div class="control">
<div class="control-head"><label for="rotZ">Roll · depth axis</label><output id="rotZOut"></output></div>
<input id="rotZ" type="range" min="-180" max="180" step="1" value="-26">
</div>
</section>
<section class="section">
<div class="section-heading">
<span class="icon">✦</span>
Light translation
</div>
<div class="control">
<div class="control-head"><label for="lightX">Light X</label><output id="lightXOut"></output></div>
<input id="lightX" type="range" min="-2.8" max="2.8" step="0.01" value="1.35">
</div>
<div class="control">
<div class="control-head"><label for="lightY">Light Y</label><output id="lightYOut"></output></div>
<input id="lightY" type="range" min="1.1" max="5.8" step="0.01" value="4.25">
</div>
<div class="control">
<div class="control-head"><label for="lightZ">Light depth</label><output id="lightZOut"></output></div>
<input id="lightZ" type="range" min="2.4" max="6.6" step="0.01" value="5.05">
</div>
</section>
<section class="section">
<div class="section-heading">
<span class="icon">≈</span>
Match tolerance
</div>
<div class="tolerance-box">
<div class="match-row">
<span class="tiny">Boundary error</span>
<span class="tolerance-value" id="toleranceValue">11%</span>
</div>
<input id="tolerance" type="range" min="2" max="24" step="1" value="11" aria-label="Silhouette tolerance">
<div class="tiny" style="margin-top:5px; line-height:1.45; text-transform:none; letter-spacing:0">
Position and scale are normalized. Rotation and proportions remain significant.
</div>
</div>
</section>
<section class="section">
<div class="button-row" style="margin-bottom:8px">
<button id="resetBtn" class="ghost">Reset object</button>
<button id="randomBtn" class="ghost">Randomize</button>
</div>
<div class="button-row">
<button id="targetBtn" class="ghost">Use current as target</button>
<button id="revealBtn" class="primary">Reveal target</button>
</div>
</section>
</aside>
<section class="stage" aria-label="Interactive three-dimensional shadow scene">
<div id="viewport"></div>
<div class="stage-top">
<div class="mode-switch" aria-label="Pointer interaction mode">
<button id="rotateMode" class="active">Rotate object</button>
<button id="lightMode">Move light</button>
</div>
<div class="stage-label">Perspective shadow / wall plane z −3.2</div>
</div>
<div class="stage-bottom">
<div class="legend">
<span><i class="swatch"></i>Target outline</span>
<span><i class="swatch current"></i>Current outline</span>
</div>
<div class="hint">
Drag in the viewport to rotate the object, or switch to Move light and drag the source in depth.
</div>
</div>
</section>
<aside class="panel analysis-panel">
<div class="panel-title">
<h2>Silhouette analysis</h2>
<span class="tiny">Normalized</span>
</div>
<div class="silhouette-grid">
<div class="shape-card">
<div class="shape-head"><span>Target</span><span>Reference</span></div>
<canvas id="targetCanvas" width="320" height="236" aria-label="Target silhouette"></canvas>
<div class="shape-foot" id="targetFoot">Awaiting target</div>
</div>
<div class="shape-card">
<div class="shape-head"><span>Current</span><span>Live</span></div>
<canvas id="currentCanvas" width="320" height="236" aria-label="Current silhouette"></canvas>
<div class="shape-foot" id="currentFoot">—</div>
</div>
</div>
<div class="match-card">
<div class="match-row">
<div>
<div class="tiny">Current silhouette error</div>
<div class="tiny" id="matchState" style="margin-top:5px; text-transform:none; letter-spacing:0">Outside tolerance</div>
</div>
<div class="match-score" id="matchScore">—</div>
</div>
<div class="meter"><div class="meter-fill" id="meterFill"></div></div>
</div>
<div class="solutions-head">
<div>
<h3>Valid solutions</h3>
<div class="tiny">Distinct control states inside tolerance</div>
</div>
<div class="solution-count" id="solutionCount">0 found</div>
</div>
<div id="solutions">
<div class="loading">Computing equivalent silhouettes…</div>
</div>
</aside>
</main>
<footer>Three.js core only · procedural low-poly geometry · no external assets</footer>
</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 clamp = THREE.MathUtils.clamp;
const rad = THREE.MathUtils.degToRad;
const WALL_Z = -3.2;
const OBJECT_Y = 1.35;
const DESCRIPTOR_SAMPLES = 64;
const initialState = {
yaw: -34,
tilt: 21,
roll: -26,
lx: 1.35,
ly: 4.25,
lz: 5.05
};
const targetState = {
yaw: 22,
tilt: -14,
roll: 11,
lx: -0.85,
ly: 3.25,
lz: 4.15
};
let state = { ...initialState };
let target = { ...targetState };
let tolerance = 11;
let targetHull = [];
let currentHull = [];
let targetDescriptor = null;
let solutionPool = [];
let poolBuildId = 0;
let interactionMode = "rotate";
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0c1119);
scene.fog = new THREE.Fog(0x0c1119, 11, 23);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 60);
camera.position.set(0, 3.35, 8.15);
camera.lookAt(0, 1.55, -0.55);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive low-poly shadow puzzle viewport");
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb9d8ff, 0x17131c, 1.55);
scene.add(hemisphere);
const fillLight = new THREE.DirectionalLight(0x6e9dcc, 1.35);
fillLight.position.set(-5, 6, 5);
scene.add(fillLight);
const pointLight = new THREE.PointLight(0xffd9a3, 115, 28, 2);
pointLight.castShadow = true;
pointLight.shadow.mapSize.set(1024, 1024);
pointLight.shadow.camera.near = 0.15;
pointLight.shadow.camera.far = 24;
pointLight.shadow.bias = -0.00025;
pointLight.shadow.normalBias = 0.025;
scene.add(pointLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(14, 14),
new THREE.MeshStandardMaterial({
color: 0x0d121b,
roughness: 0.92,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = 0;
floor.receiveShadow = true;
scene.add(floor);
const wall = new THREE.Mesh(
new THREE.PlaneGeometry(12, 7),
new THREE.MeshStandardMaterial({
color: 0x171d28,
roughness: 0.94,
metalness: 0.03,
side: THREE.DoubleSide
})
);
wall.position.set(0, 3.25, WALL_Z);
wall.receiveShadow = true;
scene.add(wall);
const wallGridPoints = [];
for (let x = -6; x <= 6; x += 0.5) {
wallGridPoints.push(new THREE.Vector3(x, 0, WALL_Z + 0.008), new THREE.Vector3(x, 6.5, WALL_Z + 0.008));
}
for (let y = 0; y <= 6.5; y += 0.5) {
wallGridPoints.push(new THREE.Vector3(-6, y, WALL_Z + 0.008), new THREE.Vector3(6, y, WALL_Z + 0.008));
}
const wallGrid = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(wallGridPoints),
new THREE.LineBasicMaterial({
color: 0x334052,
transparent: true,
opacity: 0.24,
depthWrite: false
})
);
scene.add(wallGrid);
const floorGrid = new THREE.GridHelper(12, 24, 0x34445a, 0x263142);
floorGrid.position.y = 0.012;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.28;
scene.add(floorGrid);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(0.72, 0.88, 0.46, 8),
new THREE.MeshStandardMaterial({
color: 0x202a38,
roughness: 0.72,
metalness: 0.18,
flatShading: true
})
);
pedestal.position.y = 0.23;
pedestal.receiveShadow = true;
scene.add(pedestal);
const objectGeometry = new THREE.IcosahedronGeometry(1.13, 0);
const objectMaterial = new THREE.MeshStandardMaterial({
color: 0xe5a45e,
roughness: 0.56,
metalness: 0.14,
flatShading: true
});
const puzzleObject = new THREE.Mesh(objectGeometry, objectMaterial);
puzzleObject.position.y = OBJECT_Y;
puzzleObject.castShadow = true;
puzzleObject.receiveShadow = true;
scene.add(puzzleObject);
const objectEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(objectGeometry, 12),
new THREE.LineBasicMaterial({
color: 0x40251b,
transparent: true,
opacity: 0.7
})
);
puzzleObject.add(objectEdges);
const lightMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.12, 0),
new THREE.MeshBasicMaterial({ color: 0xffe5a7 })
);
scene.add(lightMarker);
const lightHalo = new THREE.Mesh(
new THREE.OctahedronGeometry(0.22, 0),
new THREE.MeshBasicMaterial({
color: 0xffc76e,
transparent: true,
opacity: 0.15,
depthWrite: false
})
);
scene.add(lightHalo);
const beamGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3(0, OBJECT_Y, 0)
]);
const beam = new THREE.Line(
beamGeometry,
new THREE.LineDashedMaterial({
color: 0xffd590,
transparent: true,
opacity: 0.22,
dashSize: 0.12,
gapSize: 0.1
})
);
beam.computeLineDistances();
scene.add(beam);
function makeOutline(color) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(new Float32Array(3), 3));
const line = new THREE.LineLoop(
geometry,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.92,
depthWrite: false
})
);
line.frustumCulled = false;
scene.add(line);
return line;
}
const targetOutline = makeOutline(0x67e6ff);
const currentOutline = makeOutline(0xffb45f);
const projectionEuler = new THREE.Euler();
const projectedVertex = new THREE.Vector3();
const geometryPositions = objectGeometry.attributes.position;
function cross(o, a, b) {
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
}
function convexHull(points) {
const unique = [];
const seen = new Set();
for (const p of points) {
const key = `${p[0].toFixed(7)},${p[1].toFixed(7)}`;
if (!seen.has(key)) {
seen.add(key);
unique.push([p[0], p[1]]);
}
}
unique.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
if (unique.length <= 2) return unique;
const lower = [];
for (const p of unique) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
const upper = [];
for (let i = unique.length - 1; i >= 0; i--) {
const p = unique[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
function projectState(parameters) {
projectionEuler.set(
rad(parameters.tilt),
rad(parameters.yaw),
rad(parameters.roll),
"YXZ"
);
const points = [];
const denominatorZ = parameters.lz;
for (let i = 0; i < geometryPositions.count; i++) {
projectedVertex
.fromBufferAttribute(geometryPositions, i)
.applyEuler(projectionEuler)
.add(puzzleObject.position);
const denominator = projectedVertex.z - denominatorZ;
if (Math.abs(denominator) < 0.00001) continue;
const t = (WALL_Z - parameters.lz) / denominator;
points.push([
parameters.lx + t * (projectedVertex.x - parameters.lx),
parameters.ly + t * (projectedVertex.y - parameters.ly)
]);
}
return convexHull(points);
}
function polygonCentroid(hull) {
if (!hull.length) return [0, 0];
let x = 0;
let y = 0;
for (const p of hull) {
x += p[0];
y += p[1];
}
return [x / hull.length, y / hull.length];
}
function radialRadius(hull, angle, origin) {
const dx = Math.cos(angle);
const dy = Math.sin(angle);
let best = Infinity;
for (let i = 0; i < hull.length; i++) {
const a = hull[i];
const b = hull[(i + 1) % hull.length];
const ex = b[0] - a[0];
const ey = b[1] - a[1];
const ax = a[0] - origin[0];
const ay = a[1] - origin[1];
const denominator = dx * ey - dy * ex;
if (Math.abs(denominator) < 1e-9) continue;
const r = (ax * ey - ay * ex) / denominator;
const u = (ax * dy - ay * dx) / denominator;
if (r >= 0 && u >= -1e-7 && u <= 1 + 1e-7 && r < best) {
best = r;
}
}
return Number.isFinite(best) ? best : 0;
}
function buildDescriptor(hull) {
const centroid = polygonCentroid(hull);
let maxRadius = 0;
for (let i = 0; i < DESCRIPTOR_SAMPLES; i++) {
const angle = (i / DESCRIPTOR_SAMPLES) * Math.PI * 2;
maxRadius = Math.max(maxRadius, radialRadius(hull, angle, centroid));
}
if (maxRadius <= 0) return new Float64Array(DESCRIPTOR_SAMPLES);
const descriptor = new Float64Array(DESCRIPTOR_SAMPLES);
for (let i = 0; i < DESCRIPTOR_SAMPLES; i++) {
const angle = (i / DESCRIPTOR_SAMPLES) * Math.PI * 2;
descriptor[i] = radialRadius(hull, angle, centroid) / maxRadius;
}
return descriptor;
}
function compareDescriptors(candidate, reference) {
let difference = 0;
let referenceMean = 0;
for (let i = 0; i < DESCRIPTOR_SAMPLES; i++) {
difference += Math.abs(candidate[i] - reference[i]);
referenceMean += reference[i];
}
referenceMean /= DESCRIPTOR_SAMPLES;
return referenceMean > 0 ? (difference / DESCRIPTOR_SAMPLES / referenceMean) * 100 : 0;
}
function evaluateState(parameters) {
const hull = projectState(parameters);
const descriptor = buildDescriptor(hull);
return {
parameters: { ...parameters },
hull,
score: compareDescriptors(descriptor, targetDescriptor)
};
}
function clampState(parameters) {
return {
yaw: clamp(parameters.yaw, -180, 180),
tilt: clamp(parameters.tilt, -60, 60),
roll: clamp(parameters.roll, -180, 180),
lx: clamp(parameters.lx, -2.8, 2.8),
ly: clamp(parameters.ly, 1.1, 5.8),
lz: clamp(parameters.lz, 2.4, 6.6)
};
}
function randomState() {
return {
yaw: Math.random() * 360 - 180,
tilt: Math.random() * 120 - 60,
roll: Math.random() * 360 - 180,
lx: Math.random() * 5.6 - 2.8,
ly: Math.random() * 4.7 + 1.1,
lz: Math.random() * 4.2 + 2.4
};
}
function stateDistance(a, b) {
return (
Math.abs(a.yaw - b.yaw) / 28 +
Math.abs(a.tilt - b.tilt) / 18 +
Math.abs(a.roll - b.roll) / 28 +
Math.abs(a.lx - b.lx) / 0.35 +
Math.abs(a.ly - b.ly) / 0.35 +
Math.abs(a.lz - b.lz) / 0.35
);
}
function setLinePoints(line, hull) {
const positions = [];
for (const p of hull) {
positions.push(p[0], p[1], WALL_Z + 0.022);
}
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry();
line.geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
}
function normalizedPoints(hull) {
if (!hull.length) return [];
const center = polygonCentroid(hull);
let maxRadius = 0;
for (const p of hull) {
maxRadius = Math.max(maxRadius, Math.hypot(p[0] - center[0], p[1] - center[1]));
}
if (maxRadius <= 0) return hull.map(() => [0, 0]);
return hull.map(p => [
(p[0] - center[0]) / maxRadius,
(p[1] - center[1]) / maxRadius
]);
}
function drawSilhouette(canvas, hull, fillColor, strokeColor, overlayHull = null) {
const context = canvas.getContext("2d");
const width = canvas.width;
const height = canvas.height;
context.clearRect(0, 0, width, height);
context.fillStyle = "#080d14";
context.fillRect(0, 0, width, height);
context.strokeStyle = "rgba(98, 121, 148, .13)";
context.lineWidth = 1;
context.beginPath();
for (let x = 0; x <= width; x += width / 6) {
context.moveTo(x, 0);
context.lineTo(x, height);
}
for (let y = 0; y <= height; y += height / 5) {
context.moveTo(0, y);
context.lineTo(width, y);
}
context.stroke();
const drawPath = (points, fill, stroke, dashed = false) => {
if (!points.length) return;
const normalized = normalizedPoints(points);
const scale = Math.min(width, height) * 0.34;
context.save();
context.translate(width / 2, height / 2);
context.beginPath();
normalized.forEach((p, index) => {
const x = p[0] * scale;
const y = -p[1] * scale;
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
context.closePath();
if (fill) {
context.fillStyle = fill;
context.fill();
}
context.setLineDash(dashed ? [6, 5] : []);
context.strokeStyle = stroke;
context.lineWidth = dashed ? 2 : 2.5;
context.stroke();
context.restore();
};
if (overlayHull) {
drawPath(overlayHull, null, "rgba(103, 230, 255, .95)", true);
}
drawPath(hull, fillColor, strokeColor, false);
}
function syncInputs() {
$("rotY").value = state.yaw;
$("rotX").value = state.tilt;
$("rotZ").value = state.roll;
$("lightX").value = state.lx;
$("lightY").value = state.ly;
$("lightZ").value = state.lz;
$("rotYOut").textContent = `${Math.round(state.yaw)}°`;
$("rotXOut").textContent = `${Math.round(state.tilt)}°`;
$("rotZOut").textContent = `${Math.round(state.roll)}°`;
$("lightXOut").textContent = state.lx.toFixed(2);
$("lightYOut").textContent = state.ly.toFixed(2);
$("lightZOut").textContent = state.lz.toFixed(2);
}
function updateScene() {
puzzleObject.rotation.set(rad(state.tilt), rad(state.yaw), rad(state.roll), "YXZ");
pointLight.position.set(state.lx, state.ly, state.lz);
lightMarker.position.copy(pointLight.position);
lightHalo.position.copy(pointLight.position);
const beamPositions = beam.geometry.attributes.position;
beamPositions.setXYZ(0, state.lx, state.ly, state.lz);
beamPositions.setXYZ(1, 0, OBJECT_Y, 0);
beamPositions.needsUpdate = true;
beam.computeLineDistances();
}
function updateTargetVisual() {
targetHull = projectState(target);
targetDescriptor = buildDescriptor(targetHull);
setLinePoints(targetOutline, targetHull);
drawSilhouette($("targetCanvas"), targetHull, "rgba(103, 230, 255, .22)", "#67e6ff");
$("targetFoot").textContent =
`R ${Math.round(target.yaw)}° / ${Math.round(target.tilt)}° / ${Math.round(target.roll)}°`;
}
function updateCurrentVisual() {
currentHull = projectState(state);
setLinePoints(currentOutline, currentHull);
const currentDescriptor = buildDescriptor(currentHull);
const score = compareDescriptors(currentDescriptor, targetDescriptor);
const good = score <= tolerance;
drawSilhouette(
$("currentCanvas"),
currentHull,
"rgba(255, 180, 95, .24)",
"#ffb45f",
targetHull
);
$("currentFoot").textContent = `${score < 0.05 ? "0.0" : score.toFixed(1)}% boundary error`;
$("matchScore").textContent = `${score < 0.05 ? "0.0" : score.toFixed(1)}%`;
$("matchScore").classList.toggle("good", good);
$("matchState").textContent = good ? "Inside selected tolerance" : "Outside tolerance";
$("matchState").style.color = good ? "var(--green)" : "var(--muted)";
$("statusDot").classList.toggle("good", good);
$("headerStatus").textContent = good ? "Silhouette matched" : "Search for a matching silhouette";
const meter = clamp((score / Math.max(tolerance * 2, 0.001)) * 100, 0, 100);
$("meterFill").style.width = `${meter}%`;
$("meterFill").classList.toggle("good", good);
}
function renderAll() {
syncInputs();
updateScene();
updateCurrentVisual();
}
function refineCandidate(start) {
let best = clampState(start);
let bestScore = evaluateState(best).score;
const steps = {
yaw: 24,
tilt: 12,
roll: 24,
lx: 0.65,
ly: 0.45,
lz: 0.65
};
for (let round = 0; round < 9; round++) {
let improved = false;
for (const key of Object.keys(steps)) {
for (const direction of [-1, 1]) {
const candidate = { ...best };
candidate[key] += steps[key] * direction;
const clamped = clampState(candidate);
const score = evaluateState(clamped).score;
if (score < bestScore - 0.0001) {
best = clamped;
bestScore = score;
improved = true;
}
}
}
if (!improved) {
for (const key of Object.keys(steps)) steps[key] *= 0.56;
}
}
return evaluateState(best);
}
function makeMicroVariants(base) {
const variants = [];
const variations = {
yaw: [0.15, 0.3, 0.6, 1, 2, 4],
tilt: [0.15, 0.3, 0.6, 1, 2],
roll: [0.15, 0.3, 0.6, 1, 2, 4],
lx: [0.005, 0.01, 0.025, 0.05, 0.1],
ly: [0.005, 0.01, 0.025, 0.05, 0.1],
lz: [0.005, 0.01, 0.025, 0.05, 0.1]
};
for (const [key, values] of Object.entries(variations)) {
for (const value of values) {
for (const direction of [-1, 1]) {
const candidate = { ...base };
candidate[key] += value * direction;
variants.push(clampState(candidate));
}
}
}
return variants;
}
async function rebuildSolutionPool() {
const buildId = ++poolBuildId;
$("solutions").innerHTML = '<div class="loading">Computing equivalent silhouettes…</div>';
$("solutionCount").textContent = "searching";
await new Promise(resolve => setTimeout(resolve, 35));
if (buildId !== poolBuildId) return;
const evaluations = [];
evaluations.push(evaluateState(target));
for (let i = 0; i < 1050; i++) {
evaluations.push(evaluateState(randomState()));
}
evaluations.sort((a, b) => a.score - b.score);
const refined = [];
const refinementSeeds = evaluations.slice(0, 11);
for (const seed of refinementSeeds) {
refined.push(refineCandidate(seed.parameters));
}
const combined = [...evaluations, ...refined];
const variantSeeds = [target, ...refined.slice(0, 8).map(item => item.parameters)];
for (const seed of variantSeeds) {
for (const variant of makeMicroVariants(seed)) {
combined.push(evaluateState(variant));
}
}
const unique = new Map();
for (const item of combined) {
const p = item.parameters;
const key = [
p.yaw.toFixed(3),
p.tilt.toFixed(3),
p.roll.toFixed(3),
p.lx.toFixed(4),
p.ly.toFixed(4),
p.lz.toFixed(4)
].join("|");
if (!unique.has(key) || unique.get(key).score > item.score) {
unique.set(key, item);
}
}
solutionPool = [...unique.values()].sort((a, b) => a.score - b.score);
if (buildId === poolBuildId) {
refreshSolutions();
}
}
function refreshSolutions() {
const valid = solutionPool.filter(item => item.score <= tolerance + 1e-8);
if (!valid.length) {
$("solutions").innerHTML = '<div class="loading">No solutions inside this tolerance.</div>';
$("solutionCount").textContent = "0 found";
return;
}
const selected = [];
const exact = valid.find(item => item.score < 0.00001);
if (exact) selected.push(exact);
for (const item of valid) {
if (selected.length >= 6) break;
if (selected.some(chosen => stateDistance(chosen.parameters, item.parameters) < 0.055)) continue;
selected.push(item);
}
for (const item of valid) {
if (selected.length >= 6) break;
if (!selected.includes(item)) selected.push(item);
}
$("solutionCount").textContent = `${valid.length} found`;
$("solutions").innerHTML = "";
selected.forEach((item, index) => {
const article = document.createElement("article");
article.className = "solution";
const p = item.parameters;
article.innerHTML = `
<canvas width="176" height="152" aria-label="Candidate solution silhouette"></canvas>
<div class="solution-info">
<div class="solution-top">
<span class="valid">✓ Valid ${String(index + 1).padStart(2, "0")}</span>
<span class="error">${item.score.toFixed(1)}% Δ</span>
</div>
<div class="solution-values">
OBJ ${Math.round(p.yaw)}° / ${Math.round(p.tilt)}° / ${Math.round(p.roll)}°<br>
LIT ${p.lx.toFixed(2)}, ${p.ly.toFixed(2)}, ${p.lz.toFixed(2)}
</div>
<button type="button">Apply solution</button>
</div>
`;
drawSilhouette(
article.querySelector("canvas"),
item.hull,
"rgba(255, 180, 95, .2)",
"#ffb45f",
targetHull
);
article.querySelector("button").addEventListener("click", event => {
state = { ...item.parameters };
renderAll();
const button = event.currentTarget;
const original = button.textContent;
button.textContent = "Applied";
setTimeout(() => button.textContent = original, 700);
});
$("solutions").appendChild(article);
});
}
const inputMap = [
["rotY", "yaw"],
["rotX", "tilt"],
["rotZ", "roll"],
["lightX", "lx"],
["lightY", "ly"],
["lightZ", "lz"]
];
for (const [id, key] of inputMap) {
$(id).addEventListener("input", event => {
state[key] = Number(event.target.value);
renderAll();
});
}
$("tolerance").addEventListener("input", event => {
tolerance = Number(event.target.value);
$("toleranceValue").textContent = `${tolerance}%`;
updateCurrentVisual();
refreshSolutions();
});
$("resetBtn").addEventListener("click", () => {
state = { ...initialState };
renderAll();
});
$("randomBtn").addEventListener("click", () => {
state = randomState();
renderAll();
});
$("targetBtn").addEventListener("click", () => {
target = { ...state };
updateTargetVisual();
updateCurrentVisual();
rebuildSolutionPool();
});
$("revealBtn").addEventListener("click", () => {
state = { ...target };
renderAll();
});
function setMode(mode) {
interactionMode = mode;
$("rotateMode").classList.toggle("active", mode === "rotate");
$("lightMode").classList.toggle("active", mode === "light");
renderer.domElement.style.cursor = mode === "rotate" ? "grab" : "crosshair";
}
$("rotateMode").addEventListener("click", () => setMode("rotate"));
$("lightMode").addEventListener("click", () => setMode("light"));
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const dragPoint = new THREE.Vector3();
let dragging = false;
let dragStartX = 0;
let dragStartY = 0;
let dragInitial = { ...state };
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragStartX = event.clientX;
dragStartY = event.clientY;
dragInitial = { ...state };
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = interactionMode === "rotate" ? "grabbing" : "crosshair";
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
if (interactionMode === "rotate") {
const dx = event.clientX - dragStartX;
const dy = event.clientY - dragStartY;
state.yaw = clamp(dragInitial.yaw + dx * 0.58, -180, 180);
state.tilt = clamp(dragInitial.tilt + dy * 0.45, -60, 60);
} else {
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);
dragPlane.constant = -state.lz;
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
state.lx = clamp(dragPoint.x, -2.8, 2.8);
state.ly = clamp(dragPoint.y, 1.1, 5.8);
}
}
renderAll();
});
function endDrag(event) {
dragging = false;
renderer.domElement.style.cursor = interactionMode === "rotate" ? "grab" : "crosshair";
if (event && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
function resizeRenderer() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(viewport);
updateTargetVisual();
renderAll();
resizeRenderer();
rebuildSolutionPool();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```