Prompt specification
Build or customize the Three.js 3D scene "Knit stretch direction study" 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: Knit stretch direction study
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/knit-stretch-direction-study-x0598
Scene Description Prompt:
Knit stretch direction study. Expand the patch horizontally and vertically by changing loop shapes rather than yarn thickness; preserve all interlocking relationships so the source of flexibility remains visible. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (knit-stretch-direction-study-x0598):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Knit Stretch Direction Study</title>
<style>
:root {
--ink: #27302e;
--muted: #68716d;
--paper: #f3efe7;
--panel: rgba(255, 255, 255, 0.78);
--line: rgba(39, 48, 46, 0.13);
--yarn: #ce5a48;
--yarn-light: #ed806a;
--teal: #16878a;
--blue: #3978a8;
--shadow: 0 18px 55px rgba(48, 52, 47, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas.dragging {
cursor: grabbing;
}
.title-card {
position: fixed;
top: 28px;
left: 30px;
z-index: 5;
width: min(390px, calc(100vw - 380px));
pointer-events: none;
}
.eyebrow {
margin-bottom: 9px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(30px, 3.1vw, 49px);
font-weight: 620;
letter-spacing: -0.055em;
line-height: 0.98;
}
h1 span {
color: var(--yarn);
font-weight: 450;
}
.subtitle {
max-width: 350px;
margin: 13px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.status {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 16px;
padding: 7px 10px;
border: 1px solid rgba(22, 135, 138, 0.18);
border-radius: 999px;
background: rgba(22, 135, 138, 0.07);
color: #27696b;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
}
.status i {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 4px rgba(22, 135, 138, 0.1);
}
.panel {
position: fixed;
top: 24px;
right: 24px;
z-index: 6;
width: 324px;
max-height: calc(100vh - 48px);
overflow: auto;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.82);
border-radius: 20px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(120%);
-webkit-backdrop-filter: blur(18px) saturate(120%);
scrollbar-width: thin;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 17px;
}
.panel-title strong {
font-size: 13px;
letter-spacing: -0.01em;
}
.model-tag {
padding: 4px 7px;
border-radius: 6px;
background: rgba(206, 90, 72, 0.1);
color: #a94739;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.control {
margin: 0 0 16px;
}
.control-head {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 8px;
}
.control label {
font-size: 12px;
font-weight: 700;
}
.control output {
color: var(--yarn);
font-size: 12px;
font-variant-numeric: tabular-nums;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 4px 0 6px;
border-radius: 99px;
outline: none;
appearance: none;
-webkit-appearance: none;
background: linear-gradient(
90deg,
var(--yarn) 0 var(--fill, 0%),
rgba(39, 48, 46, 0.13) var(--fill, 0%) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
border: 3px solid #fff;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: var(--yarn);
box-shadow: 0 2px 7px rgba(72, 37, 32, 0.24);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #fff;
border-radius: 50%;
background: var(--yarn);
box-shadow: 0 2px 7px rgba(72, 37, 32, 0.24);
}
.range-note {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.03em;
}
.presets {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 7px;
margin: 2px 0 18px;
}
.preset {
min-height: 34px;
padding: 7px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.56);
color: var(--ink);
font-size: 10px;
font-weight: 700;
cursor: pointer;
transition: 150ms ease;
}
.preset:hover {
border-color: rgba(206, 90, 72, 0.38);
background: #fff;
transform: translateY(-1px);
}
.preset.active {
border-color: rgba(206, 90, 72, 0.3);
background: rgba(206, 90, 72, 0.11);
color: #a94739;
}
.metrics {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
margin: 0 0 17px;
}
.metric {
min-height: 59px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.42);
}
.metric strong {
display: block;
margin-bottom: 4px;
font-size: 16px;
font-weight: 720;
font-variant-numeric: tabular-nums;
letter-spacing: -0.03em;
}
.metric span {
color: var(--muted);
font-size: 9px;
font-weight: 650;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.divider {
height: 1px;
margin: 15px 0;
background: var(--line);
}
.toggles {
display: grid;
gap: 10px;
}
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #4c5652;
font-size: 10px;
font-weight: 650;
cursor: pointer;
}
.toggle input {
position: relative;
width: 29px;
height: 17px;
margin: 0;
border-radius: 99px;
appearance: none;
-webkit-appearance: none;
outline: none;
background: rgba(39, 48, 46, 0.18);
cursor: pointer;
transition: background 150ms ease;
}
.toggle input::after {
position: absolute;
top: 3px;
left: 3px;
width: 11px;
height: 11px;
border-radius: 50%;
background: #fff;
content: "";
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.18);
transition: transform 150ms ease;
}
.toggle input:checked {
background: var(--teal);
}
.toggle input:checked::after {
transform: translateX(12px);
}
.inspection {
margin-top: 14px;
padding: 10px 11px;
border-radius: 9px;
background: rgba(22, 135, 138, 0.07);
color: #336c6d;
font-size: 9px;
line-height: 1.5;
}
.inspection strong {
color: #1e6264;
}
.legend {
position: fixed;
bottom: 26px;
left: 30px;
z-index: 5;
display: grid;
gap: 7px;
pointer-events: none;
color: #59635f;
font-size: 9px;
font-weight: 650;
letter-spacing: 0.02em;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 18px;
height: 3px;
border-radius: 99px;
background: var(--yarn);
box-shadow: 0 1px 3px rgba(115, 48, 39, 0.18);
}
.swatch.diamond {
width: 7px;
height: 7px;
margin: 0 5.5px;
border-radius: 1px;
background: var(--teal);
transform: rotate(45deg);
}
.swatch.dashed {
height: 0;
border-top: 1px dashed #8b9691;
background: none;
}
.swatch.arrow {
width: 17px;
height: 2px;
background: var(--blue);
}
.swatch.arrow::after {
display: block;
width: 5px;
height: 5px;
margin: -2px 0 0 12px;
border-top: 2px solid var(--blue);
border-right: 2px solid var(--blue);
content: "";
transform: rotate(45deg);
}
.camera-tools {
position: fixed;
right: 24px;
bottom: 26px;
z-index: 6;
display: flex;
align-items: center;
gap: 7px;
}
.camera-tools button {
padding: 8px 11px;
border: 1px solid rgba(39, 48, 46, 0.15);
border-radius: 9px;
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
font-size: 9px;
font-weight: 750;
cursor: pointer;
backdrop-filter: blur(10px);
}
.camera-tools button:hover {
background: #fff;
}
.hint {
position: fixed;
left: 50%;
bottom: 25px;
z-index: 5;
padding: 7px 11px;
border-radius: 99px;
background: rgba(255, 255, 255, 0.52);
color: #707975;
font-size: 9px;
pointer-events: none;
transform: translateX(-50%);
backdrop-filter: blur(8px);
}
@media (max-width: 760px) {
.title-card {
top: 15px;
left: 16px;
width: calc(100vw - 32px);
}
.subtitle,
.status {
display: none;
}
h1 {
font-size: 31px;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 43vh;
padding: 15px;
border-radius: 16px;
}
.panel-title {
margin-bottom: 10px;
}
.control {
margin-bottom: 11px;
}
.presets {
margin-bottom: 12px;
}
.metrics {
margin-bottom: 12px;
}
.legend,
.hint {
display: none;
}
.camera-tools {
top: 73px;
right: 14px;
bottom: auto;
}
}
</style>
</head>
<body>
<main id="viewport" aria-label="Interactive three-dimensional knitted fabric study"></main>
<header class="title-card">
<div class="eyebrow">Textile mechanics / Study 01</div>
<h1>Knit <span>stretch</span></h1>
<p class="subtitle">
Directional extension through loop geometry—not yarn thickness.
Every linked loop and interlock remains in place.
</p>
<div class="status"><i></i>Topology locked · yarn gauge fixed</div>
</header>
<aside class="panel" aria-label="Stretch controls">
<div class="panel-title">
<strong>Directional extension</strong>
<span class="model-tag">Linked-loop model</span>
</div>
<div class="control">
<div class="control-head">
<label for="horizontal">Horizontal stretch</label>
<output id="horizontalValue">0%</output>
</div>
<input
id="horizontal"
type="range"
min="0"
max="100"
value="0"
aria-label="Horizontal stretch percentage"
/>
<div class="range-note">Loops widen and flatten across the wale.</div>
</div>
<div class="control">
<div class="control-head">
<label for="vertical">Vertical stretch</label>
<output id="verticalValue">0%</output>
</div>
<input
id="vertical"
type="range"
min="0"
max="100"
value="0"
aria-label="Vertical stretch percentage"
/>
<div class="range-note">Loops elongate through the course.</div>
</div>
<div class="presets" aria-label="Stretch presets">
<button class="preset active" data-preset="relaxed">Relaxed</button>
<button class="preset" data-preset="horizontal">Horizontal +</button>
<button class="preset" data-preset="vertical">Vertical +</button>
<button class="preset" data-preset="biaxial">Biaxial +</button>
</div>
<div class="metrics">
<div class="metric">
<strong id="metricWidth">—</strong>
<span>Patch width</span>
</div>
<div class="metric">
<strong id="metricHeight">—</strong>
<span>Patch height</span>
</div>
<div class="metric">
<strong id="metricLoop">—</strong>
<span>Loop size</span>
</div>
<div class="metric">
<strong>234</strong>
<span>Interlocks held</span>
</div>
</div>
<div class="divider"></div>
<div class="toggles">
<label class="toggle">
Pull direction arrows
<input id="showArrows" type="checkbox" checked />
</label>
<label class="toggle">
Interlock crossing points
<input id="showLinks" type="checkbox" checked />
</label>
<label class="toggle">
Relaxed-state boundary
<input id="showRest" type="checkbox" checked />
</label>
</div>
<div class="inspection" aria-live="polite">
<strong>Fixed yarn diameter: 0.9 mm.</strong><br />
<span id="inspectionText">Hover a loop to inspect its position.</span>
</div>
</aside>
<div class="legend" aria-hidden="true">
<div class="legend-row"><span class="swatch"></span> Yarn · constant diameter</div>
<div class="legend-row"><span class="swatch diamond"></span> Interlock crossing</div>
<div class="legend-row"><span class="swatch dashed"></span> Relaxed boundary</div>
<div class="legend-row"><span class="swatch arrow"></span> Applied pull</div>
</div>
<div class="camera-tools" aria-label="Camera controls">
<button id="frontView">Front</button>
<button id="threeView">3D</button>
<button id="fitView">Fit</button>
</div>
<div class="hint">Drag to orbit · scroll to zoom · click a loop</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const horizontalInput = document.getElementById("horizontal");
const verticalInput = document.getElementById("vertical");
const horizontalValue = document.getElementById("horizontalValue");
const verticalValue = document.getElementById("verticalValue");
const metricWidth = document.getElementById("metricWidth");
const metricHeight = document.getElementById("metricHeight");
const metricLoop = document.getElementById("metricLoop");
const inspectionText = document.getElementById("inspectionText");
const presetButtons = [...document.querySelectorAll(".preset")];
// Model dimensions are treated as centimeters.
const COLS = 14;
const ROWS = 18;
const BASE_LOOP_WIDTH = 0.82;
const BASE_LOOP_HEIGHT = 1.05;
const X_PITCH_RATIO = 0.76;
const Y_PITCH_RATIO = 0.55;
const YARN_RADIUS = 0.045; // 0.9 mm diameter
const PATH_SEGMENTS = 28;
const RADIAL_SEGMENTS = 5;
const VERTICES_PER_LOOP = PATH_SEGMENTS * RADIAL_SEGMENTS;
const FACES_PER_LOOP = PATH_SEGMENTS * RADIAL_SEGMENTS * 2;
const LOOP_COUNT = COLS * ROWS;
const BASE_WIDTH =
(COLS - 1) * BASE_LOOP_WIDTH * X_PITCH_RATIO + BASE_LOOP_WIDTH;
const BASE_HEIGHT =
(ROWS - 1) * BASE_LOOP_HEIGHT * Y_PITCH_RATIO + BASE_LOOP_HEIGHT;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf3efe7);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-8, 8, 7, -7, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0, 0);
const cameraState = {
yaw: 0.18,
pitch: 0.12,
zoom: 1,
distance: 20
};
let cameraHalfHeight = 7;
const hemiLight = new THREE.HemisphereLight(0xfff9ee, 0x87938f, 1.65);
scene.add(hemiLight);
const keyLight = new THREE.DirectionalLight(0xfff4e6, 3.25);
keyLight.position.set(-4.5, 7.5, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.00025;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xb9d9df, 1.05);
fillLight.position.set(7, -2, 6);
scene.add(fillLight);
const backPlane = new THREE.Mesh(
new THREE.PlaneGeometry(32, 32),
new THREE.MeshStandardMaterial({
color: 0xf3efe7,
roughness: 1,
metalness: 0
})
);
backPlane.position.z = -1.28;
backPlane.receiveShadow = true;
scene.add(backPlane);
const technicalGrid = new THREE.GridHelper(30, 30, 0x9aa49f, 0xb7bdb9);
technicalGrid.rotation.x = Math.PI / 2;
technicalGrid.position.z = -1.24;
technicalGrid.material.transparent = true;
technicalGrid.material.opacity = 0.11;
technicalGrid.material.depthWrite = false;
scene.add(technicalGrid);
// One merged, low-poly tube mesh keeps the fabric efficient while allowing
// every loop to deform without changing its topology.
const positions = new Float32Array(LOOP_COUNT * VERTICES_PER_LOOP * 3);
const normals = new Float32Array(LOOP_COUNT * VERTICES_PER_LOOP * 3);
const colors = new Float32Array(LOOP_COUNT * VERTICES_PER_LOOP * 3);
const pathPositions = new Float32Array(LOOP_COUNT * PATH_SEGMENTS * 3);
const indices = new Uint32Array(LOOP_COUNT * FACES_PER_LOOP * 3);
let indexCursor = 0;
for (let loop = 0; loop < LOOP_COUNT; loop++) {
for (let segment = 0; segment < PATH_SEGMENTS; segment++) {
const nextSegment = (segment + 1) % PATH_SEGMENTS;
for (let radial = 0; radial < RADIAL_SEGMENTS; radial++) {
const nextRadial = (radial + 1) % RADIAL_SEGMENTS;
const a = loop * VERTICES_PER_LOOP + segment * RADIAL_SEGMENTS + radial;
const b =
loop * VERTICES_PER_LOOP +
nextSegment * RADIAL_SEGMENTS +
radial;
const c =
loop * VERTICES_PER_LOOP +
nextSegment * RADIAL_SEGMENTS +
nextRadial;
const d =
loop * VERTICES_PER_LOOP +
segment * RADIAL_SEGMENTS +
nextRadial;
indices[indexCursor++] = a;
indices[indexCursor++] = b;
indices[indexCursor++] = d;
indices[indexCursor++] = b;
indices[indexCursor++] = c;
indices[indexCursor++] = d;
}
}
}
const patchGeometry = new THREE.BufferGeometry();
patchGeometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage)
);
patchGeometry.setAttribute(
"normal",
new THREE.BufferAttribute(normals, 3).setUsage(THREE.DynamicDrawUsage)
);
patchGeometry.setAttribute(
"color",
new THREE.BufferAttribute(colors, 3).setUsage(THREE.DynamicDrawUsage)
);
patchGeometry.setIndex(new THREE.BufferAttribute(indices, 1));
const yarnMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.72,
metalness: 0,
flatShading: true
});
const patchMesh = new THREE.Mesh(patchGeometry, yarnMaterial);
patchMesh.castShadow = true;
patchMesh.receiveShadow = true;
patchMesh.frustumCulled = false;
scene.add(patchMesh);
const baseLoopColors = [];
const baseYarn = new THREE.Color("#c95746");
const lightYarn = new THREE.Color("#e77761");
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const loop = row * COLS + col;
const color = baseYarn.clone();
color.lerp(lightYarn, (row + col) % 2 === 0 ? 0.06 : 0.2);
baseLoopColors[loop] = color;
const colorOffset = loop * VERTICES_PER_LOOP * 3;
for (let vertex = 0; vertex < VERTICES_PER_LOOP; vertex++) {
const offset = colorOffset + vertex * 3;
colors[offset] = color.r;
colors[offset + 1] = color.g;
colors[offset + 2] = color.b;
}
}
}
const hoverColor = new THREE.Color("#ffd166");
const selectedColor = new THREE.Color("#16878a");
// The selected loop's centerline is shown as a fine analytical trace.
const selectedPositions = new Float32Array((PATH_SEGMENTS + 1) * 3);
const selectedGeometry = new THREE.BufferGeometry();
selectedGeometry.setAttribute(
"position",
new THREE.BufferAttribute(selectedPositions, 3)
);
const selectedLine = new THREE.Line(
selectedGeometry,
new THREE.LineBasicMaterial({
color: 0x116f72,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
selectedLine.renderOrder = 8;
selectedLine.visible = false;
scene.add(selectedLine);
// Small diamonds identify where an angled loop passes through the plane
// of the linked loop below.
const markerCount = (ROWS - 1) * COLS;
const markerGeometry = new THREE.OctahedronGeometry(0.052, 0);
const markerMaterial = new THREE.MeshBasicMaterial({
color: 0x16878a,
transparent: true,
opacity: 0.58,
depthTest: false,
depthWrite: false
});
const markers = new THREE.InstancedMesh(
markerGeometry,
markerMaterial,
markerCount
);
markers.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
markers.frustumCulled = false;
markers.renderOrder = 6;
scene.add(markers);
const markerDummy = new THREE.Object3D();
// Relaxed-state reference outline.
const restGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-BASE_WIDTH / 2, -BASE_HEIGHT / 2, -0.65),
new THREE.Vector3(BASE_WIDTH / 2, -BASE_HEIGHT / 2, -0.65),
new THREE.Vector3(BASE_WIDTH / 2, BASE_HEIGHT / 2, -0.65),
new THREE.Vector3(-BASE_WIDTH / 2, BASE_HEIGHT / 2, -0.65)
]);
const restFrame = new THREE.LineLoop(
restGeometry,
new THREE.LineDashedMaterial({
color: 0x7e8a85,
dashSize: 0.12,
gapSize: 0.09,
transparent: true,
opacity: 0.4,
depthWrite: false
})
);
restFrame.computeLineDistances();
scene.add(restFrame);
// Live patch dimensions.
const dimensionPositions = new Float32Array(36);
const dimensionGeometry = new THREE.BufferGeometry();
dimensionGeometry.setAttribute(
"position",
new THREE.BufferAttribute(dimensionPositions, 3)
);
const dimensions = new THREE.LineSegments(
dimensionGeometry,
new THREE.LineBasicMaterial({
color: 0x596762,
transparent: true,
opacity: 0.42
})
);
dimensions.frustumCulled = false;
scene.add(dimensions);
const arrowGroup = new THREE.Group();
scene.add(arrowGroup);
const horizontalPull = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0x3978a8,
0.18,
0.11
);
const oppositeHorizontalPull = new THREE.ArrowHelper(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(),
1,
0x3978a8,
0.18,
0.11
);
const verticalPull = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(),
1,
0x3978a8,
0.18,
0.11
);
const oppositeVerticalPull = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(),
1,
0x3978a8,
0.18,
0.11
);
arrowGroup.add(
horizontalPull,
oppositeHorizontalPull,
verticalPull,
oppositeVerticalPull
);
const stretch = {
current: { horizontal: 0, vertical: 0 },
target: { horizontal: 0, vertical: 0 }
};
let currentWidth = BASE_WIDTH;
let currentHeight = BASE_HEIGHT;
let currentLoopWidth = BASE_LOOP_WIDTH;
let currentLoopHeight = BASE_LOOP_HEIGHT;
let hoveredLoop = -1;
let selectedLoop = -1;
function applyCamera() {
const aspect = window.innerWidth / window.innerHeight;
camera.left = -cameraHalfHeight * aspect;
camera.right = cameraHalfHeight * aspect;
camera.top = cameraHalfHeight;
camera.bottom = -cameraHalfHeight;
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraTarget.x +
cameraState.distance * Math.sin(cameraState.yaw) * cp,
cameraTarget.y + cameraState.distance * Math.sin(cameraState.pitch),
cameraTarget.z + cameraState.distance * Math.cos(cameraState.yaw) * cp
);
camera.lookAt(cameraTarget);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
function setCameraFrustum() {
const aspect = window.innerWidth / window.innerHeight;
cameraHalfHeight = Math.max(
6.9,
(currentHeight + 1.7) / 2,
(currentWidth + 1.7) / (2 * aspect)
);
applyCamera();
}
function updateDimensionLines(width, height) {
const horizontalY = -height / 2 - 0.28;
const verticalX = width / 2 + 0.28;
const tick = 0.12;
const values = [
-width / 2, horizontalY, 0, width / 2, horizontalY, 0,
-width / 2, horizontalY - tick, 0, -width / 2, horizontalY + tick, 0,
width / 2, horizontalY - tick, 0, width / 2, horizontalY + tick, 0,
verticalX, -height / 2, 0, verticalX, height / 2, 0,
verticalX - tick, -height / 2, 0, verticalX + tick, -height / 2, 0,
verticalX - tick, height / 2, 0, verticalX + tick, height / 2, 0
];
dimensionPositions.set(values);
dimensionGeometry.attributes.position.needsUpdate = true;
dimensionGeometry.computeBoundingSphere();
}
function updatePullArrows(width, height, horizontal, vertical) {
const horizontalLength = 0.85 + horizontal * 1.05;
const verticalLength = 0.85 + vertical * 1.05;
horizontalPull.position.set(
-width / 2 - 0.68,
-height / 2 - 0.72,
0.12
);
horizontalPull.setLength(horizontalLength, 0.18, 0.11);
oppositeHorizontalPull.position.set(
width / 2 + 0.68,
-height / 2 - 0.72,
0.12
);
oppositeHorizontalPull.setLength(horizontalLength, 0.18, 0.11);
verticalPull.position.set(
width / 2 + 0.7,
-height / 2 - 0.42,
0.12
);
verticalPull.setLength(verticalLength, 0.18, 0.11);
oppositeVerticalPull.position.set(
width / 2 + 0.7,
height / 2 + 0.42,
0.12
);
oppositeVerticalPull.setLength(verticalLength, 0.18, 0.11);
}
function updateSelectedLine() {
if (selectedLoop < 0) {
selectedLine.visible = false;
return;
}
selectedLine.visible = true;
const pathOffset = selectedLoop * PATH_SEGMENTS * 3;
for (let segment = 0; segment < PATH_SEGMENTS; segment++) {
selectedPositions[segment * 3] =
pathPositions[pathOffset + segment * 3];
selectedPositions[segment * 3 + 1] =
pathPositions[pathOffset + segment * 3 + 1];
selectedPositions[segment * 3 + 2] =
pathPositions[pathOffset + segment * 3 + 2];
}
selectedPositions[PATH_SEGMENTS * 3] =
pathPositions[pathOffset];
selectedPositions[PATH_SEGMENTS * 3 + 1] =
pathPositions[pathOffset + 1];
selectedPositions[PATH_SEGMENTS * 3 + 2] =
pathPositions[pathOffset + 2];
selectedGeometry.attributes.position.needsUpdate = true;
selectedGeometry.computeBoundingSphere();
}
function updatePatch() {
const horizontal = stretch.current.horizontal;
const vertical = stretch.current.vertical;
// Only the centerline of the yarn changes. Tube radius never changes.
const widthFactor =
(1 + horizontal * 0.72) * (1 - vertical * 0.035);
const heightFactor =
(1 + vertical * 0.82) * (1 - horizontal * 0.035);
currentLoopWidth = BASE_LOOP_WIDTH * widthFactor;
currentLoopHeight = BASE_LOOP_HEIGHT * heightFactor;
const xPitch = currentLoopWidth * X_PITCH_RATIO;
const yPitch = currentLoopHeight * Y_PITCH_RATIO;
currentWidth =
(COLS - 1) * xPitch + currentLoopWidth;
currentHeight =
(ROWS - 1) * yPitch + currentLoopHeight;
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const loop = row * COLS + col;
const centerX = (col - (COLS - 1) / 2) * xPitch;
const centerY = (row - (ROWS - 1) / 2) * yPitch;
// Alternating planes let each odd row thread through the even row
// below, preserving a visible and countable interlock relationship.
const angle = row % 2 === 1 ? 0.54 : 0;
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
for (let segment = 0; segment < PATH_SEGMENTS; segment++) {
const t = (segment / PATH_SEGMENTS) * Math.PI * 2;
const sinT = Math.sin(t);
const cosT = Math.cos(t);
// Slightly narrowed head gives the loop a knitted-loop silhouette.
const headTaper = 0.76 + 0.24 * ((1 - cosT) * 0.5);
const localX =
0.5 * currentLoopWidth * sinT * headTaper;
const localY = 0.5 * currentLoopHeight * cosT;
// A small side wave provides depth for adjacent wales.
const localZ = 0.05 * sinT;
const worldX =
centerX + localX * cosAngle - localZ * sinAngle;
const worldY = centerY + localY;
const worldZ =
localX * sinAngle + localZ * cosAngle;
const pathOffset = (loop * PATH_SEGMENTS + segment) * 3;
pathPositions[pathOffset] = worldX;
pathPositions[pathOffset + 1] = worldY;
pathPositions[pathOffset + 2] = worldZ;
}
}
}
// Rebuild the low-poly tube surfaces from the unchanged centerlines.
for (let loop = 0; loop < LOOP_COUNT; loop++) {
const pathOffset = loop * PATH_SEGMENTS * 3;
for (let segment = 0; segment < PATH_SEGMENTS; segment++) {
const previous = (segment - 1 + PATH_SEGMENTS) % PATH_SEGMENTS;
const next = (segment + 1) % PATH_SEGMENTS;
const previousOffset = pathOffset + previous * 3;
const nextOffset = pathOffset + next * 3;
let tangentX =
pathPositions[nextOffset] - pathPositions[previousOffset];
let tangentY =
pathPositions[nextOffset + 1] - pathPositions[previousOffset + 1];
let tangentZ =
pathPositions[nextOffset + 2] - pathPositions[previousOffset + 2];
const tangentLength =
Math.hypot(tangentX, tangentY, tangentZ) || 1;
tangentX /= tangentLength;
tangentY /= tangentLength;
tangentZ /= tangentLength;
// A stable frame for the five-sided tube section.
let normalX = tangentY;
let normalY = -tangentX;
const normalLength =
Math.hypot(normalX, normalY) || 1;
normalX /= normalLength;
normalY /= normalLength;
const binormalX = -tangentX * tangentZ;
const binormalY = -tangentY * tangentZ;
const binormalZ =
tangentX * tangentX + tangentY * tangentY;
for (let radial = 0; radial < RADIAL_SEGMENTS; radial++) {
const radialAngle =
(radial / RADIAL_SEGMENTS) * Math.PI * 2;
const cosRadial = Math.cos(radialAngle);
const sinRadial = Math.sin(radialAngle);
const offsetX =
normalX * cosRadial + binormalX * sinRadial;
const offsetY =
normalY * cosRadial + binormalY * sinRadial;
const offsetZ =
binormalZ * sinRadial;
const vertex =
loop * VERTICES_PER_LOOP +
segment * RADIAL_SEGMENTS +
radial;
const positionOffset = vertex * 3;
positions[positionOffset] =
pathPositions[pathOffset + segment * 3] +
offsetX * YARN_RADIUS;
positions[positionOffset + 1] =
pathPositions[pathOffset + segment * 3 + 1] +
offsetY * YARN_RADIUS;
positions[positionOffset + 2] =
pathPositions[pathOffset + segment * 3 + 2] +
offsetZ * YARN_RADIUS;
const normalLength2 =
Math.hypot(offsetX, offsetY, offsetZ) || 1;
normals[positionOffset] = offsetX / normalLength2;
normals[positionOffset + 1] = offsetY / normalLength2;
normals[positionOffset + 2] = offsetZ / normalLength2;
}
}
}
patchGeometry.attributes.position.needsUpdate = true;
patchGeometry.attributes.normal.needsUpdate = true;
patchGeometry.computeBoundingSphere();
// Update the actual crossing positions of the linked loop pairs.
let markerIndex = 0;
for (let row = 1; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const x = (col - (COLS - 1) / 2) * xPitch;
const lowerY = (row - 1 - (ROWS - 1) / 2) * yPitch;
const upperY = (row - (ROWS - 1) / 2) * yPitch;
const crossingY =
row % 2 === 1
? upperY - currentLoopHeight * 0.5
: lowerY + currentLoopHeight * 0.5;
markerDummy.position.set(x, crossingY, 0);
markerDummy.rotation.set(0, Math.PI / 4, 0);
markerDummy.scale.setScalar(row % 2 === 1 ? 1 : 0.82);
markerDummy.updateMatrix();
markers.setMatrixAt(markerIndex++, markerDummy.matrix);
}
}
markers.instanceMatrix.needsUpdate = true;
updateDimensionLines(currentWidth, currentHeight);
updatePullArrows(
currentWidth,
currentHeight,
horizontal,
vertical
);
updateSelectedLine();
setCameraFrustum();
metricWidth.textContent = `${currentWidth.toFixed(1)} cm`;
metricHeight.textContent = `${currentHeight.toFixed(1)} cm`;
metricLoop.textContent =
`${(currentLoopWidth * 10).toFixed(1)} × ` +
`${(currentLoopHeight * 10).toFixed(1)} mm`;
}
function colorLoop(loop) {
if (loop < 0) return;
const color =
loop === selectedLoop
? selectedColor
: loop === hoveredLoop
? hoverColor
: baseLoopColors[loop];
const colorOffset = loop * VERTICES_PER_LOOP * 3;
for (let vertex = 0; vertex < VERTICES_PER_LOOP; vertex++) {
const offset = colorOffset + vertex * 3;
colors[offset] = color.r;
colors[offset + 1] = color.g;
colors[offset + 2] = color.b;
}
patchGeometry.attributes.color.needsUpdate = true;
}
function setHoveredLoop(loop) {
if (loop === hoveredLoop) return;
const previous = hoveredLoop;
hoveredLoop = loop;
colorLoop(previous);
colorLoop(hoveredLoop);
if (hoveredLoop >= 0) {
const row = Math.floor(hoveredLoop / COLS);
const col = hoveredLoop % COLS;
inspectionText.textContent =
`Hovering loop R${String(row + 1).padStart(2, "0")} / ` +
`C${String(col + 1).padStart(2, "0")}. ` +
`Click to retain its analytical trace.`;
} else if (selectedLoop < 0) {
inspectionText.textContent =
"Hover a loop to inspect its position.";
}
}
function setSelectedLoop(loop) {
const previous = selectedLoop;
selectedLoop = loop;
colorLoop(previous);
colorLoop(selectedLoop);
updateSelectedLine();
if (selectedLoop >= 0) {
const row = Math.floor(selectedLoop / COLS);
const col = selectedLoop % COLS;
inspectionText.textContent =
`Selected loop R${String(row + 1).padStart(2, "0")} / ` +
`C${String(col + 1).padStart(2, "0")}. ` +
`Its interlock remains attached during deformation.`;
} else {
inspectionText.textContent =
"Hover a loop to inspect its position.";
}
}
function updateSliderFill(input) {
const percent =
(Number(input.value) - Number(input.min)) /
(Number(input.max) - Number(input.min)) *
100;
input.style.setProperty("--fill", `${percent}%`);
}
function updateOutputs() {
horizontalValue.textContent = `${horizontalInput.value}%`;
verticalValue.textContent = `${verticalInput.value}%`;
updateSliderFill(horizontalInput);
updateSliderFill(verticalInput);
}
function clearPresetSelection() {
presetButtons.forEach((button) =>
button.classList.remove("active")
);
}
horizontalInput.addEventListener("input", () => {
stretch.target.horizontal = Number(horizontalInput.value) / 100;
updateOutputs();
clearPresetSelection();
});
verticalInput.addEventListener("input", () => {
stretch.target.vertical = Number(verticalInput.value) / 100;
updateOutputs();
clearPresetSelection();
});
const presets = {
relaxed: { horizontal: 0, vertical: 0 },
horizontal: { horizontal: 80, vertical: 0 },
vertical: { horizontal: 0, vertical: 80 },
biaxial: { horizontal: 58, vertical: 65 }
};
presetButtons.forEach((button) => {
button.addEventListener("click", () => {
const preset = presets[button.dataset.preset];
stretch.target.horizontal = preset.horizontal;
stretch.target.vertical = preset.vertical;
horizontalInput.value = preset.horizontal;
verticalInput.value = preset.vertical;
updateOutputs();
clearPresetSelection();
button.classList.add("active");
});
});
document.getElementById("showArrows").addEventListener("change", (event) => {
arrowGroup.visible = event.target.checked;
});
document.getElementById("showLinks").addEventListener("change", (event) => {
markers.visible = event.target.checked;
});
document.getElementById("showRest").addEventListener("change", (event) => {
restFrame.visible = event.target.checked;
});
document.getElementById("frontView").addEventListener("click", () => {
cameraState.yaw = 0;
cameraState.pitch = 0;
cameraState.zoom = 1;
applyCamera();
});
document.getElementById("threeView").addEventListener("click", () => {
cameraState.yaw = 0.42;
cameraState.pitch = 0.27;
cameraState.zoom = 1;
applyCamera();
});
document.getElementById("fitView").addEventListener("click", () => {
cameraState.yaw = 0.18;
cameraState.pitch = 0.12;
cameraState.zoom = 1;
setCameraFrustum();
});
// Direct camera controls, implemented without Three.js addons.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let pointerMoved = false;
let previousPointerX = 0;
let previousPointerY = 0;
function pick(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
camera.updateMatrixWorld();
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObject(patchMesh, false)[0];
if (!hit || hit.faceIndex === undefined) return -1;
return Math.floor(hit.faceIndex / FACES_PER_LOOP);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = false;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.classList.add("dragging");
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
if (Math.hypot(deltaX, deltaY) > 2) {
pointerMoved = true;
}
cameraState.yaw -= deltaX * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + deltaY * 0.0045,
-0.75,
0.75
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
applyCamera();
} else {
setHoveredLoop(pick(event));
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointerDown = false;
renderer.domElement.classList.remove("dragging");
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!pointerMoved) {
const hit = pick(event);
setSelectedLoop(hit >= 0 ? hit : -1);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
pointerMoved = false;
renderer.domElement.classList.remove("dragging");
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) setHoveredLoop(-1);
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.55,
2.8
);
applyCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraState.yaw = 0;
cameraState.pitch = 0;
cameraState.zoom = 1;
applyCamera();
});
function resize() {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
setCameraFrustum();
}
window.addEventListener("resize", resize);
updateOutputs();
updatePatch();
applyCamera();
let previousTime = performance.now();
function animate(time) {
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
const horizontalDifference =
stretch.target.horizontal - stretch.current.horizontal;
const verticalDifference =
stretch.target.vertical - stretch.current.vertical;
if (
Math.abs(horizontalDifference) > 0.0001 ||
Math.abs(verticalDifference) > 0.0001
) {
const easing = 1 - Math.exp(-delta * 7.5);
stretch.current.horizontal +=
horizontalDifference * easing;
stretch.current.vertical +=
verticalDifference * easing;
updatePatch();
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```