Prompt specification
Build or customize the Three.js 3D scene "Overhang Orientation Puzzle" 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: Overhang Orientation Puzzle
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/overhang-orientation-puzzle-x2004
Scene Description Prompt:
Rotate a low-poly printable shape to compare unsupported regions under an explicit toy overhang rule. Three.js from cdnjs, one HTML file.
Working Three.js Starter (overhang-orientation-puzzle-x2004):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Overhang Lab — Low-Poly Toy Printer</title>
<style>
:root {
color-scheme: dark;
--bg: #0a1018;
--panel: #111a25;
--panel-2: #172332;
--line: #26384a;
--text: #e8f0f7;
--muted: #8da1b5;
--cyan: #73d4e8;
--coral: #ff607c;
--amber: #ffc857;
--green: #66dfad;
--radius: 14px;
}
* {
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input, label {
font: inherit;
}
button {
color: inherit;
}
.app {
width: 100%;
height: 100%;
display: grid;
grid-template-rows: 64px minmax(0, 1fr);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(12, 19, 28, 0.94);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 34px;
height: 34px;
flex: 0 0 auto;
border: 2px solid var(--cyan);
border-radius: 9px;
transform: rotate(45deg);
position: relative;
box-shadow: 0 0 20px rgba(115, 212, 232, 0.15);
}
.brand-mark::after {
content: "";
position: absolute;
inset: 7px;
background: var(--cyan);
border-radius: 3px;
}
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: 0.01em;
white-space: nowrap;
}
.brand p {
margin: 2px 0 0;
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
.header-badge {
border: 1px solid #345064;
background: rgba(115, 212, 232, 0.07);
color: #a8ddea;
border-radius: 999px;
padding: 7px 11px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.08em;
white-space: nowrap;
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 350px;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #0b131d;
}
#scene {
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
outline: none;
}
#scene.dragging {
cursor: grabbing;
}
.metric-badge {
position: absolute;
top: 16px;
left: 16px;
display: flex;
align-items: center;
gap: 12px;
padding: 10px 13px;
border: 1px solid rgba(125, 157, 180, 0.22);
border-radius: 12px;
background: rgba(10, 17, 26, 0.82);
backdrop-filter: blur(10px);
pointer-events: none;
}
.metric-badge .dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--coral);
box-shadow: 0 0 12px rgba(255, 96, 124, 0.55);
}
.metric-badge strong {
display: block;
font-size: 15px;
}
.metric-badge span {
display: block;
margin-top: 1px;
color: var(--muted);
font-size: 11px;
}
.mode-switch {
position: absolute;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
display: flex;
gap: 4px;
padding: 4px;
border: 1px solid rgba(125, 157, 180, 0.22);
border-radius: 11px;
background: rgba(10, 17, 26, 0.88);
backdrop-filter: blur(10px);
}
.mode-switch button {
border: 0;
border-radius: 8px;
padding: 8px 12px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 12px;
}
.mode-switch button.active {
color: #071018;
background: var(--cyan);
font-weight: 700;
}
.legend {
position: absolute;
right: 16px;
bottom: 17px;
display: flex;
gap: 13px;
padding: 9px 12px;
border: 1px solid rgba(125, 157, 180, 0.18);
border-radius: 10px;
background: rgba(10, 17, 26, 0.78);
color: var(--muted);
font-size: 11px;
pointer-events: none;
}
.legend span {
display: flex;
align-items: center;
gap: 5px;
}
.swatch {
width: 8px;
height: 8px;
border-radius: 2px;
}
.hint {
position: absolute;
left: 16px;
bottom: 18px;
color: var(--muted);
font-size: 11px;
pointer-events: none;
}
#compareLabels {
position: absolute;
inset: 0;
display: none;
pointer-events: none;
}
#viewport.comparing #compareLabels {
display: block;
}
.view-label {
position: absolute;
top: 16px;
padding: 6px 9px;
border-radius: 7px;
background: rgba(10, 17, 26, 0.78);
border: 1px solid rgba(125, 157, 180, 0.22);
color: #c8d8e5;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
.view-label.current {
left: 16px;
}
.view-label.reference {
left: calc(50% + 16px);
}
#viewport.stacked .view-label.reference {
left: 16px;
top: calc(50% + 16px);
}
.split-line {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
background: rgba(125, 157, 180, 0.28);
}
#viewport.stacked .split-line {
top: 50%;
bottom: auto;
left: 0;
width: 100%;
height: 1px;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 18px;
border-left: 1px solid var(--line);
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #33485d transparent;
}
.section {
padding-bottom: 18px;
margin-bottom: 18px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
margin-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
h2 {
margin: 0;
font-size: 13px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.section-note {
color: var(--muted);
font-size: 10px;
}
.sliders {
display: grid;
gap: 11px;
}
.slider-row {
display: grid;
grid-template-columns: 58px 1fr 43px;
align-items: center;
gap: 8px;
}
.slider-row label,
.slider-row output {
font-size: 11px;
color: var(--muted);
}
.slider-row output {
text-align: right;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.button-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin-top: 12px;
}
.button-grid.two {
grid-template-columns: repeat(2, 1fr);
}
.button-grid.three {
grid-template-columns: repeat(3, 1fr);
}
.btn {
border: 1px solid #304357;
border-radius: 9px;
background: #192635;
padding: 9px 10px;
cursor: pointer;
color: #dce8f2;
font-size: 11px;
transition: background 120ms, border-color 120ms, transform 120ms;
}
.btn:hover {
background: #223449;
border-color: #45627c;
}
.btn:active {
transform: translateY(1px);
}
.btn.primary {
border-color: #59b8cd;
background: var(--cyan);
color: #08131c;
font-weight: 800;
}
.btn.active {
border-color: var(--cyan);
color: var(--cyan);
background: rgba(115, 212, 232, 0.08);
}
.btn.subtle {
background: transparent;
}
.rule-card {
padding: 13px;
border: 1px solid #2c465a;
border-radius: var(--radius);
background: linear-gradient(145deg, #172635, #121c28);
}
.rule-card p {
margin: 0;
color: #b9c9d7;
font-size: 11px;
line-height: 1.55;
}
.rule-card strong {
color: var(--text);
}
.formula {
display: block;
margin-top: 9px;
padding: 8px 9px;
border-radius: 8px;
background: rgba(5, 11, 17, 0.48);
color: #a8ddea;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.comparison-card {
padding: 13px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--panel-2);
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-width: 0;
padding: 10px;
border-radius: 10px;
background: rgba(6, 12, 18, 0.34);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 5px;
color: var(--coral);
font-size: 22px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.metric.reference strong {
color: var(--cyan);
}
.metric small {
display: block;
margin-top: 6px;
color: var(--muted);
font-size: 10px;
}
.delta {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
}
.delta.good {
color: var(--green);
}
.delta.bad {
color: var(--coral);
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 12px;
color: var(--muted);
font-size: 11px;
}
.check-row label {
display: flex;
align-items: center;
gap: 7px;
cursor: pointer;
}
.check-row input {
accent-color: var(--cyan);
}
details {
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
summary {
color: #c3d2df;
cursor: pointer;
font-weight: 700;
}
details p {
margin: 10px 0 0;
}
.file-label {
display: block;
margin-top: 11px;
padding: 10px;
border: 1px dashed #3d566d;
border-radius: 9px;
color: #a9bdcc;
text-align: center;
cursor: pointer;
font-size: 11px;
}
.file-label:hover {
border-color: var(--cyan);
color: var(--cyan);
}
.file-label input {
display: none;
}
.footer-note {
margin-top: 10px;
color: #71869a;
font-size: 10px;
line-height: 1.45;
}
#toast {
position: fixed;
left: 50%;
top: 76px;
transform: translate(-50%, -12px);
z-index: 30;
padding: 10px 14px;
border: 1px solid #3c566b;
border-radius: 9px;
background: #142332;
color: #dceaf4;
font-size: 12px;
opacity: 0;
pointer-events: none;
transition: opacity 180ms, transform 180ms;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
html, body {
overflow: auto;
}
.app {
height: auto;
min-height: 100%;
grid-template-rows: 60px auto;
}
main {
grid-template-columns: 1fr;
}
#viewport {
height: 62vh;
min-height: 430px;
}
aside {
border-left: 0;
border-top: 1px solid var(--line);
overflow: visible;
}
.legend {
top: 16px;
bottom: auto;
}
.hint {
display: none;
}
}
@media (max-width: 520px) {
header {
padding: 0 14px;
}
.brand p,
.header-badge {
display: none;
}
aside {
padding: 14px;
}
.mode-switch {
bottom: 14px;
}
.legend {
right: 12px;
gap: 8px;
padding: 7px 9px;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Overhang Lab</h1>
<p>Rotate a low-poly toy and inspect unsupported regions.</p>
</div>
</div>
<div class="header-badge">EXPLICIT TOY HEURISTIC</div>
</header>
<main>
<section id="viewport" aria-label="Interactive 3D comparison">
<canvas id="scene" tabindex="0"></canvas>
<div class="metric-badge" id="currentBadge">
<div class="dot"></div>
<div>
<strong id="badgePercent">0.0% unsupported</strong>
<span id="badgeArea">0 mm² unsupported</span>
</div>
</div>
<div id="compareLabels">
<div class="split-line"></div>
<div class="view-label current">CURRENT</div>
<div class="view-label reference">REFERENCE</div>
</div>
<div class="hint">Drag to rotate the model · Right-drag to orbit · Wheel to zoom</div>
<div class="mode-switch" role="group" aria-label="Pointer interaction mode">
<button id="modeModel" class="active" type="button">Turn model</button>
<button id="modeOrbit" type="button">Orbit view</button>
<button id="resetCamera" type="button" title="Reset camera">Reset camera</button>
</div>
<div class="legend">
<span><i class="swatch" style="background:#87b9ca"></i>Supported</span>
<span><i class="swatch" style="background:#ffc857"></i>Near limit</span>
<span><i class="swatch" style="background:#ff607c"></i>Unsupported</span>
</div>
</section>
<aside>
<section class="section">
<div class="section-title">
<h2>Orientation</h2>
<span class="section-note">Degrees</span>
</div>
<div class="sliders">
<div class="slider-row">
<label for="angleX">X pitch</label>
<input id="angleX" type="range" min="-180" max="180" value="18">
<output id="angleXValue">18°</output>
</div>
<div class="slider-row">
<label for="angleY">Y yaw</label>
<input id="angleY" type="range" min="-180" max="180" value="-22">
<output id="angleYValue">-22°</output>
</div>
<div class="slider-row">
<label for="angleZ">Z roll</label>
<input id="angleZ" type="range" min="-180" max="180" value="0">
<output id="angleZValue">0°</output>
</div>
</div>
<div class="button-grid">
<button class="btn" type="button" data-preset="base">Base</button>
<button class="btn" type="button" data-preset="side">Side</button>
<button class="btn" type="button" data-preset="tip">Tip</button>
<button class="btn" type="button" data-preset="fin">Fin</button>
</div>
<div class="button-grid two">
<button id="autoRotate" class="btn" type="button">Auto turn</button>
<button id="resetOrientation" class="btn" type="button">Reset model</button>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Toy overhang rule</h2>
<span class="section-note">Geometric heuristic</span>
</div>
<div class="rule-card">
<p>
A downward-facing triangle is <strong>unsupported</strong> when its
overhang angle from vertical exceeds the selected limit.
Triangles whose centroid is within <strong>0.75 mm</strong> of
the bed are treated as bed-supported.
</p>
<code class="formula">γ = asin(clamp(−n·ẑ, 0, 1))</code>
</div>
<div class="slider-row" style="margin-top:13px;grid-template-columns:1fr 54px">
<label for="criticalAngle">Critical angle</label>
<output id="criticalAngleValue">45°</output>
</div>
<input
id="criticalAngle"
type="range"
min="0"
max="70"
step="1"
value="45"
aria-label="Critical overhang angle"
>
<div class="check-row">
<label>
<input id="highlightUnsupported" type="checkbox" checked>
Highlight unsupported regions
</label>
<label>
<input id="showEdges" type="checkbox" checked>
Facets
</label>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Comparison</h2>
<span class="section-note">Current vs pinned</span>
</div>
<div class="comparison-card">
<div class="metric-grid">
<div class="metric">
<span>Current</span>
<strong id="currentPercent">0.0%</strong>
<small id="currentArea">0 mm² unsupported</small>
</div>
<div class="metric reference">
<span>Reference</span>
<strong id="referencePercent">0.0%</strong>
<small id="referenceArea">0 mm² unsupported</small>
</div>
</div>
<div id="deltaText" class="delta">Current and reference match.</div>
</div>
<div class="button-grid two">
<button id="pinReference" class="btn" type="button">Pin current</button>
<button id="compareButton" class="btn" type="button">Compare split</button>
</div>
</section>
<section class="section">
<details>
<summary>Model and method</summary>
<p>
The default is a closed, faceted rocket-like toy with four raised
fins. It is measured on a nominal 100 × 100 mm bed. Uploaded STL
files are normalized to a maximum dimension of 68 mm.
</p>
<p>
This is a deliberately simple overhang estimator, not a slicing
engine. It does not model bridges, islands, support placement,
nozzle geometry, path width, or layer adhesion.
</p>
</details>
<label class="file-label">
Load low-poly STL
<input id="stlInput" type="file" accept=".stl,model/stl">
</label>
<div class="footer-note">
Drop an STL onto the 3D view. ASCII and binary STL files are supported.
</div>
</section>
</aside>
</main>
</div>
<div id="toast" role="status"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Constants and DOM
// ------------------------------------------------------------
const viewport = document.getElementById("viewport");
const canvas = document.getElementById("scene");
const ui = {
currentBadge: document.getElementById("currentBadge"),
badgePercent: document.getElementById("badgePercent"),
badgeArea: document.getElementById("badgeArea"),
currentPercent: document.getElementById("currentPercent"),
currentArea: document.getElementById("currentArea"),
referencePercent: document.getElementById("referencePercent"),
referenceArea: document.getElementById("referenceArea"),
deltaText: document.getElementById("deltaText"),
angleX: document.getElementById("angleX"),
angleY: document.getElementById("angleY"),
angleZ: document.getElementById("angleZ"),
angleXValue: document.getElementById("angleXValue"),
angleYValue: document.getElementById("angleYValue"),
angleZValue: document.getElementById("angleZValue"),
criticalAngle: document.getElementById("criticalAngle"),
criticalAngleValue: document.getElementById("criticalAngleValue"),
highlightUnsupported: document.getElementById("highlightUnsupported"),
showEdges: document.getElementById("showEdges"),
compareButton: document.getElementById("compareButton"),
pinReference: document.getElementById("pinReference"),
autoRotate: document.getElementById("autoRotate"),
modeModel: document.getElementById("modeModel"),
modeOrbit: document.getElementById("modeOrbit"),
resetCamera: document.getElementById("resetCamera"),
resetOrientation: document.getElementById("resetOrientation"),
stlInput: document.getElementById("stlInput"),
toast: document.getElementById("toast")
};
const BED_SIZE = 100;
const BED_CLEARANCE = 0.15;
const BED_SUPPORT_TOLERANCE = 0.75;
const DEFAULT_ORIENTATION = { x: 18, y: -22, z: 0 };
const COLORS = {
supported: new THREE.Color(0x87b9ca),
marginal: new THREE.Color(0xffc857),
unsupported: new THREE.Color(0xff607c),
neutral: new THREE.Color(0x8cb5c5)
};
const state = {
orientation: { ...DEFAULT_ORIENTATION },
referenceOrientation: { x: 0, y: 0, z: 0 },
criticalAngle: 45,
highlight: true,
showEdges: true,
comparing: false,
pointerMode: "model",
autoRotate: false,
currentStats: null,
referenceStats: null
};
// ------------------------------------------------------------
// Renderer, scenes, and custom camera
// ------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
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.autoClear = false;
const camera = new THREE.PerspectiveCamera(38, 1, 0.5, 1000);
const cameraTarget = new THREE.Vector3(0, 0, 27);
const cameraState = {
theta: 0.72,
phi: 1.03,
radius: 145
};
function updateCamera() {
const { theta, phi, radius } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(phi) * Math.sin(theta),
cameraTarget.y + radius * Math.sin(phi) * Math.cos(theta),
cameraTarget.z + radius * Math.cos(phi)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.theta = 0.72;
cameraState.phi = 1.03;
cameraState.radius = 145;
updateCamera();
}
function createScene() {
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b131d);
const hemi = new THREE.HemisphereLight(0xccefff, 0x17202b, 2.0);
scene.add(hemi);
const key = new THREE.DirectionalLight(0xffffff, 3.0);
key.position.set(45, 55, 95);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -70;
key.shadow.camera.right = 70;
key.shadow.camera.top = 70;
key.shadow.camera.bottom = -70;
key.shadow.camera.near = 1;
key.shadow.camera.far = 220;
key.shadow.bias = -0.0004;
scene.add(key);
const rim = new THREE.DirectionalLight(0x73d4e8, 1.1);
rim.position.set(-65, -35, 55);
scene.add(rim);
const bed = new THREE.Mesh(
new THREE.BoxGeometry(BED_SIZE, BED_SIZE, 2),
new THREE.MeshStandardMaterial({
color: 0x14202b,
roughness: 0.95,
metalness: 0.0
})
);
bed.position.z = -1;
bed.receiveShadow = true;
scene.add(bed);
const bedEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(BED_SIZE, BED_SIZE, 2)),
new THREE.LineBasicMaterial({
color: 0x31495b,
transparent: true,
opacity: 0.65
})
);
bedEdges.position.z = -1;
scene.add(bedEdges);
const grid = new THREE.GridHelper(BED_SIZE, 20, 0x476474, 0x253747);
grid.rotation.x = Math.PI / 2;
grid.position.z = 0.025;
grid.material.transparent = true;
grid.material.opacity = 0.62;
scene.add(grid);
const axes = new THREE.Group();
axes.add(new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(-43, -43, 0.4),
9,
0xff607c,
2.2,
1.2
));
axes.add(new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(-43, -43, 0.4),
9,
0x66dfad,
2.2,
1.2
));
axes.add(new THREE.ArrowHelper(
new THREE.Vector3(0, 0, 1),
new THREE.Vector3(-43, -43, 0.4),
9,
0x73d4e8,
2.2,
1.2
));
scene.add(axes);
return scene;
}
const sceneCurrent = createScene();
const sceneReference = createScene();
const currentGroup = new THREE.Group();
const referenceGroup = new THREE.Group();
sceneCurrent.add(currentGroup);
sceneReference.add(referenceGroup);
const surfaceMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 0.57,
metalness: 0.03,
side: THREE.FrontSide
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x17303e,
transparent: true,
opacity: 0.42,
depthWrite: false
});
let currentGeometry = null;
let referenceGeometry = null;
let currentMesh = null;
let referenceMesh = null;
let currentEdges = null;
let referenceEdges = null;
// ------------------------------------------------------------
// Default low-poly rocket-like toy
// ------------------------------------------------------------
function createDefaultGeometry() {
const segments = 12;
const positions = [];
const indices = [];
const ringZ = [-30, -20, 18];
const ringCount = 3;
for (let ring = 0; ring < ringCount; ring++) {
for (let i = 0; i < segments; i++) {
const angle = (i / segments) * Math.PI * 2;
let radius;
if (ring === 0) {
radius = 18;
} else if (ring === 1) {
radius = i % 3 === 0 ? 36 : 22;
} else {
radius = 14;
}
positions.push(
Math.cos(angle) * radius,
Math.sin(angle) * radius,
ringZ[ring]
);
}
}
const topIndex = positions.length / 3;
positions.push(0, 0, 32);
const bottomCenter = positions.length / 3;
positions.push(0, 0, -30);
for (let ring = 0; ring < ringCount - 1; ring++) {
const lower = ring * segments;
const upper = (ring + 1) * segments;
for (let i = 0; i < segments; i++) {
const next = (i + 1) % segments;
const a = lower + i;
const b = lower + next;
const c = upper + i;
const d = upper + next;
indices.push(a, b, c);
indices.push(b, d, c);
}
}
const upperRing = (ringCount - 1) * segments;
for (let i = 0; i < segments; i++) {
const next = (i + 1) % segments;
indices.push(upperRing + i, upperRing + next, topIndex);
}
for (let i = 0; i < segments; i++) {
const next = (i + 1) % segments;
indices.push(bottomCenter, next, i);
}
const indexed = new THREE.BufferGeometry();
indexed.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
indexed.setIndex(indices);
indexed.computeVertexNormals();
const edges = new THREE.EdgesGeometry(indexed, 18);
const geometry = indexed.toNonIndexed();
indexed.dispose();
geometry.computeVertexNormals();
return { geometry, edges };
}
// ------------------------------------------------------------
// Display replacement
// ------------------------------------------------------------
function disposeGroupContents(group) {
for (const child of [...group.children]) {
group.remove(child);
if (child.geometry) child.geometry.dispose();
}
}
function installGeometry(bundle) {
disposeGroupContents(currentGroup);
disposeGroupContents(referenceGroup);
currentGeometry = bundle.geometry;
currentGeometry.setAttribute("color", new THREE.BufferAttribute(
new Float32Array(currentGeometry.getAttribute("position").count * 3), 3
));
referenceGeometry = currentGeometry.clone();
currentMesh = new THREE.Mesh(currentGeometry, surfaceMaterial);
currentMesh.castShadow = true;
currentMesh.receiveShadow = true;
referenceMesh = new THREE.Mesh(referenceGeometry, surfaceMaterial);
referenceMesh.castShadow = true;
referenceMesh.receiveShadow = true;
currentEdges = new THREE.LineSegments(bundle.edges, edgeMaterial);
referenceEdges = new THREE.LineSegments(bundle.edges.clone(), edgeMaterial);
currentGroup.add(currentMesh, currentEdges);
referenceGroup.add(referenceMesh, referenceEdges);
currentEdges.visible = state.showEdges;
referenceEdges.visible = state.showEdges;
}
// ------------------------------------------------------------
// Orientation and overhang analysis
// ------------------------------------------------------------
const tempBox = new THREE.Box3();
const tempA = new THREE.Vector3();
const tempB = new THREE.Vector3();
const tempC = new THREE.Vector3();
const tempAB = new THREE.Vector3();
const tempAC = new THREE.Vector3();
const tempNormal = new THREE.Vector3();
const tempCentroid = new THREE.Vector3();
function settleGroup(group, orientation) {
group.rotation.set(
THREE.MathUtils.degToRad(orientation.x),
THREE.MathUtils.degToRad(orientation.y),
THREE.MathUtils.degToRad(orientation.z),
"XYZ"
);
group.position.set(0, 0, 0);
group.updateMatrixWorld(true);
tempBox.setFromObject(group);
group.position.z = -tempBox.min.z + BED_CLEARANCE;
group.updateMatrixWorld(true);
}
function analyzeMesh(mesh, geometry, thresholdDegrees) {
mesh.updateWorldMatrix(true, false);
const position = geometry.attributes.position;
const colors = geometry.attributes.color;
const threshold = THREE.MathUtils.degToRad(thresholdDegrees);
let totalArea = 0;
let unsupportedArea = 0;
let unsupportedTriangles = 0;
let marginalTriangles = 0;
for (let i = 0; i < position.count; i += 3) {
tempA.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
tempB.fromBufferAttribute(position, i + 1).applyMatrix4(mesh.matrixWorld);
tempC.fromBufferAttribute(position, i + 2).applyMatrix4(mesh.matrixWorld);
tempAB.subVectors(tempB, tempA);
tempAC.subVectors(tempC, tempA);
tempNormal.crossVectors(tempAB, tempAC);
const doubleArea = tempNormal.length();
const area = doubleArea * 0.5;
totalArea += area;
if (doubleArea > 1e-10) {
tempNormal.multiplyScalar(1 / doubleArea);
} else {
tempNormal.set(0, 0, 0);
}
tempCentroid
.copy(tempA)
.add(tempB)
.add(tempC)
.multiplyScalar(1 / 3);
// γ: 0° on a vertical wall, 90° on a horizontal downward face.
const gamma = tempNormal.z < 0
? Math.asin(THREE.MathUtils.clamp(-tempNormal.z, 0, 1))
: 0;
const bedSupported = tempCentroid.z <= BED_SUPPORT_TOLERANCE;
const unsupported = !bedSupported && gamma > threshold;
const marginal = !unsupported && !bedSupported &&
gamma > Math.max(0, threshold - THREE.MathUtils.degToRad(6));
let color;
if (!state.highlight) {
color = COLORS.neutral;
} else if (unsupported) {
color = COLORS.unsupported;
unsupportedArea += area;
unsupportedTriangles++;
} else if (marginal) {
color = COLORS.marginal;
marginalTriangles++;
} else {
color = COLORS.supported;
}
for (let v = 0; v < 3; v++) {
colors.setXYZ(i + v, color.r, color.g, color.b);
}
}
colors.needsUpdate = true;
return {
totalArea,
unsupportedArea,
unsupportedTriangles,
marginalTriangles,
percent: totalArea > 0 ? (unsupportedArea / totalArea) * 100 : 0
};
}
function formatArea(area) {
return `${Math.round(area).toLocaleString()} mm²`;
}
function updateOrientationInputs() {
const o = state.orientation;
ui.angleX.value = o.x;
ui.angleY.value = o.y;
ui.angleZ.value = o.z;
ui.angleXValue.value = `${Math.round(o.x)}°`;
ui.angleYValue.value = `${Math.round(o.y)}°`;
ui.angleZValue.value = `${Math.round(o.z)}°`;
}
function updateMetrics() {
const current = state.currentStats;
const reference = state.referenceStats;
if (!current || !reference) return;
ui.badgePercent.textContent = `${current.percent.toFixed(1)}% unsupported`;
ui.badgeArea.textContent = `${formatArea(current.unsupportedArea)} unsupported`;
ui.currentPercent.textContent = `${current.percent.toFixed(1)}%`;
ui.currentArea.textContent = `${formatArea(current.unsupportedArea)} unsupported`;
ui.referencePercent.textContent = `${reference.percent.toFixed(1)}%`;
ui.referenceArea.textContent = `${formatArea(reference.unsupportedArea)} unsupported`;
const delta = reference.percent - current.percent;
ui.deltaText.classList.remove("good", "bad");
if (Math.abs(delta) < 0.05) {
ui.deltaText.textContent = "Current and reference match.";
} else {
const better = delta > 0;
ui.deltaText.classList.add(better ? "good" : "bad");
ui.deltaText.textContent =
`${better ? "Better" : "Worse"} than reference by ` +
`${Math.abs(delta).toFixed(1)} percentage points.`;
}
}
function refreshCurrent() {
settleGroup(currentGroup, state.orientation);
state.currentStats = analyzeMesh(
currentMesh,
currentGeometry,
state.criticalAngle
);
updateOrientationInputs();
updateMetrics();
}
function refreshReference() {
settleGroup(referenceGroup, state.referenceOrientation);
state.referenceStats = analyzeMesh(
referenceMesh,
referenceGeometry,
state.criticalAngle
);
updateMetrics();
}
function setOrientation(next) {
state.orientation.x = next.x;
state.orientation.y = next.y;
state.orientation.z = next.z;
refreshCurrent();
}
// ------------------------------------------------------------
// UI events
// ------------------------------------------------------------
ui.angleX.addEventListener("input", () => {
state.orientation.x = Number(ui.angleX.value);
refreshCurrent();
});
ui.angleY.addEventListener("input", () => {
state.orientation.y = Number(ui.angleY.value);
refreshCurrent();
});
ui.angleZ.addEventListener("input", () => {
state.orientation.z = Number(ui.angleZ.value);
refreshCurrent();
});
ui.criticalAngle.addEventListener("input", () => {
state.criticalAngle = Number(ui.criticalAngle.value);
ui.criticalAngleValue.value = `${state.criticalAngle}°`;
refreshCurrent();
refreshReference();
});
ui.highlightUnsupported.addEventListener("change", () => {
state.highlight = ui.highlightUnsupported.checked;
refreshCurrent();
refreshReference();
});
ui.showEdges.addEventListener("change", () => {
state.showEdges = ui.showEdges.checked;
currentEdges.visible = state.showEdges;
referenceEdges.visible = state.showEdges;
});
document.querySelectorAll("[data-preset]").forEach((button) => {
button.addEventListener("click", () => {
const presets = {
base: { x: 0, y: 0, z: 0 },
side: { x: 90, y: 0, z: 0 },
tip: { x: 180, y: 0, z: 0 },
fin: { x: 0, y: 90, z: 0 }
};
setOrientation(presets[button.dataset.preset]);
});
});
ui.resetOrientation.addEventListener("click", () => {
setOrientation({ ...DEFAULT_ORIENTATION });
});
ui.pinReference.addEventListener("click", () => {
state.referenceOrientation = { ...state.orientation };
refreshReference();
showToast("Current orientation pinned as reference.");
});
ui.compareButton.addEventListener("click", () => {
state.comparing = !state.comparing;
updateComparisonLayout();
});
ui.autoRotate.addEventListener("click", () => {
state.autoRotate = !state.autoRotate;
ui.autoRotate.classList.toggle("active", state.autoRotate);
});
ui.modeModel.addEventListener("click", () => {
state.pointerMode = "model";
ui.modeModel.classList.add("active");
ui.modeOrbit.classList.remove("active");
});
ui.modeOrbit.addEventListener("click", () => {
state.pointerMode = "orbit";
ui.modeOrbit.classList.add("active");
ui.modeModel.classList.remove("active");
});
ui.resetCamera.addEventListener("click", resetCamera);
function updateComparisonLayout() {
viewport.classList.toggle("comparing", state.comparing);
ui.compareButton.classList.toggle("active", state.comparing);
ui.compareButton.textContent = state.comparing
? "Exit split"
: "Compare split";
ui.currentBadge.style.display = state.comparing ? "none" : "flex";
}
let toastTimer = 0;
function showToast(message) {
ui.toast.textContent = message;
ui.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
ui.toast.classList.remove("show");
}, 2200);
}
// ------------------------------------------------------------
// Direct pointer controls: turn model, orbit camera, zoom
// ------------------------------------------------------------
const pointers = new Map();
let dragType = null;
let lastPinchDistance = 0;
let lastPinchCenter = { x: 0, y: 0 };
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
function pointerCenter() {
const values = [...pointers.values()];
if (!values.length) return { x: 0, y: 0 };
if (values.length === 1) return values[0];
return {
x: (values[0].x + values[1].x) * 0.5,
y: (values[0].y + values[1].y) * 0.5
};
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.focus();
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
canvas.classList.add("dragging");
if (pointers.size === 1) {
dragType =
event.button === 2 ||
event.button === 1 ||
event.altKey ||
state.pointerMode === "orbit"
? "orbit"
: "model";
} else if (pointers.size === 2) {
dragType = "pinch";
lastPinchDistance = pointerDistance();
lastPinchCenter = pointerCenter();
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const distance = pointerDistance();
const center = pointerCenter();
if (lastPinchDistance > 0 && distance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (lastPinchDistance / distance),
48,
280
);
cameraState.theta -=
(center.x - lastPinchCenter.x) * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - (center.y - lastPinchCenter.y) * 0.005,
0.16,
Math.PI - 0.16
);
updateCamera();
}
lastPinchDistance = distance;
lastPinchCenter = center;
return;
}
if (dragType === "model") {
state.orientation.y += dx * 0.45;
state.orientation.x += dy * 0.45;
refreshCurrent();
} else if (dragType === "orbit") {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.16,
Math.PI - 0.16
);
updateCamera();
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 0) {
dragType = null;
canvas.classList.remove("dragging");
} else if (pointers.size === 1) {
dragType = state.pointerMode === "orbit" ? "orbit" : "model";
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
48,
280
);
updateCamera();
}, { passive: false });
// ------------------------------------------------------------
// Minimal ASCII and binary STL parser
// ------------------------------------------------------------
function parseSTL(buffer) {
const view = new DataView(buffer);
let positions = null;
if (buffer.byteLength >= 84) {
const triangleCount = view.getUint32(80, true);
const expectedLength = 84 + triangleCount * 50;
if (triangleCount > 0 && expectedLength === buffer.byteLength) {
positions = new Float32Array(triangleCount * 9);
let offset = 84;
for (let triangle = 0; triangle < triangleCount; triangle++) {
// Skip the 12-byte stored normal.
offset += 12;
for (let vertex = 0; vertex < 3; vertex++) {
const p = (triangle * 3 + vertex) * 3;
positions[p] = view.getFloat32(offset, true);
positions[p + 1] = view.getFloat32(offset + 4, true);
positions[p + 2] = view.getFloat32(offset + 8, true);
offset += 12;
}
offset += 2; // Attribute byte count.
}
return positions;
}
}
const text = new TextDecoder().decode(buffer);
const values = [];
const expression = /vertex\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/gi;
let match;
while ((match = expression.exec(text)) !== null) {
values.push(
Number(match[1]),
Number(match[2]),
Number(match[3])
);
}
if (values.length < 9 || values.length % 3 !== 0) {
throw new Error("The STL file could not be parsed.");
}
positions = new Float32Array(values);
return positions;
}
function geometryFromSTL(buffer) {
const rawPositions = parseSTL(buffer);
const raw = new THREE.BufferGeometry();
raw.setAttribute(
"position",
new THREE.Float32BufferAttribute(rawPositions, 3)
);
raw.computeBoundingBox();
const box = raw.boundingBox;
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const maximumDimension = Math.max(size.x, size.y, size.z);
if (!Number.isFinite(maximumDimension) || maximumDimension <= 0) {
throw new Error("The STL contains no usable triangles.");
}
const scale = 68 / maximumDimension;
const centered = new Float32Array(rawPositions.length);
for (let i = 0; i < rawPositions.length; i += 3) {
centered[i] = (rawPositions[i] - center.x) * scale;
centered[i + 1] = (rawPositions[i + 1] - center.y) * scale;
centered[i + 2] = (rawPositions[i + 2] - center.z) * scale;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(centered, 3)
);
geometry.computeVertexNormals();
const edges = new THREE.EdgesGeometry(geometry, 22);
raw.dispose();
return { geometry, edges };
}
async function loadSTLFile(file) {
try {
showToast(`Loading ${file.name}…`);
const buffer = await file.arrayBuffer();
const bundle = geometryFromSTL(buffer);
installGeometry(bundle);
state.orientation = { x: 0, y: 0, z: 0 };
state.referenceOrientation = { x: 0, y: 0, z: 0 };
state.comparing = false;
updateComparisonLayout();
refreshCurrent();
refreshReference();
showToast(`${file.name} loaded and normalized to 68 mm.`);
} catch (error) {
console.error(error);
showToast(error.message || "Unable to load STL.");
}
}
ui.stlInput.addEventListener("change", () => {
const file = ui.stlInput.files[0];
if (file) loadSTLFile(file);
ui.stlInput.value = "";
});
viewport.addEventListener("dragover", (event) => {
event.preventDefault();
});
viewport.addEventListener("drop", (event) => {
event.preventDefault();
const file = event.dataTransfer.files[0];
if (file && file.name.toLowerCase().endsWith(".stl")) {
loadSTLFile(file);
}
});
// ------------------------------------------------------------
// Resize and split rendering
// ------------------------------------------------------------
const renderSize = new THREE.Vector2();
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
const stacked = state.comparing && width < 650;
viewport.classList.toggle("stacked", stacked);
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(viewport);
function renderScene() {
renderer.getSize(renderSize);
const width = Math.floor(renderSize.x);
const height = Math.floor(renderSize.y);
renderer.setScissorTest(false);
renderer.setViewport(0, 0, width, height);
renderer.clear(true, true, true);
if (!state.comparing) {
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.render(sceneCurrent, camera);
return;
}
renderer.setScissorTest(true);
if (width < 650) {
const half = Math.floor(height / 2);
camera.aspect = width / half;
camera.updateProjectionMatrix();
renderer.setViewport(0, half, width, height - half);
renderer.setScissor(0, half, width, height - half);
renderer.clear(true, true, true);
renderer.render(sceneCurrent, camera);
renderer.setViewport(0, 0, width, half);
renderer.setScissor(0, 0, width, half);
renderer.clear(true, true, true);
renderer.render(sceneReference, camera);
} else {
const half = Math.floor(width / 2);
camera.aspect = half / height;
camera.updateProjectionMatrix();
renderer.setViewport(0, 0, half, height);
renderer.setScissor(0, 0, half, height);
renderer.clear(true, true, true);
renderer.render(sceneCurrent, camera);
renderer.setViewport(half, 0, width - half, height);
renderer.setScissor(half, 0, width - half, height);
renderer.clear(true, true, true);
renderer.render(sceneReference, camera);
}
renderer.setScissorTest(false);
}
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
let previousTime = performance.now();
let previousAutoAnalysis = 0;
function animate(now) {
const delta = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (state.autoRotate && now - previousAutoAnalysis > 70) {
state.orientation.y = (state.orientation.y + 14 * delta) % 360;
refreshCurrent();
previousAutoAnalysis = now;
}
renderScene();
requestAnimationFrame(animate);
}
// ------------------------------------------------------------
// Start
// ------------------------------------------------------------
installGeometry(createDefaultGeometry());
resetCamera();
resizeRenderer();
refreshCurrent();
refreshReference();
updateComparisonLayout();
requestAnimationFrame(animate);
</script>
</body>
</html>
```