Prompt specification
Build or customize the Three.js 3D scene "Symmetry operation explorer" 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: Symmetry operation explorer
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/symmetry-operation-explorer-x1740
Scene Description Prompt:
Symmetry operation explorer. Allow selecting reflection planes and rotation angles for several geometric objects; overlay transformed copies and verify correspondence rather than merely labeling objects symmetric by appearance. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (symmetry-operation-explorer-x1740):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Symmetry Operation Explorer</title>
<style>
:root{
--bg:#0a0e16; --panel:#111827; --panel2:#0d1420; --line:#1f2a3d;
--txt:#e6edf6; --dim:#8ea0b8; --accent:#38bdf8; --good:#34d399; --bad:#fb7185;
--warn:#fbbf24;
}
*{box-sizing:border-box}
html,body{height:100%;margin:0}
body{
background:var(--bg); color:var(--txt);
font:13px/1.45 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
overflow:hidden;
}
#app{display:grid;grid-template-columns:296px 1fr 330px;grid-template-rows:46px 1fr;height:100%}
header{
grid-column:1/4;display:flex;align-items:center;gap:14px;padding:0 14px;
background:linear-gradient(180deg,#111a2a,#0c1320);border-bottom:1px solid var(--line);
}
header h1{font-size:15px;margin:0;letter-spacing:.4px;font-weight:650}
header .sub{color:var(--dim);font-size:12px}
header .spacer{flex:1}
.btn{
background:#182236;border:1px solid #27344d;color:var(--txt);border-radius:7px;
padding:6px 10px;cursor:pointer;font-size:12px;transition:.15s;
}
.btn:hover{background:#223049;border-color:#38507a}
.btn.primary{background:linear-gradient(180deg,#0ea5e9,#0284c7);border-color:#38bdf8;color:#03131f;font-weight:700}
.btn.primary:hover{filter:brightness(1.08)}
.btn.ghost{background:transparent}
.btn.tiny{padding:2px 7px;font-size:11px;border-radius:5px}
aside{background:var(--panel);overflow-y:auto;padding:12px}
#left{border-right:1px solid var(--line)}
#right{border-left:1px solid var(--line)}
#view{position:relative;overflow:hidden}
canvas{display:block;width:100%;height:100%}
section{margin-bottom:14px}
h2{
font-size:11px;text-transform:uppercase;letter-spacing:1.1px;color:var(--dim);
margin:0 0 8px;display:flex;align-items:center;gap:8px;
}
h2:after{content:"";flex:1;height:1px;background:var(--line)}
.row{display:flex;gap:6px;flex-wrap:wrap;align-items:center}
.chip{
background:#16202f;border:1px solid #26344c;color:#cfe0f2;border-radius:999px;
padding:4px 9px;font-size:11.5px;cursor:pointer;user-select:none;transition:.12s;
}
.chip:hover{border-color:#3d5party}
.chip:hover{border-color:#3d5b8a;background:#1b2940}
.chip.on{background:rgba(56,189,248,.16);border-color:var(--accent);color:#eaf6ff}
.obj{
display:flex;align-items:center;gap:8px;padding:6px 8px;border:1px solid transparent;
border-radius:8px;cursor:pointer;margin-bottom:3px;
}
.obj:hover{background:#16202f}
.obj.focus{background:rgba(56,189,248,.09);border-color:#24456b}
.obj .dot{width:10px;height:10px;border-radius:3px;flex:none}
.obj .nm{flex:1}
.obj .meta{color:var(--dim);font-size:11px}
.obj .badge{font-size:11px;width:16px;text-align:center}
label.small{display:block;color:var(--dim);font-size:11px;margin:7px 0 3px}
input[type=number]{
width:56px;background:#0b1220;border:1px solid #26344c;color:var(--txt);
border-radius:5px;padding:3px 5px;font:inherit;font-size:11.5px;
}
input[type=range]{width:100%;accent-color:var(--accent)}
.field{display:flex;align-items:center;gap:5px;margin-bottom:5px;flex-wrap:wrap}
.field span.lbl{color:var(--dim);width:70px;font-size:11px}
.switch{display:flex;align-items:center;gap:7px;color:#c6d4e4;font-size:11.5px;margin:4px 0;cursor:pointer}
.switch input{accent-color:var(--accent)}
table{border-collapse:collapse;width:100%;font-size:11px}
th,td{border-bottom:1px solid var(--line);padding:5px 4px;text-align:left;vertical-align:top}
th{color:var(--dim);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.5px}
td.ok{color:var(--good)} td.no{color:var(--bad)} td.mid{color:var(--warn)}
.stackitem{
display:flex;gap:6px;align-items:center;background:#141d2c;border:1px solid #22304a;
border-radius:6px;padding:4px 6px;margin-bottom:4px;font-size:11.5px;
}
.stackitem .sw{width:9px;height:9px;border-radius:2px;flex:none}
.stackitem .lb{flex:1;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.hint{color:var(--dim);font-size:11px;line-height:1.5}
.logitem{border-left:2px solid #2b3d5c;padding:2px 0 2px 8px;margin-bottom:5px;font-size:11.5px}
.logitem.ok{border-left-color:var(--good)} .logitem.no{border-left-color:var(--bad)}
.k{color:var(--dim)}
#hud{
position:absolute;left:12px;bottom:12px;background:rgba(9,14,23,.82);
border:1px solid var(--line);border-radius:9px;padding:8px 11px;max-width:60%;
backdrop-filter:blur(6px);font-size:12px;
}
#hud .op{color:var(--accent);font-weight:600}
#hud .pv{color:var(--dim);font-size:11px;margin-top:2px}
#tip{position:absolute;right:12px;bottom:12px;color:var(--dim);font-size:11px;text-align:right}
.badge-ok{color:var(--good)} .badge-no{color:var(--bad)}
.pill{display:inline-block;padding:1px 6px;border-radius:999px;font-size:10.5px;border:1px solid}
.pill.ok{color:var(--good);border-color:rgba(52,211,153,.4);background:rgba(52,211,153,.1)}
.pill.no{color:var(--bad);border-color:rgba(251,113,133,.4);background:rgba(251,113,133,.1)}
details{background:#0e1622;border:1px solid var(--line);border-radius:8px;padding:8px}
summary{cursor:pointer;color:var(--dim);font-size:11.5px}
@media(max-width:1100px){#app{grid-template-columns:260px 1fr 280px}}
</style>
</head>
<body>
<div id="app">
<header>
<h1>Symmetry Operation Explorer</h1>
<span class="sub">reflection planes & rotation axes · overlay transformed copies · verify vertex/edge/face correspondence</span>
<span class="spacer"></span>
<button class="btn ghost" id="btnVerify">Verify correspondence</button>
<button class="btn ghost" id="btnTop">Top view</button>
<button class="btn ghost" id="btnReset">Reset view</button>
</header>
<aside id="left">
<section>
<h2>Objects</h2>
<div id="objList"></div>
<div class="hint" style="margin-top:6px">Tick a solid to place it in the scene. The same operation is applied to every enabled solid, so you can compare which ones actually admit it.</div>
</section>
<section>
<h2>Operation</h2>
<div class="row" style="margin-bottom:8px">
<span class="chip on" data-optype="reflect">Reflection (mirror plane)</span>
<span class="chip" data-optype="rotate">Rotation (axis + angle)</span>
</div>
<div id="reflectUI">
<label class="small">Plane normal presets</label>
<div class="row" id="normPresets"></div>
<label class="small">Normal (x, y, z) — plane passes through n·p = d</label>
<div class="field">
<span class="lbl">normal</span>
<input type="number" id="nx" value="1" step="0.5"><input type="number" id="ny" value="0" step="0.5"><input type="number" id="nz" value="0" step="0.5">
</div>
<div class="field">
<span class="lbl">offset d</span>
<input type="number" id="nd" value="0" step="0.25">
<span class="k">(0 = plane through the solid's centre)</span>
</div>
</div>
<div id="rotateUI" style="display:none">
<label class="small">Axis presets</label>
<div class="row" id="axisPresets"></div>
<label class="small">Axis (x, y, z)</label>
<div class="field">
<span class="lbl">axis</span>
<input type="number" id="ax" value="0" step="0.5"><input type="number" id="ay" value="1" step="0.5"><input type="number" id="az" value="0" step="0.5">
</div>
<label class="small">Angle</label>
<input type="range" id="angle" min="0" max="360" step="1" value="90">
<div class="field">
<span class="lbl">angle</span>
<input type="number" id="anglenum" value="90" step="5" min="0" max="360">
<span class="chip" data-angle="90">90°</span><span class="chip" data-angle="120">120°</span>
<span class="chip" data-angle="180">180°</span><span class="chip" data-angle="240">240°</span><span class="chip" data-angle="270">270°</span>
</div>
<label class="switch"><input type="checkbox" id="snap"> snap angle to 15° multiples</label>
</div>
<div class="row" style="margin-top:10px">
<button class="btn" id="btnAdd">Add to overlay stack</button>
<button class="btn" id="btnCompose">Compose with top</button>
</div>
<div class="hint" style="margin-top:5px">“Compose with top” applies the current operation <i>after</i> the top entry of the stack and stores the product.</div>
</section>
<section>
<h2>Overlay</h2>
<div class="field"><span class="lbl">opacity</span><input type="range" id="opacity" min="10" max="90" value="34"></div>
<div class="field"><span class="lbl">explode</span><input type="range" id="explode" min="0" max="100" value="45"></div>
<label class="switch"><input type="checkbox" id="showGhost" checked> show transformed copy</label>
<label class="switch"><input type="checkbox" id="showCorr" checked> show correspondence lines</label>
<label class="switch"><input type="checkbox" id="showPlane" checked> show plane / axis visual</label>
<label class="switch"><input type="checkbox" id="showStack" checked> show stacked ghosts</label>
</section>
<section>
<h2>Stack</h2>
<div id="stackList"></div>
<button class="btn tiny" id="btnClearStack">clear stack</button>
</section>
</aside>
<div id="view">
<canvas id="c"></canvas>
<div id="hud"><div class="op">—</div><div class="pv"></div></div>
<div id="tip">drag = orbit · wheel = zoom · shift/right-drag = pan · V = verify · R = reset</div>
</div>
<aside id="right">
<section>
<h2>Verification report</h2>
<div id="report"><div class="hint">Press <b>Verify correspondence</b> to test the current operation against every enabled solid.</div></div>
</section>
<section>
<h2>Confirmed symmetries</h2>
<div id="ledger"><div class="hint">No operations confirmed yet.</div></div>
</section>
<section>
<h2>History</h2>
<div id="log"><div class="hint">—</div></div>
</section>
<section>
<details>
<summary>How the verification works</summary>
<div class="hint" style="margin-top:7px">
1. The operation matrix <i>M</i> is applied to every vertex of the solid.<br>
2. All (transformed → original) pairs within tolerance are sorted by distance and greedily matched; a match is accepted only if it is <b>bijective</b>.<br>
3. The induced vertex permutation is used to re-map every edge and every face; each image must already exist in the original incidence structure.<br>
4. <i>det(M)</i> reports proper (+1) vs. improper (−1, a mirror) transformations.<br>
5. Only if vertices, edges <i>and</i> faces all correspond is the operation accepted as a symmetry. Appearance alone never counts.
</div>
</details>
</section>
</aside>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ─────────────────────────── geometry data ─────────────────────────── */
const S = 0.72; // cube scale
const CUBE_V = [[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]].map(v=>v.map(c=>c*S));
const BOX_D = [1.5,0.8,1.1];
const BOX_V = [[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]]
.map(v=>v.map((c,i)=>c*BOX_D[i]/2));
const TET_V = [[1,1,1],[1,-1,-1],[-1,1,-1],[-1,-1,1]].map(v=>v.map(c=>c*0.55));
const OCT_V = [[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]].map(v=>v.map(c=>c*0.92));
const PRISM_V = [
[0,0.9,-0.7],[-0.78,-0.45,-0.7],[0.78,-0.45,-0.7],
[0,0.9,0.7],[-0.78,-0.45,0.7],[0.78,-0.45,0.7]];
const HEX_V = [];
for(let i=0;i<6;i++){const a=Math.PI/6*i+(Math.PI/6);HEX_V.push([0.8*Math.cos(a),0.8*Math.sin(a),-0.55]);}
for(let i=0;i<6;i++){const a=Math.PI/6*i+(Math.PI/6);HEX_V.push([0.8*Math.cos(a),0.8*Math.sin(a), 0.55]);}
const PHI=(1+Math.sqrt(5))/2;
const ICO_V=[[-1,PHI,0],[1,PHI,0],[-1,-PHI,0],[1,-PHI,0],[0,-1,PHI],[0,1,PHI],[0,-1,-PHI],[0,1,-PHI],
[PHI,0,-1],[PHI,0,1],[-PHI,0,-1],[-PHI,0,1]].map(v=>v.map(c=>c*0.45));
const TW_V=[];
for(let i=0;i<3;i++){const a=Math.PI/2+2*Math.PI*i/3;TW_V.push([0.85*Math.cos(a),0.85*Math.sin(a),-0.6]);}
for(let i=0;i<3;i++){const a=Math.PI/2+2*Math.PI*i/3+Math.PI/6;TW_V.push([0.85*Math.cos(a),0.85*Math.sin(a),0.6]);}
const OBJECTS = [
{id:'cube', name:'Cube', color:0x7aa2ff, verts:CUBE_V,
faces:[[0,3,2,1],[4,5,6,7],[0,1,5,4],[3,7,6,2],[0,4,7,3],[1,2,6,5]]},
{id:'box', name:'Rectangular box', color:0xffb86b, verts:BOX_V,
faces:[[0,3,2,1],[4,5,6,7],[0,1,5,4],[3,7,6,2],[0,4,7,3],[1,2,6,5]]},
{id:'tet', name:'Regular tetrahedron', color:0x6ee7a8, verts:TET_V,
faces:[[0,1,2],[0,3,1],[0,2,3],[1,3,2]]},
{id:'oct', name:'Regular octahedron', color:0xf472b6, verts:OCT_V,
faces:[[0,2,4],[0,4,3],[0,3,5],[0,5,2],[1,2,5],[1,5,3],[1,3,4],[1,4,2]]},
{id:'prism', name:'Triangular prism', color:0xfacc15, verts:PRISM_V,
faces:[[0,1,2],[3,4,5],[0,1,4,3],[1,2,5,4],[2,0,3,5]]},
{id:'hex', name:'Hexagonal prism', color:0x38bdf8, verts:HEX_V,
faces:[[0,1,2,3,4,5],[6,7,8,9,10,11],[0,1,7,6],[1,2,8,7],[2,3,9,8],[3,4,10,9],[4,5,11,10],[5,0,6,11]]},
{id:'twist', name:'Twisted prism (chiral)', color:0xc084fc, verts:TW_V,
faces:[[0,1,2],[3,4,5],[0,1,4,3],[1,2,5,4],[2,0,3,5]]},
{id:'ico', name:'Icosahedron', color:0x34d399, verts:ICO_V,
faces:[[0,11,5],[0,5,1],[0,1,7],[0,7,10],[0,10,11],[1,5,9],[5,11,4],[11,10,2],[10,7,6],[7,1,8],
[3,9,4],[3,4,2],[3,2,6],[3,6,8],[3,8,9],[4,9,5],[2,4,11],[6,2,10],[8,6,7],[9,8,1]]}
];
const OBJ = Object.fromEntries(OBJECTS.map(o=>{
const edges=[]; const ek=new Set();
o.faces.forEach(f=>{for(let i=0;i<f.length;i++){const a=f[i],b=f[(i+1)%f.length];const k=Math.min(a,b)+','+Math.max(a,b);if(!ek.has(k)){ek.add(k);edges.push([a,b]);}}});
const fk=new Set(o.faces.map(f=>f.slice().sort((x,y)=>x-y).join(',')));
const r=Math.max(...o.verts.map(v=>Math.hypot(v[0],v[1],v[2])));
o.edges=edges; o.faceKeys=fk; o.radius=r;
return [o.id,o];
}));
/* ─────────────────────────── state ─────────────────────────── */
const state = {
enabled:new Set(['cube','tet','oct']),
focused:'cube',
opType:'reflect',
stack:[],
last:null,
ledger:{}, // objId -> [{label,params}]
log:[],
showGhost:true, showCorr:true, showPlane:true, showStack:true,
opacity:0.34, explode:0.45
};
/* ─────────────────────────── renderer / scene ─────────────────────────── */
const canvas=document.getElementById('c');
const renderer=new THREE.WebGLRenderer({canvas,antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio,2));
const scene=new THREE.Scene();
scene.background=new THREE.Color(0x0a0e16);
const camera=new THREE.PerspectiveCamera(45,1,0.1,200);
scene.add(new THREE.AmbientLight(0xffffff,0.5));
const d1=new THREE.DirectionalLight(0xffffff,0.95);d1.position.set(5,8,6);scene.add(d1);
const d2=new THREE.DirectionalLight(0x88bbff,0.35);d2.position.set(-6,3,-5);scene.add(d2);
const grid=new THREE.GridHelper(40,40,0x22314a,0x141d2c);grid.position.y=-2.1;scene.add(grid);
const world=new THREE.Group();scene.add(world);
/* axis gizmo */
function axisLines(){
const g=new THREE.Group();
const mk=(a,b,col)=>{const p=new Float32Array([...a,...b]);const geo=new THREE.BufferGeometry();geo.setAttribute('position',new THREE.BufferAttribute(p,3));
const ln=new THREE.Line(geo,new THREE.LineBasicMaterial({color:col}));g.add(ln);};
mk([0,0,0],[2.4,0,0],0xff6b6b);mk([0,0,0],[0,2.4,0],0x4ade80);mk([0,0,0],[0,0,2.4],0x60a5fa);
g.add(sprite('X',0xff6b6b,[2.55,0,0]),sprite('Y',0x4ade80,[0,2.55,0]),sprite('Z',0x60a5fa,[0,0,2.55]));
return g;
}
function sprite(txt,col,pos){
const c=document.createElement('canvas');c.width=c.height=64;const x=c.getContext('2d');
x.fillStyle='#'+col.toString(16).padStart(6,'0');x.font='bold 40px sans-serif';x.textAlign='center';x.textBaseline='middle';x.fillText(txt,32,34);
const tex=new THREE.CanvasTexture(c);
const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:tex,transparent:true,depthTest:false}));
sp.scale.setScalar(0.42);sp.position.set(...pos);return sp;
}
world.add(axisLines());
/* ─────────────────────────── camera controls (implemented here) ─────────────────────────── */
const cam={theta:0.85,phi:1.05,radius:9.5,target:new THREE.Vector3(0,0,0),
tTheta:0.85,tPhi:1.05,tRadius:9.5,tTarget:new THREE.Vector3(0,0,0)};
let dragging=0,px=0,py=0;
canvas.addEventListener('contextmenu',e=>e.preventDefault());
canvas.addEventListener('pointerdown',e=>{dragging=(e.button===2||e.shiftKey)?2:1;px=e.clientX;py=e.clientY;canvas.setPointerCapture(e.pointerId);});
canvas.addEventListener('pointerup',e=>{dragging=0;});
canvas.addEventListener('pointermove',e=>{
if(!dragging)return;const dx=e.clientX-px,dy=e.clientY-py;px=e.clientX;py=e.clientY;
if(dragging===1){cam.tTheta-=dx*0.006;cam.tPhi=Math.max(0.05,Math.min(Math.PI-0.05,cam.tPhi-dy*0.006));}
else{
const right=new THREE.Vector3().setFromMatrixColumn(camera.matrix,0);
const up=new THREE.Vector3().setFromMatrixColumn(camera.matrix,1);
const k=cam.tRadius*0.0014;
cam.tTarget.addScaledVector(right,-dx*k).addScaledVector(up,dy*k);
}
});
canvas.addEventListener('wheel',e=>{e.preventDefault();cam.tRadius=Math.max(2.5,Math.min(45,cam.tRadius*(1+e.deltaY*0.0012)));},{passive:false});
function resetCam(){cam.tTheta=0.85;cam.tPhi=1.05;cam.tRadius=9.5;cam.tTarget.set(0,0,0);}
document.getElementById('btnReset').onclick=resetCam;
document.getElementById('btnTop').onclick=()=>{cam.tPhi=0.06;cam.tTheta=0;};
addEventListener('keydown',e=>{
if(e.target.tagName==='INPUT')return;
const k=e.key.toLowerCase();
if(k==='v')verify(); if(k==='r')resetCam();
if(k==='g'){state.showGhost=!state.showGhost;document.getElementById('showGhost').checked=state.showGhost;rebuild();}
});
function resize(){const r=document.getElementById('view').getBoundingClientRect();
renderer.setSize(r.width,r.height,false);camera.aspect=r.width/r.height;camera.updateProjectionMatrix();}
addEventListener('resize',resize);
/* ─────────────────────────── operations ─────────────────────────── */
const NORMALS=[
['X',[1,0,0]],['Y',[0,1,0]],['Z',[0,0,1]],
['X=Y',[1,1,0]],['X=−Y',[1,-1,0]],['Y=Z',[0,1,1]],['Y=−Z',[0,1,-1]],
['X=Z',[1,0,1]],['X=−Z',[1,0,-1]],['body diag',[1,1,1]]];
const AXES=[['X',[1,0,0]],['Y',[0,1,0]],['Z',[0,0,1]],
['body diag',[1,1,1]],['edge diag',[1,1,0]],['X+Z',[1,0,1]],['Y+Z',[0,1,1]]];
function norm3(v){const l=Math.hypot(v[0],v[1],v[2])||1;return [v[0]/l,v[1]/l,v[2]/l];}
function reflectParams(){
const n=norm3([+val('nx'),+val('ny'),+val('nz')]);
return {type:'reflect',normal:n,offset:+val('nd')};
}
function rotateParams(){
let a=norm3([+val('ax'),+val('ay'),+val('az')]);
let ang=+val('anglenum');
if(document.getElementById('snap').checked)ang=Math.round(ang/15)*15;
if(ang>=360)ang-=360;
return {type:'rotate',axis:a,angle:ang};
}
const val=id=>document.getElementById(id).value;
function opMatrix(p){
if(p.type==='reflect'){
const n=p.normal,d=p.offset||0;
const m=new THREE.Matrix4();
m.set(
1-2*n[0]*n[0], -2*n[0]*n[1], -2*n[0]*n[2], 2*d*n[0],
-2*n[1]*n[0], 1-2*n[1]*n[1], -2*n[1]*n[2], 2*d*n[1],
-2*n[2]*n[0], -2*n[2]*n[1], 1-2*n[2]*n[2], 2*d*n[2],
0,0,0,1);
return m;
}
const m=new THREE.Matrix4();
m.makeRotationAxis(new THREE.Vector3(...p.axis),THREE.MathUtils.degToRad(p.angle));
return m;
}
function opLabel(p){
if(p.type==='reflect'){
const n=p.normal.map(c=>Math.abs(c)<1e-6?0:+(c).toFixed(3));
return `mirror in plane n=(${n.join(', ')}), d=${+(p.offset||0).toFixed(3)}`;
}
const a=p.axis.map(c=>Math.abs(c)<1e-6?0:+(c).toFixed(3));
return `rotation ${+(p.angle).toFixed(1)}° about (${a.join(', ')})`;
}
function det3(m){
const e=m.elements;
return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5]);
}
function apply(m,v){const t=new THREE.Vector3(v[0],v[1],v[2]).applyMatrix4(m);return [t.x,t.y,t.z];}
/* ─────────────────────────── verification ─────────────────────────── */
const TOL=1e-3;
function verifyObject(obj,M){
const n=obj.verts.length;
const T=obj.verts.map(v=>apply(M,v));
const cand=[];
for(let i=0;i<n;i++)for(let j=0;j<n;j++){
const d=Math.hypot(T[i][0]-obj.verts[j][0],T[i][1]-obj.verts[j][1],T[i][2]-obj.verts[j][2]);
if(d<TOL)cand.push({i,j,d});
}
cand.sort((a,b)=>a.d-b.d);
const mapT=new Array(n).fill(-1),mapO=new Array(n).fill(-1);
for(const c of cand){if(mapT[c.i]<0&&mapO[c.j]<0){mapT[c.i]=c.j;mapO[c.j]=c.i;}}
const matched=mapT.filter(x=>x>=0).length;
const bijective=matched===n;
let edgesOK=0,facesOK=0;
const edgeSet=new Set(obj.edges.map(e=>Math.min(e[0],e[1])+','+Math.max(e[0],e[1])));
obj.edges.forEach(e=>{
const a=mapT[e[0]],b=mapT[e[1]];
if(a<0||b<0)return;
if(edgeSet.has(Math.min(a,b)+','+Math.max(a,b)))edgesOK++;
});
obj.faces.forEach(f=>{
if(f.some(i=>mapT[i]<0))return;
const k=f.map(i=>mapT[i]).sort((x,y)=>x-y).join(',');
if(obj.faceKeys.has(k))facesOK++;
});
const unmatched=[];
for(let i=0;i<n;i++)if(mapT[i]<0){
let best=Infinity;
for(let j=0;j<n;j++)best=Math.min(best,Math.hypot(T[i][0]-obj.verts[j][0],T[i][1]-obj.verts[j][1],T[i][2]-obj.verts[j][2]));
unmatched.push({i,gap:+best.toFixed(3)});
}
const det=det3(M);
const isSym=bijective&&edgesOK===obj.edges.length&&facesOK===obj.faces.length;
const reasons=[];
if(!bijective)reasons.push(`${n-matched} of ${n} transformed vertices have no partner (nearest gap ${unmatched[0]?unmatched[0].gap:'?'})`);
if(edgesOK!==obj.edges.length)reasons.push(`${obj.edges.length-edgesOK}/${obj.edges.length} edges broken`);
if(facesOK!==obj.faces.length)reasons.push(`${obj.faces.length-facesOK}/${obj.faces.length} faces broken`);
const perm=mapT.map((j,i)=>j>=0?`${i}→${j}`:null).filter(Boolean);
return {objId:obj.id,name:obj.name,matched,total:n,bijective,
edgesOK,edgesTotal:obj.edges.length,facesOK,facesTotal:obj.faces.length,
det:+det.toFixed(6),proper:det>0,isSym,reasons,perm,unmatched};
}
/* ─────────────────────────── scene building ─────────────────────────── */
function solidGeom(obj){
const tris=[];obj.faces.forEach(f=>{for(let i=1;i<f.length-1;i++)tris.push(f[0],f[i],f[i+1]);});
const g=new THREE.BufferGeometry();
g.setAttribute('position',new THREE.Float32BufferAttribute(obj.verts.flat(),3));
g.setIndex(tris);g.computeVertexNormals();return g;
}
function edgeGeom(obj,transform){
const p=[];
obj.edges.forEach(e=>{const a=transform?transform(obj.verts[e[0]]):obj.verts[e[0]];
const b=transform?transform(obj.verts[e[1]]):obj.verts[e[1]];
p.push(...a,...b);});
const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(p,3));return g;
}
function disposeObj(o){o.traverse(c=>{if(c.geometry)c.geometry.dispose();if(c.material){(Array.isArray(c.material)?c.material:[c.material]).forEach(m=>m.dispose());}});}
function clearWorld(){while(world.children.length>1){const c=world.children.pop();disposeObj(c);}}
function slots(){
const ids=[...state.enabled];const cols=Math.min(ids.length,3)||1;
const rows=Math.ceil(ids.length/cols);const sp=3.4;const out=[];
ids.forEach((id,i)=>{const c=i%cols,r=Math.floor(i/cols);
out.push({id,pos:new THREE.Vector3((c-(cols-1)/2)*sp,0,(r-(rows-1)/2)*sp)});});
return out;
}
const STACK_COLORS=[0xff9f43,0x9b8cff,0x2dd4bf,0xf472b6,0xfacc15];
function rebuild(){
clearWorld();
const M=opMatrix(currentParams());
const slotsArr=slots();
const ex=state.explode;
slotsArr.forEach((s,idx)=>{
const obj=OBJ[s.id];const g=new THREE.Group();g.position.copy(s.pos);
const focused=obj.id===state.focused;
const mat=new THREE.MeshPhongMaterial({color:obj.color,flatShading:true,shininess:24,side:THREE.DoubleSide,
transparent:true,opacity:focused?1:0.42});
g.add(new THREE.Mesh(solidGeom(obj),mat));
g.add(new THREE.LineSegments(edgeGeom(obj),new THREE.LineBasicMaterial({color:0x0a0e16,transparent:true,opacity:0.75})));
// live transformed copy
if(state.showGhost){
const tw=v=>apply(M,v);
g.add(new THREE.LineSegments(edgeGeom(obj,tw),new THREE.LineBasicMaterial({color:0x38bdf8,transparent:true,opacity:0.95})));
// displaced (exploded) solid for correspondence reading
const disp=obj.verts.map(v=>{const t=apply(M,v);const r=Math.hypot(t[0],t[1],t[2])||1;
const k=ex*0.9*obj.radius/r;return [t[0]+t[0]*k,t[1]+t[1]*k,t[2]+t[2]*k];});
const gp=solidGeom(obj);
gp.setAttribute('position',new THREE.Float32BufferAttribute(disp.flat(),3));gp.computeVertexNormals();
g.add(new THREE.Mesh(gp,new THREE.MeshPhongMaterial({color:0x38bdf8,flatShading:true,transparent:true,
opacity:state.opacity,side:THREE.DoubleSide,depthWrite:false})));
g.add(new THREE.LineSegments(edgeGeom(obj,v=>disp[v.length?0:0]),new THREE.LineBasicMaterial())); // placeholder removed below
g.children.pop();
// correspondence lines + points
if(state.showCorr){
const res=verifyObject(obj,M);
const seg=[],cols=[];
res.perm.forEach(s=>{const i=+s.split('→')[0];const seg2=[...obj.verts[i],...disp[i]];seg.push(...seg2);cols.push(0.34,0.85,0.60);});
const lg=new THREE.BufferGeometry();lg.setAttribute('position',new THREE.Float32BufferAttribute(seg,3));
g.add(new THREE.LineSegments(lg,new THREE.LineBasicMaterial({vertexColors:true,transparent:true,opacity:0.95})));
const pg=new THREE.BufferGeometry();pg.setAttribute('position',new THREE.Float32BufferAttribute(disp.flat(),3));
const cc=[];disp.forEach((_,i)=>{const ok=res.perm.some(s=>+s.split('→')[0]===i);
cc.push(ok?0.21:0.98,ok?0.85:0.45,ok?0.60:0.55);});
pg.setAttribute('color',new THREE.Float32BufferAttribute(cc,3));
g.add(new THREE.Points(pg,new THREE.PointsMaterial({size:0.13,vertexColors:true,sizeAttenuation:true})));
}
}
// stacked ghosts
if(state.showStack){
state.stack.forEach((st,i)=>{
const tw=v=>apply(st.M,v);
g.add(new THREE.LineSegments(edgeGeom(obj,tw),new THREE.LineBasicMaterial({
color:STACK_COLORS[i%STACK_COLORS.length],transparent:true,opacity:0.55})));
});
}
// plane / axis visual
if(state.showPlane){
const p=currentParams();
if(p.type==='reflect'){
const n=new THREE.Vector3(...p.normal);
const pg=new THREE.PlaneGeometry(2.9,2.9);
const mesh=new THREE.Mesh(pg,new THREE.MeshBasicMaterial({color:0x38bdf8,transparent:true,opacity:0.10,
side:THREE.DoubleSide,depthWrite:false}));
mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0,0,1),n);
mesh.position.copy(n).multiplyScalar(p.offset||0);
g.add(mesh);
const bl=new THREE.LineSegments(new THREE.EdgesGeometry(pg),new THREE.LineBasicMaterial({color:0x38bdf8,transparent:true,opacity:0.5}));
bl.quaternion.copy(mesh.quaternion);bl.position.copy(mesh.position);g.add(bl);
}else{
const a=new THREE.Vector3(...p.axis),r=obj.radius*1.35;
const lg=new THREE.BufferGeometry().setFromPoints([a.clone().multiplyScalar(-r),a.clone().multiplyScalar(r)]);
g.add(new THREE.Line(lg,new THREE.LineBasicMaterial({color:0x38bdf8,transparent:true,opacity:0.8})));
const u=new THREE.Vector3(0,1,0);if(Math.abs(a.dot(u))>0.9)u.set(1,0,0);
const U=new THREE.Vector3().crossVectors(a,u).normalize(),V=new THREE.Vector3().crossVectors(a,U).normalize();
const pts=[],R=r*0.62,th=THREE.MathUtils.degToRad(p.angle);
for(let i=0;i<=48;i++){const t=th*i/48;
pts.push(U.clone().multiplyScalar(Math.cos(t)*R).addScaledVector(V,Math.sin(t)*R));}
g.add(new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts),
new THREE.LineBasicMaterial({color:0x38bdf8,transparent:true,opacity:0.9})));
g.add(new THREE.Mesh(new THREE.SphereGeometry(0.07,10,8),new THREE.MeshBasicMaterial({color:0x38bdf8})));
}
}
world.add(g);
});
}
/* ─────────────────────────── UI ─────────────────────────── */
function currentParams(){return state.opType==='reflect'?reflectParams():rotateParams();}
const objList=document.getElementById('objList');
function buildObjList(){
objList.innerHTML='';
OBJECTS.forEach(o=>{
const d=document.createElement('div');
d.className='obj'+(o.id===state.focused?' focus':'');
const cb=document.createElement('input');cb.type='checkbox';cb.checked=state.enabled.has(o.id);
cb.onchange=()=>{cb.checked?state.enabled.add(o.id):state.enabled.delete(o.id);
if(!state.enabled.size&&cb.checked)cb.checked=true;rebuild();};
const dot=document.createElement('span');dot.className='dot';dot.style.background='#'+o.color.toString(16).padStart(6,'0');
const nm=document.createElement('span');nm.className='nm';nm.textContent=o.name;
const meta=document.createElement('span');meta.className='meta';meta.textContent=`${o.verts.length}v/${o.faces.length}f`;
const badge=document.createElement('span');badge.className='badge';badge.id='bdg_'+o.id;
d.onclick=e=>{if(e.target!==cb){state.focused=o.id;buildObjList();rebuild();}};
d.append(cb,dot,nm,meta,badge);objList.appendChild(d);
});
}
const normBox=document.getElementById('normPresets');
NORMALS.forEach(([lab,n])=>{const c=document.createElement('span');c.className='chip';c.textContent=lab;
c.onclick=()=>{setOpType('reflect');document.getElementById('nx').value=n[0];document.getElementById('ny').value=n[1];
document.getElementById('nz').value=n[2];rebuild();};normBox.appendChild(c);});
const axisBox=document.getElementById('axisPresets');
AXES.forEach(([lab,n])=>{const c=document.createElement('span');c.className='chip';c.textContent=lab;
c.onclick=()=>{setOpType('rotate');document.getElementById('ax').value=n[0];document.getElementById('ay').value=n[1];
document.getElementById('az').value=n[2];rebuild();};axisBox.appendChild(c);});
function setOpType(t){
state.opType=t;
document.querySelectorAll('[data-optype]').forEach(c=>c.classList.toggle('on',c.dataset.optype===t));
document.getElementById('reflectUI').style.display=t==='reflect'?'':'none';
document.getElementById('rotateUI').style.display=t==='rotate'?'':'none';
}
document.querySelectorAll('[data-optype]').forEach(c=>c.onclick=()=>{setOpType(c.dataset.optype);rebuild();});
document.querySelectorAll('[data-angle]').forEach(c=>c.onclick=()=>{setOpType('rotate');
document.getElementById('angle').value=c.dataset.angle;document.getElementById('anglenum').value=c.dataset.angle;rebuild();});
['nx','ny','nz','nd','ax','ay','az','anglenum'].forEach(id=>{
document.getElementById(id).addEventListener('input',()=>{if(id==='anglenum')document.getElementById('angle').value=+val('anglenum');rebuild();});});
document.getElementById('angle').addEventListener('input',()=>{
document.getElementById('anglenum').value=document.getElementById('angle').value;rebuild();});
document.getElementById('snap').addEventListener('change',rebuild);
document.getElementById('opacity').addEventListener('input',e=>{state.opacity=+e.target.value/100;rebuild();});
document.getElementById('explode').addEventListener('input',e=>{state.explode=+e.target.value/100;rebuild();});
[['showGhost','showGhost'],['showCorr','showCorr'],['showPlane','showPlane'],['showStack','showStack']].forEach(([id,k])=>{
document.getElementById(id).addEventListener('change',e=>{state[k]=e.target.checked;rebuild();});});
/* stack */
function buildStack(){
const box=document.getElementById('stackList');box.innerHTML='';
if(!state.stack.length){box.innerHTML='<div class="hint">empty</div>';return;}
state.stack.forEach((st,i)=>{
const d=document.createElement('div');d.className='stackitem';
const sw=document.createElement('span');sw.className='sw';sw.style.background='#'+STACK_COLORS[i%STACK_COLORS.length].toString(16).padStart(6,'0');
const lb=document.createElement('span');lb.className='lb';lb.textContent=st.label;lb.title=st.label;
lb.onclick=()=>{restoreParams(st.params);rebuild();};
const rm=document.createElement('button');rm.className='btn tiny';rm.textContent='×';
rm.onclick=()=>{state.stack.splice(i,1);buildStack();rebuild();};
d.append(sw,lb,rm);box.appendChild(d);
});
}
function restoreParams(p){
setOpType(p.type);
if(p.type==='reflect'){document.getElementById('nx').value=p.normal[0];document.getElementById('ny').value=p.normal[1];
document.getElementById('nz').value=p.normal[2];document.getElementById('nd').value=p.offset||0;}
else{document.getElementById('ax').value=p.axis[0];document.getElementById('ay').value=p.axis[1];
document.getElementById('az').value=p.axis[2];document.getElementById('angle').value=p.angle;
document.getElementById('anglenum').value=p.angle;}
}
document.getElementById('btnAdd').onclick=()=>{
const p=currentParams();state.stack.push({label:opLabel(p),params:JSON.parse(JSON.stringify(p)),M:opMatrix(p)});
buildStack();rebuild();};
document.getElementById('btnCompose').onclick=()=>{
if(!state.stack.length)return;
const p=currentParams();const M=new THREE.Matrix4().multiplyMatrices(state.stack[state.stack.length-1].M,opMatrix(p));
state.stack.push({label:'('+state.stack[state.stack.length-1].label+') ∘ ('+opLabel(p)+')',
params:JSON.parse(JSON.stringify(p)),M});
buildStack();rebuild();};
document.getElementById('btnClearStack').onclick=()=>{state.stack=[];buildStack();rebuild();};
/* ─────────────────────────── verify + report ─────────────────────────── */
function verify(){
const p=currentParams(),M=opMatrix(p);
const ids=[...state.enabled];
const res=ids.map(id=>verifyObject(OBJ[id],M));
state.last={label:opLabel(p),params:JSON.parse(JSON.stringify(p)),res,det:det3(M)};
// badges
OBJECTS.forEach(o=>{const b=document.getElementById('bdg_'+o.id);if(!b)return;
const r=res.find(x=>x.objId===o.id);
if(!r){b.textContent='';b.className='badge';return;}
b.textContent=r.isSym?'✓':'✕';b.className='badge '+(r.isSym?'badge-ok':'badge-no');});
// ledger
res.forEach(r=>{
if(r.isSym){
state.ledger[r.objId]=state.ledger[r.objId]||[];
const lab=opLabel(p);
if(!state.ledger[r.objId].some(x=>x.label===lab))
state.ledger[r.objId].push({label:lab,params:JSON.parse(JSON.stringify(p))});
}
});
state.log.unshift({label:opLabel(p),ok:res.every(r=>r.isSym),partial:res.filter(r=>r.isSym).length+'/'+res.length});
if(state.log.length>40)state.log.pop();
renderReport();renderLedger();renderLog();
}
document.getElementById('btnVerify').onclick=verify;
function renderReport(){
const L=state.last,el=document.getElementById('report');
if(!L){el.innerHTML='<div class="hint">Press <b>Verify correspondence</b>.</div>';return;}
let h=`<div class="hint" style="margin-bottom:7px"><b>${L.label}</b><br>
determinant = ${L.det.toFixed(3)} → ${L.det>0?'proper (orientation preserving)':'improper (orientation reversing)'}</div>`;
h+='<table><thead><tr><th>Object</th><th>Vtx</th><th>Edges</th><th>Faces</th><th>Verdict</th></tr></thead><tbody>';
L.res.forEach(r=>{
const ok=r.isSym;
h+=`<tr><td>${r.name}</td>
<td class="${r.bijective?'ok':'no'}">${r.matched}/${r.total}</td>
<td class="${r.edgesOK===r.edgesTotal?'ok':'no'}">${r.edgesOK}/${r.edgesTotal}</td>
<td class="${r.facesOK===r.facesTotal?'ok':'no'}">${r.facesOK}/${r.facesTotal}</td>
<td class="${ok?'ok':'no'}">${ok?'symmetry':'not a symmetry'}</td></tr>`;
});
h+='</tbody></table>';
L.res.forEach(r=>{
h+=`<div style="margin-top:8px"><b>${r.name}</b> `;
h+=r.isSym?`<span class="pill ok">confirmed symmetry</span>`:`<span class="pill no">no correspondence</span>`;
h+=`<div class="hint" style="margin-top:3px">`;
if(r.isSym){
h+=`every transformed vertex coincides with exactly one original vertex, and the induced permutation preserves all ${r.edgesTotal} edges and all ${r.facesTotal} faces.<br>`;
h+=`<span class="k">permutation</span> ${r.perm.join(' ')}`;
}else{
if(r.reasons.length)h+=r.reasons.join('<br>')+'<br>';
if(r.unmatched.length)h+=`<span class="k">unmatched transformed vertices</span> ${r.unmatched.map(u=>'v'+u.i+' (gap '+u.gap+')').join(', ')}<br>`;
h+=`<span class="k">matched</span> ${r.perm.length?r.perm.join(' '):'none'}`;
}
h+=`</div></div>`;
});
el.innerHTML=h;
}
function renderLedger(){
const el=document.getElementById('ledger');const ids=Object.keys(state.ledger);
if(!ids.length){el.innerHTML='<div class="hint">No operations confirmed yet.</div>';return;}
let h='';
ids.forEach(id=>{
h+=`<div style="margin-bottom:7px"><b style="color:#'+OBJ[id].color.toString(16).padStart(6,'0')+'">${OBJ[id].name}</b><br>`;
state.ledger[id].forEach(e=>{
h+=`<span class="chip" style="margin:2px 3px 2px 0" title="click to reload">${e.label}</span>`;
});
h+='</div>';
});
el.innerHTML=h;
el.querySelectorAll('.chip').forEach((c,i)=>{ /* lazy lookup */ });
// attach handlers
const chips=el.querySelectorAll('.chip');let idx=0;
ids.forEach(id=>state.ledger[id].forEach(e=>{
const c=chips[idx++];
c.onclick=()=>{restoreParams(e.params);rebuild();};
}));
}
function renderLog(){
const el=document.getElementById('log');
if(!state.log.length){el.innerHTML='<div class="hint">—</div>';return;}
el.innerHTML=state.log.map((l,i)=>`<div class="logitem ${l.ok?'ok':'no'}"><b>${l.label}</b><br>
<span class="k">${l.ok?'confirmed for every enabled solid':l.partial+' enabled solid(s) confirmed'}</span></div>`).join('');
}
/* ─────────────────────────── HUD + loop ─────────────────────────── */
function updateHud(){
const p=currentParams();
document.querySelector('#hud .op').textContent=opLabel(p);
const pv=document.querySelector('#hud .pv');
const ids=[...state.enabled];
const M=opMatrix(p);
const res=ids.map(id=>verifyObject(OBJ[id],M));
const all=res.every(r=>r.isSym);
pv.innerHTML=`preview: ${res.map(r=>`${OBJ[r.objId].name.split(' ')[0]} ${r.matched}/${r.total}`).join(' · ')} — `+
(all?'<span style="color:#34d399">all coincide</span>':'<span style="color:#fbbf24">press Verify for the full report</span>');
}
function loop(){
requestAnimationFrame(loop);
cam.theta+=(cam.tTheta-cam.theta)*0.12;cam.phi+=(cam.tPhi-cam.phi)*0.12;cam.radius+=(cam.tRadius-cam.radius)*0.12;
cam.target.lerp(cam.tTarget,0.12);
camera.position.set(
cam.target.x+cam.radius*Math.sin(cam.phi)*Math.cos(cam.theta),
cam.target.y+cam.radius*Math.cos(cam.phi),
cam.target.z+cam.radius*Math.sin(cam.phi)*Math.sin(cam.theta));
camera.lookAt(cam.target);
renderer.render(scene,camera);
}
buildObjList();buildStack();rebuild();resize();loop();
</script>
</body>
</html>
```