SOURCE / PINNED RELEASE
Made of little things.
Nappakura
- Release
- a75ca0f8b596…
- Author-recorded commit
- 4463126213fa…
- License
- LICENSE
- Author’s source reference
- nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-8db03001b62
Archive hash verified: b448d77b767ae754…. The source-to-build association is the author’s claim; it has not been independently rebuilt.
import { gizmoHandles, hitHandle, drawGizmo, dragValues } from './gizmo.js';
import type { GizmoState, Handle } from './gizmo.js';
import { DepthRenderer } from './depth-renderer.js';
import { internalEdge, polygonEdges, inside } from './mesh.js';
import type { V2, V3, Mesh } from './mesh.js';
import { drawPiece, paperSize } from './unfold.js';
import type { Pattern, PieceDrawing } from './unfold.js';
export interface Selection {
face: number;
edge: number;
piece: number;
}
export type Mode = 'select' | 'seam' | 'tab';
export interface ViewState {
mesh: Mesh;
pattern: Pattern;
selection: Selection;
mode: Mode;
page: number;
preview: boolean;
wire: boolean;
gizmo?: GizmoState;
previewMesh?: Mesh;
modelling?: {
faces: number[];
edges: number[];
vertices: number[];
vertexMode: boolean;
};
}
export interface ViewEvents {
select: (face: number, edge: number, vertex?: number, additive?: boolean) => void;
startMove: () => void;
move: (piece: number, dx: number, dy: number) => void;
endMove: () => void;
transformStart: () => boolean;
transformPreview: (values: V3) => void;
transformEnd: (commit: boolean) => void;
}
const COLORS = ['#82a8b2', '#8e9dbb', '#a7b89a', '#bba48f', '#9f97b9', '#b9929b'];
const path = (ctx: CanvasRenderingContext2D, p: V2[]) => {
ctx.beginPath();
p.forEach((v, i) => (i ? ctx.lineTo(...v) : ctx.moveTo(...v)));
ctx.closePath();
};
const segmentDistance = (p: V2, a: V2, b: V2) => {
const dx = b[0] - a[0],
dy = b[1] - a[1],
t = Math.max(
0,
Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / (dx * dx + dy * dy || 1)),
);
return Math.hypot(p[0] - a[0] - dx * t, p[1] - a[1] - dy * t);
};
export class Views {
yaw = -0.55;
pitch = 0.28;
modelZoom = 1;
modelPan: V2 = [0, 0];
paperZoom = 1;
paperPan: V2 = [0, 0];
private gizmoHandles: Handle[] = [];
private gizmoProjection = { origin: [0, 0] as V2, basis: [] as V2[], pixelsPerMm: 1 };
private transforming?: {
id: number;
handle: Handle;
start: V2;
state: GizmoState;
projection: { origin: V2; basis: V2[]; pixelsPerMm: number };
moved: boolean;
};
private raster?: DepthRenderer;
private renderDpr = 1;
private projectedVertices: V2[] = [];
private projected: {
face: number;
points: V2[];
depth: number;
normal: V3;
}[] = [];
private paperDrawings: { piece: number; drawing: PieceDrawing }[] = [];
private pageTransform = { scale: 1, x: 0, y: 0 };
private frame = 0;
private observer: ResizeObserver;
private pointers = new Map<number, V2>();
private drag?: {
canvas: HTMLCanvasElement;
start: V2;
last: V2;
id: number;
moved: boolean;
piece: number;
pan: boolean;
};
private model: HTMLCanvasElement;
private paper: HTMLCanvasElement;
private state: () => ViewState;
private events: ViewEvents;
constructor(
model: HTMLCanvasElement,
paper: HTMLCanvasElement,
state: () => ViewState,
events: ViewEvents,
) {
this.model = model;
this.paper = paper;
this.state = state;
this.events = events;
this.observer = new ResizeObserver(() => this.draw());
this.observer.observe(model);
this.observer.observe(paper);
for (const canvas of [model, paper]) {
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
canvas.addEventListener('pointerdown', (e) => this.down(e, canvas));
canvas.addEventListener('pointermove', (e) => this.motion(e, canvas));
canvas.addEventListener('pointerup', (e) => this.up(e, canvas));
canvas.addEventListener('pointercancel', () => this.cancel());
canvas.addEventListener('lostpointercapture', () => {
if (this.drag?.canvas === canvas || this.transforming) this.cancel();
});
canvas.addEventListener(
'wheel',
(e) => {
e.preventDefault();
const amount = Math.exp(-e.deltaY * 0.001);
this.zoom(canvas === model ? 'model' : 'paper', amount);
},
{ passive: false },
);
}
window.addEventListener('blur', () => this.cancel());
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.transforming) {
e.preventDefault();
this.cancel();
this.draw();
}
});
}
draw() {
cancelAnimationFrame(this.frame);
this.frame = requestAnimationFrame(() => {
this.renderModel();
this.renderPaper();
});
}
dispose() {
cancelAnimationFrame(this.frame);
this.observer.disconnect();
}
fit(which: 'model' | 'paper' | 'both' = 'both') {
if (which !== 'paper') {
this.modelZoom = 1;
this.modelPan = [0, 0];
}
if (which !== 'model') {
this.paperZoom = 1;
this.paperPan = [0, 0];
}
this.draw();
}
zoom(which: 'model' | 'paper', factor: number) {
if (which === 'model') this.modelZoom = Math.max(0.25, Math.min(6, this.modelZoom * factor));
else this.paperZoom = Math.max(0.5, Math.min(8, this.paperZoom * factor));
this.draw();
}
orbit(dx: number, dy: number) {
this.yaw += dx;
this.pitch = Math.max(-1.5, Math.min(1.5, this.pitch + dy));
this.draw();
}
private setup(canvas: HTMLCanvasElement) {
const { width: w, height: h } = canvas.getBoundingClientRect();
if (!w || !h) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const ctx = canvas.getContext('2d')!;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
return { ctx, w, h };
}
private rotate(v: V3): V3 {
const cy = Math.cos(this.yaw),
sy = Math.sin(this.yaw),
cp = Math.cos(this.pitch),
sp = Math.sin(this.pitch);
const x = v[0] * cy + v[2] * sy,
z = -v[0] * sy + v[2] * cy;
return [x, v[1] * cp - z * sp, v[1] * sp + z * cp];
}
private renderModel() {
const setup = this.setup(this.model);
if (!setup) return;
const { ctx, w, h } = setup,
{ pattern, selection, wire, modelling, gizmo } = this.state(),
mesh = this.state().previewMesh ?? this.state().mesh;
const gradient = ctx.createLinearGradient(0, 0, w, h);
gradient.addColorStop(0, '#263443');
gradient.addColorStop(1, '#17222e');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = '#4d5c6a';
for (let x = 20; x < w; x += 24)
for (let y = 20; y < h; y += 24) {
ctx.beginPath();
ctx.arc(x, y, 0.65, 0, Math.PI * 2);
ctx.fill();
}
const scale = Math.min(w, h) * 0.65 * this.modelZoom,
cx = w / 2 + this.modelPan[0],
cy = h / 2 + this.modelPan[1];
const rotated = mesh.vertices.map((v) => this.rotate(v));
const projected = rotated.map((v) => [cx + v[0] * scale, cy - v[1] * scale] as V2);
const pieceMap = new Map<number, number>();
pattern.pieces.forEach((p) => p.faces.forEach((f) => pieceMap.set(f.face, p.id)));
this.projected = mesh.faces
.map((f, face) => ({
face,
points: f.map((i) => projected[i]),
depth: f.reduce((s, i) => s + rotated[i][2], 0) / 3,
normal: this.rotate(mesh.normals[face]),
}))
.sort((a, b) => a.depth - b.depth);
ctx.save();
ctx.shadowColor = '#0006';
ctx.shadowBlur = 24;
ctx.fillStyle = '#0a131b55';
ctx.beginPath();
ctx.ellipse(cx, cy + scale * 0.53, scale * 0.35, scale * 0.06, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
const dpr = this.model.width / w;
this.renderDpr = dpr;
this.projectedVertices = projected;
const raster = new DepthRenderer(this.model.width, this.model.height);
this.raster = raster;
const points = projected.map((p, i) => [p[0] * dpr, p[1] * dpr, rotated[i][2]] as V3);
const rgba = (hex: string, shade = 0) =>
[0, 1, 2]
.map((i) =>
Math.round(
parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16) * (1 - shade) + [4, 14, 24][i] * shade,
),
)
.concat(255);
for (const face of this.projected) {
const selected = modelling
? modelling.faces.includes(face.face)
: mesh.facePolygons[face.face] === mesh.facePolygons[selection.face];
const inPiece = pieceMap.get(face.face) === selection.piece;
const base = selected
? '#69b6ef'
: inPiece
? '#9fbdcd'
: COLORS[(pieceMap.get(face.face) || 0) % COLORS.length];
const shade = Math.max(
0,
Math.min(
0.55,
0.32 - face.normal[0] * -0.18 - face.normal[1] * 0.23 - face.normal[2] * 0.12,
),
);
raster.triangle(
mesh.faces[face.face].map((i) => points[i]),
rgba(base, shade),
face.face,
);
}
for (const edge of mesh.edges) {
if (internalEdge(mesh, edge)) continue;
const selected = modelling ? modelling.edges.includes(edge.id) : edge.id === selection.edge;
const selectedFace = edge.faces.some((f) =>
modelling
? modelling.faces.includes(f)
: mesh.facePolygons[f] === mesh.facePolygons[selection.face],
);
const color = selected
? '#ffb55c'
: selectedFace
? '#d4edff'
: wire
? pattern.joined.includes(edge.id)
? '#142430'
: '#efb777'
: '#273e4c';
raster.line(
points[edge.a],
points[edge.b],
rgba(color),
(selected ? 3 : selectedFace ? 1.5 : 0.8) * dpr,
);
}
const layer = document.createElement('canvas');
layer.width = this.model.width;
layer.height = this.model.height;
layer.getContext('2d')!.putImageData(raster.image, 0, 0);
ctx.drawImage(layer, 0, 0, w, h);
if (modelling?.vertexMode)
for (let i = 0; i < points.length; i++) {
if (!raster.visible(points[i])) continue;
const selected = modelling.vertices.includes(i);
ctx.beginPath();
ctx.arc(...projected[i], selected ? 5 : 3, 0, Math.PI * 2);
ctx.fillStyle = selected ? '#ffb55c' : '#d4edff';
ctx.fill();
}
this.gizmoHandles = [];
if (gizmo && this.state().mode === 'select') {
const c = this.rotate(gizmo.center),
origin: V2 = [cx + c[0] * scale, cy - c[1] * scale];
const basis = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
].map((v) => {
const r = this.rotate(v as V3);
return [r[0], -r[1]] as V2;
});
this.gizmoProjection = { origin, basis, pixelsPerMm: scale / gizmo.size };
this.gizmoHandles = gizmoHandles(gizmo, origin, basis);
drawGizmo(ctx, this.gizmoHandles, gizmo.operation, this.transforming?.handle);
}
// Small orientation triad stays fixed while its directions follow the model.
const origin: V2 = [34, h - 32];
[
['X', [1, 0, 0], '#ef9e87'],
['Y', [0, 1, 0], '#b7d59a'],
['Z', [0, 0, 1], '#88b8e9'],
].forEach(([label, vector, color]) => {
const v = this.rotate(vector as V3);
ctx.strokeStyle = color as string;
ctx.fillStyle = color as string;
ctx.lineWidth = 1.4;
ctx.beginPath();
ctx.moveTo(...origin);
ctx.lineTo(origin[0] + v[0] * 21, origin[1] - v[1] * 21);
ctx.stroke();
ctx.font = '10px ui-monospace, monospace';
ctx.fillText(label as string, origin[0] + v[0] * 29 - 3, origin[1] - v[1] * 29 + 3);
});
}
private renderPaper() {
const setup = this.setup(this.paper);
if (!setup) return;
const { ctx, w, h } = setup,
{ mesh, pattern, selection, page, preview } = this.state();
const [pw, ph] = paperSize(pattern.settings),
scale = Math.min((w - 44) / pw, (h - 40) / ph) * this.paperZoom;
const x = (w - pw * scale) / 2 + this.paperPan[0],
y = (h - ph * scale) / 2 + this.paperPan[1];
this.pageTransform = { scale, x, y };
ctx.fillStyle = '#e4e8ec';
ctx.fillRect(0, 0, w, h);
ctx.save();
ctx.shadowColor = '#24304422';
ctx.shadowBlur = 16;
ctx.shadowOffsetY = 4;
ctx.fillStyle = '#fffefa';
ctx.fillRect(x, y, pw * scale, ph * scale);
ctx.restore();
ctx.save();
ctx.translate(x, y);
ctx.scale(scale, scale);
if (!preview) {
const m = pattern.settings.margin;
ctx.strokeStyle = '#bbc5cd';
ctx.lineWidth = 0.25;
ctx.setLineDash([1, 1.5]);
ctx.strokeRect(m, m, pw - 2 * m, ph - 2 * m);
ctx.setLineDash([]);
}
this.paperDrawings = pattern.pieces
.filter((p) => p.page === page)
.map((piece) => ({
piece: piece.id,
drawing: drawPiece(mesh, pattern, piece),
}));
for (const { piece, drawing } of this.paperDrawings) {
for (const poly of drawing.polygons) {
path(ctx, poly.points);
ctx.fillStyle = preview
? '#fffefa'
: mesh.facePolygons[poly.face] === mesh.facePolygons[selection.face]
? '#badbfa'
: piece === selection.piece
? '#e2eef8'
: '#f1f3f1';
ctx.fill();
}
for (const tab of drawing.tabs) {
path(ctx, tab);
ctx.fillStyle = '#f1f1ed';
ctx.fill();
}
for (const line of drawing.lines) {
if (line.kind === 'flat') continue;
const selected = !preview && line.edge === selection.edge;
ctx.strokeStyle = selected ? '#c96716' : line.kind === 'cut' ? '#26343e' : '#647c8e';
ctx.lineWidth = selected
? Math.max(0.6, 1.6 / scale)
: Math.max(pattern.settings.lineWidth, 0.7 / scale);
ctx.setLineDash(
line.kind === 'mountain' ? [2, 1] : line.kind === 'valley' ? [2, 0.8, 0.4, 0.8] : [],
);
ctx.beginPath();
ctx.moveTo(...line.a);
ctx.lineTo(...line.b);
ctx.stroke();
}
ctx.setLineDash([]);
ctx.fillStyle = '#56616b';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const label of drawing.labels) {
ctx.font = `${label.size}px Arial`;
ctx.save();
ctx.translate(...label.point);
ctx.rotate(label.angle);
ctx.fillText(label.text, 0, 0);
ctx.restore();
}
}
ctx.font = '2.5px Arial';
ctx.fillStyle = '#67737b';
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillText(`${mesh.name.slice(0, 35)} · ${page + 1} · Actual size / 100%`, 10, ph - 4.5);
ctx.strokeStyle = '#68747b';
ctx.lineWidth = 0.18;
ctx.beginPath();
ctx.moveTo(pw - 35, ph - 5);
ctx.lineTo(pw - 15, ph - 5);
ctx.stroke();
ctx.textAlign = 'center';
ctx.font = '2px Arial';
ctx.fillText('20 mm', pw - 25, ph - 7);
ctx.restore();
}
private point(event: PointerEvent, canvas: HTMLCanvasElement): V2 {
const r = canvas.getBoundingClientRect();
return [event.clientX - r.left, event.clientY - r.top];
}
private hit(
point: V2,
canvas: HTMLCanvasElement,
): { face: number; edge: number; piece: number; vertex: number } {
const state = this.state();
let vertex = -1;
let face = -1,
edge = -1,
piece = -1;
if (canvas === this.model) {
face = this.raster?.faceAt(point[0] * this.renderDpr, point[1] * this.renderDpr) ?? -1;
if (face >= 0) {
const group = state.mesh.facePolygons[face];
const vertices = [
...new Set(
state.mesh.faces.flatMap((f, i) => (state.mesh.facePolygons[i] === group ? f : [])),
),
];
let nearest = 16;
for (const v of vertices) {
const p = this.projectedVertices[v],
d = Math.hypot(p[0] - point[0], p[1] - point[1]);
if (d < nearest) {
nearest = d;
vertex = v;
}
}
let best = 12;
for (const edgeId of polygonEdges(state.mesh, face)) {
const e = state.mesh.edges[edgeId],
d = segmentDistance(point, this.projectedVertices[e.a], this.projectedVertices[e.b]);
if (d < best) {
edge = edgeId;
best = d;
}
}
}
piece = state.pattern.pieces.find((p) => p.faces.some((f) => f.face === face))?.id ?? -1;
} else {
const { scale, x, y } = this.pageTransform,
p: V2 = [(point[0] - x) / scale, (point[1] - y) / scale];
let best = 10 / scale;
for (const item of [...this.paperDrawings].reverse()) {
if (state.mode !== 'select')
for (const line of item.drawing.lines) {
if (line.kind === 'flat') continue;
const d = segmentDistance(p, line.a, line.b);
if (d < best) {
best = d;
edge = line.edge;
face = line.face;
piece = item.piece;
}
}
if (face < 0) {
const poly = item.drawing.polygons.find((poly) => inside(p, poly.points));
if (poly) {
face = poly.face;
piece = item.piece;
}
}
}
}
return { face, edge, piece, vertex };
}
private down(e: PointerEvent, canvas: HTMLCanvasElement) {
if (e.button !== 0 && e.button !== 2) return;
const p = this.point(e, canvas);
if (this.transforming) {
this.cancel();
return;
}
if (canvas === this.model && e.button === 0 && !e.shiftKey && !this.pointers.size) {
const handle = hitHandle(this.gizmoHandles, p),
state = this.state().gizmo;
if (handle && state && this.events.transformStart()) {
e.preventDefault();
canvas.setPointerCapture(e.pointerId);
this.transforming = {
id: e.pointerId,
handle,
start: p,
state,
projection: this.gizmoProjection,
moved: false,
};
canvas.style.cursor = 'grabbing';
return;
}
}
this.pointers.set(e.pointerId, p);
canvas.setPointerCapture(e.pointerId);
if (this.pointers.size > 1) {
if (this.drag) this.drag.moved = true;
return;
}
const hit = this.hit(p, canvas),
pan = e.shiftKey || e.button === 2;
this.drag = {
canvas,
start: p,
last: p,
id: e.pointerId,
moved: false,
piece: pan ? -1 : hit.piece,
pan,
};
if (
canvas === this.paper &&
this.state().mode === 'select' &&
hit.face >= 0 &&
!pan &&
!this.state().preview
)
this.events.select(hit.face, -1);
}
private motion(e: PointerEvent, canvas: HTMLCanvasElement) {
const t = this.transforming;
if (t && t.id === e.pointerId) {
const p = this.point(e, canvas);
if (Math.hypot(p[0] - t.start[0], p[1] - t.start[1]) < 4 && !t.moved) return;
t.moved = true;
this.events.transformPreview(
dragValues(
t.state.operation,
t.handle.axes,
t.projection.basis,
t.start,
p,
t.projection.origin,
t.projection.pixelsPerMm,
e.shiftKey,
),
);
this.draw();
return;
}
if (!this.pointers.has(e.pointerId)) {
if (canvas === this.model)
canvas.style.cursor = hitHandle(this.gizmoHandles, this.point(e, canvas)) ? 'grab' : '';
return;
}
const p = this.point(e, canvas),
old = this.pointers.get(e.pointerId)!;
if (this.pointers.size === 2) {
const other = [...this.pointers.entries()].find(([id]) => id !== e.pointerId)![1];
const before = Math.hypot(old[0] - other[0], old[1] - other[1]),
after = Math.hypot(p[0] - other[0], p[1] - other[1]);
if (before > 5) this.zoom(canvas === this.model ? 'model' : 'paper', after / before);
const pan = canvas === this.model ? this.modelPan : this.paperPan;
pan[0] += (p[0] - old[0]) / 2;
pan[1] += (p[1] - old[1]) / 2;
this.pointers.set(e.pointerId, p);
this.draw();
return;
}
this.pointers.set(e.pointerId, p);
const drag = this.drag;
if (!drag || drag.id !== e.pointerId) return;
const delta: V2 = [p[0] - drag.last[0], p[1] - drag.last[1]];
if (!drag.moved && Math.hypot(p[0] - drag.start[0], p[1] - drag.start[1]) < 4) return;
if (
!drag.moved &&
canvas === this.paper &&
drag.piece >= 0 &&
this.state().mode === 'select' &&
!this.state().preview
)
this.events.startMove();
drag.moved = true;
if (canvas === this.model) {
if (drag.pan) {
this.modelPan[0] += delta[0];
this.modelPan[1] += delta[1];
} else this.orbit(delta[0] * 0.01, delta[1] * 0.01);
} else if (drag.piece >= 0 && this.state().mode === 'select' && !this.state().preview)
this.events.move(
drag.piece,
delta[0] / this.pageTransform.scale,
delta[1] / this.pageTransform.scale,
);
else {
this.paperPan[0] += delta[0];
this.paperPan[1] += delta[1];
}
drag.last = p;
this.draw();
}
private up(e: PointerEvent, canvas: HTMLCanvasElement) {
if (this.transforming?.id === e.pointerId) {
const commit = this.transforming.moved;
this.transforming = undefined;
this.events.transformEnd(commit);
canvas.style.cursor = '';
if (canvas.hasPointerCapture(e.pointerId)) canvas.releasePointerCapture(e.pointerId);
this.draw();
return;
}
const drag = this.drag;
this.pointers.delete(e.pointerId);
if (drag && drag.id === e.pointerId) {
if (!drag.moved && !drag.pan) {
const hit = this.hit(this.point(e, canvas), canvas);
if (hit.face >= 0)
this.events.select(hit.face, hit.edge, hit.vertex, e.ctrlKey || e.metaKey);
} else if (canvas === this.paper) this.events.endMove();
this.drag = undefined;
}
if (canvas.hasPointerCapture(e.pointerId)) canvas.releasePointerCapture(e.pointerId);
if (!this.pointers.size) this.cancel();
}
private cancel() {
if (this.transforming) {
this.transforming = undefined;
this.events.transformEnd(false);
this.model.style.cursor = '';
this.draw();
}
if (this.drag?.moved) this.events.endMove();
this.drag = undefined;
this.pointers.clear();
}
}
