Release SketchForge 0.5 edge tools

This commit is contained in:
Formsmith
2026-07-05 12:28:23 +03:00
parent f18bacf3ad
commit 5b0ea94e7b
38 changed files with 3973 additions and 519 deletions
File diff suppressed because it is too large Load Diff
+265 -38
View File
@@ -3,6 +3,7 @@
import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react";
import { SnapGridControl } from "@/components/workplane/ShapeInspector";
import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import type { GridSize, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -22,6 +23,7 @@ type SketchWorkspaceProps = {
activePointId: string | null;
selected: SketchSelection;
measurement: SketchMeasurement;
pendingMeasurementStart: SketchPoint | null;
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void;
@@ -42,6 +44,7 @@ type SketchWorkspaceProps = {
type PathStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
type DisplayPath = { id: string; points: SketchPoint[]; steps: PathStep[]; closed: boolean };
type SketchReferenceFootprint = { fillD: string | null; outlineD: string | null };
type PointerAction =
| { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
| { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } }
@@ -123,6 +126,14 @@ function formatDimension(value: number, accuracy: 1 | 2 | 3) {
return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy);
}
function dimensionPillSize(label: string, screenUnit: number, extra = 24) {
return {
width: Math.max(48, label.length * 7.5 + extra) * screenUnit,
height: 26 * screenUnit,
radius: 5 * screenUnit,
};
}
function cubicPoint(start: SketchPoint, first: { x: number; z: number }, second: { x: number; z: number }, end: SketchPoint, amount: number) {
const inverse = 1 - amount;
return {
@@ -239,6 +250,152 @@ function isRoundReference(shape: WorkplaneShape) {
return ["cylinder", "sphere", "cone", "torus", "tube", "ring", "halfSphere"].includes(shape.kind);
}
function sketchReferencePoint(shape: WorkplaneShape, x: number, z: number) {
return {
x: shape.x + x * mirrorSign(shape.mirrorX),
z: shape.z + z * mirrorSign(shape.mirrorZ),
};
}
function pointKey(point: { x: number; z: number }, tolerance: number) {
return `${Math.round(point.x / tolerance)},${Math.round(point.z / tolerance)}`;
}
function triangleArea2d(a: { x: number; z: number }, b: { x: number; z: number }, c: { x: number; z: number }) {
return Math.abs((b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z)) / 2;
}
function trianglePath(points: Array<{ x: number; z: number }>) {
return `M ${points[0].x} ${points[0].z} L ${points[1].x} ${points[1].z} L ${points[2].x} ${points[2].z} Z`;
}
function convexHull(points: Array<{ x: number; z: number }>) {
const unique = new Map<string, { x: number; z: number }>();
points.forEach((point) => unique.set(pointKey(point, 0.001), point));
const sorted = [...unique.values()].sort((a, b) => a.x === b.x ? a.z - b.z : a.x - b.x);
if (sorted.length <= 2) return sorted;
const cross = (origin: { x: number; z: number }, a: { x: number; z: number }, b: { x: number; z: number }) =>
(a.x - origin.x) * (b.z - origin.z) - (a.z - origin.z) * (b.x - origin.x);
const lower: Array<{ x: number; z: number }> = [];
sorted.forEach((point) => {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], point) <= 0) lower.pop();
lower.push(point);
});
const upper: Array<{ x: number; z: number }> = [];
[...sorted].reverse().forEach((point) => {
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], point) <= 0) upper.pop();
upper.push(point);
});
lower.pop();
upper.pop();
return [...lower, ...upper];
}
function boundaryPath(points: Array<{ x: number; z: number }>, triangles: number[][], tolerance: number) {
const pointByKey = new Map<string, { x: number; z: number }>();
const edgeCounts = new Map<string, { count: number; a: string; b: string }>();
const addEdge = (aIndex: number, bIndex: number) => {
const a = points[aIndex];
const b = points[bIndex];
const aKey = pointKey(a, tolerance);
const bKey = pointKey(b, tolerance);
pointByKey.set(aKey, a);
pointByKey.set(bKey, b);
const key = aKey < bKey ? `${aKey}|${bKey}` : `${bKey}|${aKey}`;
const current = edgeCounts.get(key);
edgeCounts.set(key, current ? { ...current, count: current.count + 1 } : { count: 1, a: aKey, b: bKey });
};
triangles.forEach(([a, b, c]) => {
addEdge(a, b);
addEdge(b, c);
addEdge(c, a);
});
const boundaryEdges = [...edgeCounts.values()].filter((edge) => edge.count === 1);
if (boundaryEdges.length === 0) return null;
const adjacency = new Map<string, string[]>();
boundaryEdges.forEach(({ a, b }) => {
adjacency.set(a, [...(adjacency.get(a) ?? []), b]);
adjacency.set(b, [...(adjacency.get(b) ?? []), a]);
});
const unused = new Set(boundaryEdges.map(({ a, b }) => (a < b ? `${a}|${b}` : `${b}|${a}`)));
const takeEdge = (a: string, b: string) => unused.delete(a < b ? `${a}|${b}` : `${b}|${a}`);
const hasEdge = (a: string, b: string) => unused.has(a < b ? `${a}|${b}` : `${b}|${a}`);
const commands: string[] = [];
while (unused.size > 0) {
const firstKey = unused.values().next().value as string;
const [start, firstNext] = firstKey.split("|");
const chain = [start, firstNext];
takeEdge(start, firstNext);
while (chain.length <= boundaryEdges.length + 1) {
const current = chain[chain.length - 1];
const previous = chain[chain.length - 2];
const next = (adjacency.get(current) ?? []).find((candidate) => candidate !== previous && hasEdge(current, candidate))
?? (adjacency.get(current) ?? []).find((candidate) => hasEdge(current, candidate));
if (!next) break;
takeEdge(current, next);
chain.push(next);
if (next === start) break;
}
const startPoint = pointByKey.get(chain[0]);
if (!startPoint) continue;
const pointsD = chain
.slice(1)
.map((key) => pointByKey.get(key))
.filter((point): point is { x: number; z: number } => Boolean(point))
.map((point) => `L ${point.x} ${point.z}`);
commands.push(`M ${startPoint.x} ${startPoint.z} ${pointsD.join(" ")}${chain[chain.length - 1] === chain[0] ? " Z" : ""}`);
}
return commands.join(" ");
}
function importedMeshFootprint(shape: WorkplaneShape): SketchReferenceFootprint | null {
if (!shape.importedMesh) return null;
const positions = resizedImportedMeshPositions(shape);
if (positions.length < 9) return null;
let minY = Number.POSITIVE_INFINITY;
for (let index = 1; index < positions.length; index += 3) {
minY = Math.min(minY, positions[index]);
}
if (!Number.isFinite(minY)) return null;
const tolerance = Math.max(0.001, Math.max(shape.width, shape.depth, shape.height) / 100000);
const bottomTolerance = Math.max(0.025, shape.height * 0.003);
const points: Array<{ x: number; z: number }> = [];
const triangles: number[][] = [];
const allProjected: Array<{ x: number; z: number }> = [];
for (let index = 0; index + 8 < positions.length; index += 9) {
const ys = [positions[index + 1], positions[index + 4], positions[index + 7]];
const projected = [
sketchReferencePoint(shape, positions[index], positions[index + 2]),
sketchReferencePoint(shape, positions[index + 3], positions[index + 5]),
sketchReferencePoint(shape, positions[index + 6], positions[index + 8]),
];
allProjected.push(...projected);
if (!ys.every((value) => value <= minY + bottomTolerance) || triangleArea2d(projected[0], projected[1], projected[2]) <= tolerance) {
continue;
}
const offset = points.length;
points.push(...projected);
triangles.push([offset, offset + 1, offset + 2]);
}
if (triangles.length > 0) {
return {
fillD: triangles.length <= 5000 ? triangles.map((triangle) => trianglePath(triangle.map((index) => points[index]))).join(" ") : null,
outlineD: boundaryPath(points, triangles, tolerance),
};
}
const hull = convexHull(allProjected);
if (hull.length < 3) return null;
const d = `M ${hull[0].x} ${hull[0].z} ${hull.slice(1).map((point) => `L ${point.x} ${point.z}`).join(" ")} Z`;
return { fillD: d, outlineD: d };
}
export function SketchWorkspace({
profile,
referenceShapes,
@@ -246,6 +403,7 @@ export function SketchWorkspace({
activePointId,
selected,
measurement,
pendingMeasurementStart,
initialSnap,
initialWorkspace,
onPlanePoint,
@@ -270,9 +428,17 @@ export function SketchWorkspace({
const [pan, setPan] = useState({ x: 0, z: 0 });
const [hover, setHover] = useState<{ x: number; z: number } | null>(null);
const [pointerAction, setPointerAction] = useState<PointerAction | null>(null);
const [svgSize, setSvgSize] = useState({ width: 0, height: 0 });
const svgRef = useRef<SVGSVGElement | null>(null);
const width = workspace.width / zoom;
const depth = workspace.depth / zoom;
const screenUnit = useMemo(() => {
const fittedScale = Math.min(
svgSize.width > 0 ? svgSize.width / width : 0,
svgSize.height > 0 ? svgSize.height / depth : 0,
);
return fittedScale > 0 ? 1 / fittedScale : Math.max(width, depth) / 720;
}, [depth, svgSize.height, svgSize.width, width]);
const displayProfile = useMemo(() => {
if (pointerAction?.kind === "move-point") {
const source = profile.points.find((point) => point.id === pointerAction.pointId);
@@ -356,6 +522,19 @@ export function SketchWorkspace({
};
};
useEffect(() => {
const svg = svgRef.current;
if (!svg) return;
const updateSize = () => {
const bounds = svg.getBoundingClientRect();
setSvgSize({ width: bounds.width, height: bounds.height });
};
updateSize();
const observer = new ResizeObserver(updateSize);
observer.observe(svg);
return () => observer.disconnect();
}, []);
const beginPan = (event: ReactPointerEvent<SVGElement>) => {
event.preventDefault();
event.stopPropagation();
@@ -472,7 +651,12 @@ export function SketchWorkspace({
const measurementLabel = formatDimension(measurementLength, workspace.accuracy);
const previewLength = activePoint && hover ? Math.hypot(hover.x - activePoint.x, hover.z - activePoint.z) : 0;
const previewLabel = formatDimension(previewLength, workspace.accuracy);
const pillScale = 1 / zoom;
const labelOffset = 22 * screenUnit;
const pointRadius = 5 * screenUnit;
const controlPointRadius = 6 * screenUnit;
const hoverPointRadius = 5 * screenUnit;
const handleSize = 12 * screenUnit;
const handleRadius = 2 * screenUnit;
const selectedImageBounds = selectedImage ? {
minX: selectedImage.x - selectedImage.width / 2,
maxX: selectedImage.x + selectedImage.width / 2,
@@ -489,6 +673,10 @@ export function SketchWorkspace({
{ id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ },
{ id: "w", x: selectedImageBounds.minX, z: selectedImage.z },
] : [];
const referenceFootprints = useMemo(
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
[referenceShapes],
);
return (
<main className="sketch-workspace-stage">
@@ -556,15 +744,23 @@ export function SketchWorkspace({
))}
</g>
<g className="sketch-reference-shapes" pointerEvents="none">
{referenceShapes.filter((shape) => !shape.hidden).map((shape) => (
<g key={shape.id} transform={`rotate(${shape.rotation ?? 0} ${shape.x} ${shape.z})`}>
{isRoundReference(shape) ? (
<ellipse cx={shape.x} cy={shape.z} rx={shape.width / 2} ry={shape.depth / 2} />
) : (
<rect x={shape.x - shape.width / 2} y={shape.z - shape.depth / 2} width={shape.width} height={shape.depth} />
)}
</g>
))}
{referenceShapes.filter((shape) => !shape.hidden).map((shape) => {
const footprint = referenceFootprints.get(shape.id);
return (
<g key={shape.id} transform={`rotate(${shape.rotation ?? 0} ${shape.x} ${shape.z})`}>
{footprint?.fillD || footprint?.outlineD ? (
<>
{footprint.fillD ? <path className="sketch-reference-mesh-face" d={footprint.fillD} /> : null}
{footprint.outlineD ? <path className="sketch-reference-mesh-outline" d={footprint.outlineD} /> : null}
</>
) : isRoundReference(shape) ? (
<ellipse cx={shape.x} cy={shape.z} rx={shape.width / 2} ry={shape.depth / 2} />
) : (
<rect x={shape.x - shape.width / 2} y={shape.z - shape.depth / 2} width={shape.width} height={shape.depth} />
)}
</g>
);
})}
</g>
<rect className="sketch-plate-border" x={-workspace.width / 2} y={-workspace.depth / 2} width={workspace.width} height={workspace.depth} pointerEvents="none" />
{pointerAction?.kind === "marquee" ? (
@@ -604,53 +800,68 @@ export function SketchWorkspace({
const dimension = segmentDimension(segment, pointById);
if (!dimension) return null;
const label = formatDimension(dimension.length, workspace.accuracy);
const pillWidth = Math.max(7.2, label.length * 1.2 + 2.4) * pillScale;
const pillHeight = 4.2 * pillScale;
const pill = dimensionPillSize(label, screenUnit, 18);
return (
<g key={`dimension-${segment.id}`} transform={`translate(${dimension.midpoint.x} ${dimension.midpoint.z - 4 * pillScale})`}>
<rect x={-pillWidth / 2} y={-pillHeight / 2} width={pillWidth} height={pillHeight} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{label}</text>
<g key={`dimension-${segment.id}`} transform={`translate(${dimension.midpoint.x} ${dimension.midpoint.z - labelOffset})`}>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{label}</text>
</g>
);
})}
</g>
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? <line className="sketch-preview-line" x1={activePoint.x} y1={activePoint.z} x2={hover.x} y2={hover.z} pointerEvents="none" /> : null}
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? (
<g className="sketch-segment-dimensions preview" pointerEvents="none" transform={`translate(${(activePoint.x + hover.x) / 2} ${(activePoint.z + hover.z) / 2 - 4 * pillScale})`}>
<rect x={-(Math.max(7.2, previewLabel.length * 1.2 + 2.4) * pillScale) / 2} y={-(4.2 * pillScale) / 2} width={Math.max(7.2, previewLabel.length * 1.2 + 2.4) * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{previewLabel}</text>
<g className="sketch-segment-dimensions preview" pointerEvents="none" transform={`translate(${(activePoint.x + hover.x) / 2} ${(activePoint.z + hover.z) / 2 - labelOffset})`}>
{(() => {
const pill = dimensionPillSize(previewLabel, screenUnit, 18);
return (
<>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{previewLabel}</text>
</>
);
})()}
</g>
) : null}
{pointerAction?.kind === "bezier" ? (
<g className="sketch-drag-handles" pointerEvents="none">
<line x1={pointerAction.origin.x * 2 - pointerAction.current.x} y1={pointerAction.origin.z * 2 - pointerAction.current.z} x2={pointerAction.current.x} y2={pointerAction.current.z} />
<circle cx={pointerAction.origin.x} cy={pointerAction.origin.z} r={1.2 / Math.sqrt(zoom)} />
<circle cx={pointerAction.origin.x} cy={pointerAction.origin.z} r={controlPointRadius} />
</g>
) : null}
{measurement ? (
<g className="sketch-measurement">
<line x1={measurement.start.x} y1={measurement.start.z} x2={measurement.end.x} y2={measurement.end.z} />
<circle className="sketch-measurement-point" cx={measurement.start.x} cy={measurement.start.z} r={pointRadius} pointerEvents="none" />
<circle className="sketch-measurement-point" cx={measurement.end.x} cy={measurement.end.z} r={pointRadius} pointerEvents="none" />
<g
className="sketch-measurement-pill"
role="button"
aria-label="Remove measurement"
transform={`translate(${(measurement.start.x + measurement.end.x) / 2} ${(measurement.start.z + measurement.end.z) / 2 - 4 * pillScale})`}
transform={`translate(${(measurement.start.x + measurement.end.x) / 2} ${(measurement.start.z + measurement.end.z) / 2 - labelOffset})`}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
onClearMeasurement();
}}
>
<rect x={-(Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale) / 2} y={-(4.2 * pillScale) / 2} width={Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text x={-0.9 * pillScale} y={0.78 * pillScale} fontSize={2.25 * pillScale}>{measurementLabel}</text>
<text className="remove" x={(Math.max(9, measurementLabel.length * 1.2 + 4.2) * pillScale) / 2 - 1.45 * pillScale} y={0.82 * pillScale} fontSize={2.45 * pillScale}>×</text>
<rect x={-dimensionPillSize(measurementLabel, screenUnit, 30).width / 2} y={-dimensionPillSize(measurementLabel, screenUnit, 30).height / 2} width={dimensionPillSize(measurementLabel, screenUnit, 30).width} height={dimensionPillSize(measurementLabel, screenUnit, 30).height} rx={dimensionPillSize(measurementLabel, screenUnit, 30).radius} />
<text x={-5 * screenUnit} y={5 * screenUnit} fontSize={13 * screenUnit}>{measurementLabel}</text>
<text className="remove" x={dimensionPillSize(measurementLabel, screenUnit, 30).width / 2 - 8 * screenUnit} y={5 * screenUnit} fontSize={14 * screenUnit}>x</text>
</g>
</g>
) : null}
{pendingMeasurementStart ? (
<g className="sketch-measurement pending" pointerEvents="none">
{hover ? <line x1={pendingMeasurementStart.x} y1={pendingMeasurementStart.z} x2={hover.x} y2={hover.z} /> : null}
<circle className="sketch-measurement-point pending" cx={pendingMeasurementStart.x} cy={pendingMeasurementStart.z} r={pointRadius} />
{hover ? <circle className="sketch-measurement-point hover" cx={hover.x} cy={hover.z} r={pointRadius} /> : null}
</g>
) : null}
{selectedPoint && tool === "select" ? (
<g className="sketch-curve-handles">
{selectedPoint.handleIn ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleIn.x} y2={selectedPoint.handleIn.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleIn.x} cy={selectedPoint.handleIn.z} r={1 / Math.sqrt(zoom)} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /></> : null}
{selectedPoint.handleOut ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleOut.x} y2={selectedPoint.handleOut.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleOut.x} cy={selectedPoint.handleOut.z} r={1 / Math.sqrt(zoom)} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /></> : null}
{selectedPoint.handleIn ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleIn.x} y2={selectedPoint.handleIn.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleIn.x} cy={selectedPoint.handleIn.z} r={controlPointRadius} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /></> : null}
{selectedPoint.handleOut ? <><line x1={selectedPoint.x} y1={selectedPoint.z} x2={selectedPoint.handleOut.x} y2={selectedPoint.handleOut.z} /><circle data-sketch-entity="handle" cx={selectedPoint.handleOut.x} cy={selectedPoint.handleOut.z} r={controlPointRadius} onPointerDown={(event) => event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /></> : null}
</g>
) : null}
<g className="sketch-points">
@@ -661,7 +872,7 @@ export function SketchWorkspace({
key={point.id}
cx={point.x}
cy={point.z}
r={0.82 / Math.sqrt(zoom)}
r={pointRadius}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
@@ -689,24 +900,40 @@ export function SketchWorkspace({
height={selectedImage.depth}
pointerEvents="none"
/>
<g className="sketch-image-dimension width" pointerEvents="none" transform={`translate(${selectedImage.x} ${selectedImageBounds.minZ - 4 * pillScale})`}>
<rect x={-6 * pillScale} y={-2.1 * pillScale} width={12 * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{formatDimension(selectedImage.width, workspace.accuracy)}</text>
<g className="sketch-image-dimension width" pointerEvents="none" transform={`translate(${selectedImage.x} ${selectedImageBounds.minZ - labelOffset})`}>
{(() => {
const label = formatDimension(selectedImage.width, workspace.accuracy);
const pill = dimensionPillSize(label, screenUnit, 18);
return (
<>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{label}</text>
</>
);
})()}
</g>
<g className="sketch-image-dimension depth" pointerEvents="none" transform={`translate(${selectedImageBounds.maxX + 7 * pillScale} ${selectedImage.z})`}>
<rect x={-6 * pillScale} y={-2.1 * pillScale} width={12 * pillScale} height={4.2 * pillScale} rx={0.55 * pillScale} />
<text y={0.78 * pillScale} fontSize={2.25 * pillScale}>{formatDimension(selectedImage.depth, workspace.accuracy)}</text>
<g className="sketch-image-dimension depth" pointerEvents="none" transform={`translate(${selectedImageBounds.maxX + 34 * screenUnit} ${selectedImage.z})`}>
{(() => {
const label = formatDimension(selectedImage.depth, workspace.accuracy);
const pill = dimensionPillSize(label, screenUnit, 18);
return (
<>
<rect x={-pill.width / 2} y={-pill.height / 2} width={pill.width} height={pill.height} rx={pill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{label}</text>
</>
);
})()}
</g>
{imageResizeHandles.map((handle) => (
<rect
key={handle.id}
data-sketch-entity="image-handle"
className={`sketch-image-resize-handle handle-${handle.id}`}
x={handle.x - 1.05 * pillScale}
y={handle.z - 1.05 * pillScale}
width={2.1 * pillScale}
height={2.1 * pillScale}
rx={0.2 * pillScale}
x={handle.x - handleSize / 2}
y={handle.z - handleSize / 2}
width={handleSize}
height={handleSize}
rx={handleRadius}
onPointerDown={(event) => {
if (event.button === 1) {
beginPan(event);
@@ -728,7 +955,7 @@ export function SketchWorkspace({
))}
</g>
) : null}
{hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? <circle className="sketch-cursor-point" cx={hover.x} cy={hover.z} r={0.7 / Math.sqrt(zoom)} pointerEvents="none" /> : null}
{hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? <circle className="sketch-cursor-point" cx={hover.x} cy={hover.z} r={hoverPointRadius} pointerEvents="none" /> : null}
</svg>
</section>
{selectedImage && tool === "select" ? (
+158 -36
View File
@@ -19,6 +19,7 @@ import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } fro
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
import {
TransformOverlay,
getElevationMeasureKey,
@@ -89,6 +90,7 @@ const preservedImportedGeometryCache = new WeakMap<WorkplaneShape, THREE.BufferG
const imageTextureLoader = new THREE.TextureLoader();
const IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT = 40000;
const NORMAL_IMPORTED_SELECTION_EDGE_ANGLE = 60;
const MODIFIER_EDGE_PICK_RADIUS_PX = 14;
function parseDroppedShapeAsset(raw: string): ShapeAsset | null {
try {
@@ -146,6 +148,8 @@ type WorkplaneViewportProps = {
onSetPlacementElevation: (elevation: number, source: "shape" | "base") => void;
onInteractionActiveChange?: (active: boolean) => void;
onEditSketch?: () => void;
canSeparateParts?: boolean;
onSeparateParts?: () => void;
onUpdateShape: (id: string, patch: ShapeUpdatePatch) => void;
onWorkspaceSettingsChange?: (settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void;
onWorkplaneModeChange: (active: boolean) => void;
@@ -219,6 +223,7 @@ declare global {
get: () => ViewportPerfStats;
};
sketchforgeCaptureCanvas?: () => string;
sketchforgeCaptureView?: (face?: SketchForgeMcpViewFace) => Promise<string> | string;
}
}
@@ -523,6 +528,51 @@ function projectToScreen(point: THREE.Vector3, state: ThreeState) {
};
}
function distanceToScreenSegment(x: number, y: number, ax: number, ay: number, bx: number, by: number) {
const dx = bx - ax;
const dy = by - ay;
const lengthSq = dx * dx + dy * dy;
const amount = lengthSq > 0.0001 ? clamp(((x - ax) * dx + (y - ay) * dy) / lengthSq, 0, 1) : 0;
return Math.hypot(x - (ax + dx * amount), y - (ay + dy * amount));
}
function projectCadPointToCanvas(point: THREE.Vector3, state: ThreeState, rect: DOMRect) {
const projected = point.clone().project(state.camera);
if (!Number.isFinite(projected.x) || !Number.isFinite(projected.y) || projected.z < -1 || projected.z > 1) {
return null;
}
return {
x: ((projected.x + 1) / 2) * rect.width,
y: ((1 - projected.y) / 2) * rect.height,
};
}
function pickModifierEdgeFromScreen(state: ThreeState, edges: CadModifierEdge[], clientX: number, clientY: number) {
const rect = state.renderer.domElement.getBoundingClientRect();
const pointerX = clientX - rect.left;
const pointerY = clientY - rect.top;
const pointA = new THREE.Vector3();
const pointB = new THREE.Vector3();
let nearestId: number | null = null;
let nearestDistance = MODIFIER_EDGE_PICK_RADIUS_PX;
state.camera.updateMatrixWorld();
edges.forEach((edge) => {
for (let index = 0; index + 5 < edge.points.length; index += 3) {
pointA.set(edge.points[index], edge.points[index + 1], edge.points[index + 2]);
pointB.set(edge.points[index + 3], edge.points[index + 4], edge.points[index + 5]);
const a = projectCadPointToCanvas(pointA, state, rect);
const b = projectCadPointToCanvas(pointB, state, rect);
if (!a || !b) continue;
const distance = distanceToScreenSegment(pointerX, pointerY, a.x, a.y, b.x, b.y);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestId = edge.id;
}
}
});
return nearestId;
}
function syncRulerOverlay(
state: ThreeState,
model: RulerModel,
@@ -1112,6 +1162,8 @@ export function WorkplaneViewport({
onSetPlacementElevation,
onInteractionActiveChange,
onEditSketch,
canSeparateParts = false,
onSeparateParts,
onUpdateShape,
onWorkspaceSettingsChange,
onWorkplaneModeChange,
@@ -1170,6 +1222,8 @@ export function WorkplaneViewport({
const mirrorModeRef = useRef(mirrorMode);
const modifierActiveRef = useRef(modifierActive);
const modifierPreviewActiveRef = useRef(modifierPreviewActive);
const modifierEdgesRef = useRef(modifierEdges);
const [hoverModifierEdgeId, setHoverModifierEdgeId] = useState<number | null>(null);
const selectedIdsKeyRef = useRef(selectedIds.join("|"));
const perfRef = useRef({
fps: 0,
@@ -1186,8 +1240,9 @@ export function WorkplaneViewport({
);
useEffect(() => {
rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive);
}, [modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]);
modifierEdgesRef.current = modifierEdges;
rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive, hoverModifierEdgeId);
}, [hoverModifierEdgeId, modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]);
const placementElevationRef = useRef(placementElevation);
const workplaneModeRef = useRef(workplaneMode);
@@ -1259,10 +1314,11 @@ export function WorkplaneViewport({
useEffect(() => {
shapesRef.current = shapes;
rebuildShapes(threeRef.current, shapes, renderSelectionIds(), !transformRef.current && !dragRef.current);
refreshDragPreviewObjects(threeRef.current, dragRef.current);
if (threeRef.current) {
syncTransformOverlay(
threeRef.current,
shapes,
previewShapesForDrag(shapes, dragRef.current),
selectedIdsRef.current,
transformOverlayRef,
setTransformOverlay,
@@ -1306,10 +1362,11 @@ export function WorkplaneViewport({
}
selectedIdsRef.current = selectedIds;
rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(selectedIds), !transformRef.current && !dragRef.current);
refreshDragPreviewObjects(threeRef.current, dragRef.current);
if (threeRef.current) {
syncTransformOverlay(
threeRef.current,
shapesRef.current,
previewShapesForDrag(shapesRef.current, dragRef.current),
selectedIds,
transformOverlayRef,
setTransformOverlay,
@@ -1324,6 +1381,7 @@ export function WorkplaneViewport({
useEffect(() => {
modifierActiveRef.current = modifierActive;
if (!modifierActive) setHoverModifierEdgeId(null);
rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current);
if (threeRef.current) threeRef.current.needsRender = true;
}, [modifierActive, renderSelectionIds]);
@@ -1334,6 +1392,12 @@ export function WorkplaneViewport({
if (threeRef.current) threeRef.current.needsRender = true;
}, [modifierPreviewActive, renderSelectionIds]);
useEffect(() => {
if (hoverModifierEdgeId !== null && !modifierEdges.some((edge) => edge.id === hoverModifierEdgeId)) {
setHoverModifierEdgeId(null);
}
}, [hoverModifierEdgeId, modifierEdges]);
useEffect(() => {
alignModeRef.current = alignMode;
alignAnchorIdRef.current = alignAnchorId;
@@ -1411,6 +1475,17 @@ export function WorkplaneViewport({
state.renderer.render(state.scene, state.camera);
return state.renderer.domElement.toDataURL("image/png");
};
window.sketchforgeCaptureView = (face = "current") => {
if (face === "home") {
resetCamera(state);
} else if (face !== "current") {
setCameraToViewFace(state, face);
}
syncViewCube(state, viewCubeRef.current);
state.camera.updateMatrixWorld();
state.renderer.render(state.scene, state.camera);
return state.renderer.domElement.toDataURL("image/png");
};
perfRef.current.lastSample = performance.now();
resetCamera(state);
rebuildShapes(state, shapesRef.current, renderSelectionIds());
@@ -1483,6 +1558,9 @@ export function WorkplaneViewport({
if (window.sketchforgeCaptureCanvas) {
delete window.sketchforgeCaptureCanvas;
}
if (window.sketchforgeCaptureView) {
delete window.sketchforgeCaptureView;
}
threeRef.current = null;
};
}, []);
@@ -2199,14 +2277,16 @@ export function WorkplaneViewport({
const pickModifierEdge = useCallback((clientX: number, clientY: number) => {
const state = threeRef.current;
if (!state) return null;
const rect = state.renderer.domElement.getBoundingClientRect();
state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
state.raycaster.setFromCamera(state.pointer, state.camera);
const hit = state.raycaster
.intersectObjects(state.modifierLayer.children, true)
.find((entry) => typeof entry.object.userData.modifierEdgeId === "number");
return hit ? hit.object.userData.modifierEdgeId as number : null;
return pickModifierEdgeFromScreen(state, modifierEdgesRef.current, clientX, clientY);
}, []);
const updateModifierEdgeHover = useCallback((clientX: number, clientY: number) => {
const edgeId = pickModifierEdge(clientX, clientY);
setHoverModifierEdgeId((current) => (current === edgeId ? current : edgeId));
}, [pickModifierEdge]);
const clearModifierEdgeHover = useCallback(() => {
setHoverModifierEdgeId((current) => (current === null ? current : null));
}, []);
const pickTransformHandle = useCallback((clientX: number, clientY: number) => {
@@ -2497,6 +2577,10 @@ export function WorkplaneViewport({
const handlePointerMove = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (modifierActiveRef.current) {
updateModifierEdgeHover(event.clientX, event.clientY);
return;
}
if (rulerModeRef.current) {
updateRulerHover(event.clientX, event.clientY);
return;
@@ -2542,21 +2626,7 @@ export function WorkplaneViewport({
drag.items.forEach((item) => {
item.nextX = clamp(item.startX + deltaX, -workspaceRef.current.width / 2 + 6, workspaceRef.current.width / 2 - 6);
item.nextZ = clamp(item.startZ + deltaZ, -workspaceRef.current.depth / 2 + 6, workspaceRef.current.depth / 2 - 6);
if (item.visual) {
if (!item.hadPreviewSimplified) {
setComplexEdgeVisibility(item.visual, false);
item.hadPreviewSimplified = true;
}
item.visual.position.x = item.nextX;
item.visual.position.z = item.nextZ;
}
if (item.helper && item.helperBox) {
item.helper.box.copy(item.helperBox);
item.helper.box.translate(new THREE.Vector3(item.nextX - item.startX, 0, item.nextZ - item.startZ));
item.helper.updateMatrixWorld(true);
}
if (threeRef.current) applyDragItemPreview(threeRef.current, item);
});
if (threeRef.current) {
const previewShapes = previewShapesForDrag(shapesRef.current, drag);
@@ -2574,9 +2644,13 @@ export function WorkplaneViewport({
threeRef.current.needsRender = true;
}
},
[setMarqueeFromState, toPlanePoint, updateRulerHover, updateTransform],
[setMarqueeFromState, toPlanePoint, updateModifierEdgeHover, updateRulerHover, updateTransform],
);
const handlePointerLeave = useCallback(() => {
if (modifierActiveRef.current) clearModifierEdgeHover();
}, [clearModifierEdgeHover]);
const finishDrag = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const state = threeRef.current;
@@ -2846,7 +2920,7 @@ export function WorkplaneViewport({
</button>
</div>
<section className={`workplane-wrap ${workplaneMode ? "placing-workplane" : ""} ${rulerMode ? "ruler-mode" : ""}`} aria-label="Workplane">
<section className={`workplane-wrap ${workplaneMode ? "placing-workplane" : ""} ${rulerMode ? "ruler-mode" : ""} ${modifierActive ? "modifier-edge-pick" : ""}`} aria-label="Workplane">
<div className="workplane-plane">
<div
className="three-workplane-host"
@@ -2860,6 +2934,7 @@ export function WorkplaneViewport({
onPointerMove={handlePointerMove}
onPointerUp={finishDrag}
onPointerCancel={finishDrag}
onPointerLeave={handlePointerLeave}
/>
{marqueeRect ? <div className="selection-marquee" style={marqueeRect} /> : null}
{transformOverlay && !alignMode && !mirrorMode && !rulerMode && !modifierActive ? (
@@ -2909,12 +2984,14 @@ export function WorkplaneViewport({
shape={selectedShape}
snap={snap}
snapOpen={snapOpen}
accuracy={workspace.accuracy}
workspace={workspace}
onUpdate={(patch, options) => onUpdateShape(selectedShape.id, patchWithResizeAnchor(selectedShape, patch, options?.resizeAxis, lastResizeAnchorRef.current))}
onClose={() => onSelectShape(null)}
onSnapChange={setSnap}
onSnapOpenChange={setSnapOpen}
onEditSketch={selectedShape.sketchProfile ? onEditSketch : undefined}
canSeparateParts={canSeparateParts}
onSeparateParts={onSeparateParts}
/>
) : null}
@@ -3442,7 +3519,16 @@ function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selec
rebuildSelectionHelpers(state, shapes, selectedIds);
}
function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[], selectedIds: number[], previewActive = false) {
function modifierEdgeMaterialStyle(active: boolean, hovered: boolean, previewActive: boolean) {
const subduedSelectedPreviewEdge = previewActive && active && !hovered;
return {
color: active ? (hovered ? "#ffbf45" : "#ff8a1d") : hovered ? "#84edff" : "#17b7e5",
opacity: subduedSelectedPreviewEdge ? 0.18 : active || hovered ? 1 : 0.72,
linewidth: active || hovered ? 3 : 1,
};
}
function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[], selectedIds: number[], previewActive = false, hoverId: number | null = null) {
if (!state) return;
disposeChildren(state.modifierLayer);
const selected = new Set(selectedIds);
@@ -3451,17 +3537,19 @@ function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[]
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(edge.points, 3));
const active = selected.has(edge.id);
const subduedSelectedPreviewEdge = previewActive && active;
const hovered = hoverId === edge.id;
const style = modifierEdgeMaterialStyle(active, hovered, previewActive);
const material = new THREE.LineBasicMaterial({
color: active ? "#ff8a1d" : "#17b7e5",
color: style.color,
depthTest: false,
depthWrite: false,
transparent: true,
opacity: subduedSelectedPreviewEdge ? 0.18 : active ? 1 : 0.82,
opacity: style.opacity,
linewidth: style.linewidth,
});
const line = new THREE.Line(geometry, material);
line.userData.modifierEdgeId = edge.id;
line.renderOrder = active ? 1002 : 1001;
line.renderOrder = hovered ? 1003 : active ? 1002 : 1001;
state.modifierLayer.add(line);
});
state.needsRender = true;
@@ -4089,6 +4177,39 @@ function findSelectedGroundFootprint(state: ThreeState, id: string) {
return state.helperLayer.children.find((child) => child.name === "SelectedGroundFootprint" && child.userData.shapeId === id) ?? null;
}
function applyDragItemPreview(state: ThreeState, item: DragItem) {
if (!item.visual || !item.visual.parent) {
item.visual = findShapeObject(state, item.id);
}
if (!item.helper || !item.helper.parent) {
item.helper = findSelectionHelper(state, item.id);
item.helperBox = item.helper ? item.helper.box.clone() : null;
}
if (item.visual) {
if (!item.hadPreviewSimplified) {
setComplexEdgeVisibility(item.visual, false);
item.hadPreviewSimplified = true;
}
item.visual.position.x = item.nextX;
item.visual.position.z = item.nextZ;
item.visual.updateMatrixWorld(true);
}
if (item.helper && item.helperBox) {
item.helper.box.copy(item.helperBox);
item.helper.box.translate(new THREE.Vector3(item.nextX - item.startX, 0, item.nextZ - item.startZ));
item.helper.updateMatrixWorld(true);
}
}
function refreshDragPreviewObjects(state: ThreeState | null, drag: DragState | null) {
if (!state || !drag) return;
drag.items.forEach((item) => applyDragItemPreview(state, item));
updateSelectedGroundFootprintPreviews(state, drag);
state.needsRender = true;
}
function updateSelectedGroundFootprintPreviews(state: ThreeState, drag: DragState) {
drag.items.forEach((item) => {
const footprint = findSelectedGroundFootprint(state, item.id);
@@ -4822,8 +4943,9 @@ function createHalfSphereGeometry(width: number, height: number, depth: number,
function disposeChildren(group: THREE.Group) {
while (group.children.length > 0) {
const child = group.children.pop();
const child = group.children[group.children.length - 1];
if (child) {
group.remove(child);
disposeObject(child);
}
}
+4 -16
View File
@@ -148,24 +148,12 @@ export function ToolbarMirrorIcon() {
return <ToolbarCommandImage file="toolbar-mirror.png" className="toolbar-user-art-icon" />;
}
export function ToolbarChamferIcon(props: IconProps) {
return (
<svg viewBox="0 0 48 48" aria-hidden="true" {...props}>
<path d="M12 17 18 11h18v18l-7 7H12Z" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 7 7h17M19 24v12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 6-6" fill="none" stroke="currentColor" strokeWidth="4.5" strokeLinecap="round" />
</svg>
);
export function ToolbarChamferIcon() {
return <ToolbarCommandImage file="toolbar-chamfer.png" className="toolbar-user-art-icon" />;
}
export function ToolbarFilletIcon(props: IconProps) {
return (
<svg viewBox="0 0 48 48" aria-hidden="true" {...props}>
<path d="M12 17c0-3.3 2.7-6 6-6h18v18c0 3.9-3.1 7-7 7H12Z" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="m12 17 7 7h17M19 24v12" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="round" />
<path d="M12 17c0-3.3 2.7-6 6-6" fill="none" stroke="currentColor" strokeWidth="4.5" strokeLinecap="round" />
</svg>
);
export function ToolbarFilletIcon() {
return <ToolbarCommandImage file="toolbar-fillet.png" className="toolbar-user-art-icon" />;
}
export function ToolbarPreserveEdgeIcon(props: IconProps) {
@@ -1,7 +1,128 @@
"use client";
import { Check, LoaderCircle, X } from "lucide-react";
import { useEffect, useState, type CSSProperties } from "react";
import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const MIN_EDGE_MODIFIER_AMOUNT = 0.001;
const EDGE_MODIFIER_AMOUNT_STEP = 0.001;
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function formatSliderValue(value: number, accuracy: WorkplaneWorkspaceSettings["accuracy"], step: number) {
if (step >= 1) return String(Math.round(value));
return formatMeasurementNumber(value, accuracy, step);
}
type EdgeHistoryOption = {
id: string;
label: string;
targetName: string;
removesNewerCount: number;
};
function EdgeModifierSlider({
label,
value,
min,
max,
step,
unit,
workspace,
length = false,
onChange,
}: {
label: string;
value: number;
min: number;
max: number;
step: number;
unit?: string;
workspace: WorkplaneWorkspaceSettings;
length?: boolean;
onChange: (value: number) => void;
}) {
const safeMin = Number.isFinite(min) ? min : 0;
const safeMax = Math.max(safeMin, Number.isFinite(max) ? max : safeMin);
const actualValue = Number.isFinite(value) ? value : safeMin;
const controlValue = length ? millimetersToDisplay(actualValue, workspace) : actualValue;
const controlMin = length ? millimetersToDisplay(safeMin, workspace) : safeMin;
const controlMax = length ? millimetersToDisplay(safeMax, workspace) : safeMax;
const controlStep = length ? displayStepFromMillimeters(step, workspace) : step;
const sliderValue = clamp(controlValue, controlMin, controlMax);
const position = ((sliderValue - controlMin) / Math.max(Number.EPSILON, controlMax - controlMin)) * 100;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatSliderValue(controlValue, workspace.accuracy, controlStep));
const unitLabel = length ? lengthDisplayUnit(workspace).label : unit;
useEffect(() => {
if (!editing) {
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
}
}, [controlStep, controlValue, editing, workspace.accuracy]);
const toModelValue = (nextValue: number) => length ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue;
onChange(clamp(toModelValue(finiteNext), safeMin, safeMax));
setEditing(false);
};
const handleSliderChange = (nextValue: number) => {
const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax);
onChange(clamp(toModelValue(next), safeMin, safeMax));
setDraft(formatSliderValue(next, workspace.accuracy, controlStep));
};
return (
<label className="edge-modifier-field edge-modifier-slider range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
<span className="range-property-header">
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
type="number"
min={controlMin}
max={controlMax}
step={controlStep}
value={editing ? draft : formatSliderValue(controlValue, workspace.accuracy, controlStep)}
inputMode="decimal"
onFocus={() => {
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
setEditing(true);
}}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.currentTarget.blur();
} else if (event.key === "Escape") {
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
setEditing(false);
}
}}
/>
{unitLabel ? <span className="range-value-unit">{unitLabel}</span> : null}
</span>
</span>
<div className="range-control">
<input
type="range"
min={controlMin}
max={controlMax}
step={controlStep}
value={sliderValue}
onChange={(event) => handleSliderChange(Number(event.currentTarget.value))}
/>
</div>
</label>
);
}
export function EdgeModifierPanel({
kind,
@@ -10,12 +131,14 @@ export function EdgeModifierPanel({
chamferAngle,
quality,
sharpAngle,
workspace,
tangentChain,
preserveEdgeSize,
targetName,
groupedCount,
appliedFeatureCount,
reversibleFeatureCount,
historyOptions,
selectedCount,
availableCount,
busy,
@@ -28,7 +151,7 @@ export function EdgeModifierPanel({
onPreserveEdgeSizeChange,
onSelectAll,
onClear,
onRemoveLastFeature,
onRemoveFeature,
onApply,
onCancel,
}: {
@@ -38,12 +161,14 @@ export function EdgeModifierPanel({
chamferAngle: number;
quality: CadModifierQuality;
sharpAngle: number;
workspace: WorkplaneWorkspaceSettings;
tangentChain: boolean;
preserveEdgeSize: boolean;
targetName: string;
groupedCount: number;
appliedFeatureCount: number;
reversibleFeatureCount: number;
historyOptions: EdgeHistoryOption[];
selectedCount: number;
availableCount: number;
busy: boolean;
@@ -56,11 +181,14 @@ export function EdgeModifierPanel({
onPreserveEdgeSizeChange: (value: boolean) => void;
onSelectAll: () => void;
onClear: () => void;
onRemoveLastFeature: () => void;
onRemoveFeature: (id: string) => void;
onApply: () => void;
onCancel: () => void;
}) {
const [historyOpen, setHistoryOpen] = useState(false);
const title = kind === "fillet" ? "Fillet edges" : "Chamfer edges";
const amountMin = Math.min(MIN_EDGE_MODIFIER_AMOUNT, Math.max(Number.EPSILON, maxAmount));
const amountMax = Math.max(amountMin, maxAmount);
return (
<aside className="edge-modifier-panel" aria-label={title}>
<div className="edge-modifier-header">
@@ -87,55 +215,50 @@ export function EdgeModifierPanel({
{appliedFeatureCount > 0 ? (
<div className="edge-modifier-history-actions">
<button type="button" disabled={reversibleFeatureCount === 0} onClick={onRemoveLastFeature}>
Remove last edge feature
<button
className="edge-modifier-history-toggle"
type="button"
aria-expanded={historyOpen}
disabled={reversibleFeatureCount === 0}
onClick={() => setHistoryOpen((open) => !open)}
>
{historyOpen ? <Minus size={15} /> : <Plus size={15} />}
<span>Edge feature history</span>
</button>
{reversibleFeatureCount === 0 ? <span>Older edge features do not have stored undo history.</span> : null}
{historyOpen && historyOptions.length > 0 ? (
<div className="edge-modifier-history-list">
{historyOptions.map((option) => (
<button className="edge-modifier-history-item" type="button" key={option.id} onClick={() => onRemoveFeature(option.id)}>
<RotateCcw size={14} />
<span>
<strong>{option.label}</strong>
<small>
{option.targetName}
{option.removesNewerCount > 0 ? ` · also removes ${option.removesNewerCount} newer` : ""}
</small>
</span>
</button>
))}
</div>
) : null}
</div>
) : null}
<label className="edge-modifier-field">
<span>{kind === "fillet" ? "Radius" : "Distance"}</span>
<div className="edge-modifier-value-row">
<input
type="range"
min="0.05"
max={Math.max(0.05, maxAmount)}
step="0.05"
value={Math.min(amount, maxAmount)}
onChange={(event) => onAmountChange(Number(event.currentTarget.value))}
/>
<input
type="number"
min="0.05"
max={maxAmount}
step="0.05"
value={amount}
onChange={(event) => onAmountChange(Number(event.currentTarget.value))}
/>
<span>mm</span>
</div>
</label>
<EdgeModifierSlider
label={kind === "fillet" ? "Radius" : "Distance"}
value={amount}
min={amountMin}
max={amountMax}
step={EDGE_MODIFIER_AMOUNT_STEP}
workspace={workspace}
length
onChange={onAmountChange}
/>
{kind === "chamfer" ? (
<label className="edge-modifier-field">
<span>Angle</span>
<div className="edge-modifier-value-row">
<input type="range" min="5" max="85" step="1" value={chamferAngle} onChange={(event) => onChamferAngleChange(Number(event.currentTarget.value))} />
<input type="number" min="5" max="85" step="1" value={chamferAngle} onChange={(event) => onChamferAngleChange(Number(event.currentTarget.value))} />
<span>°</span>
</div>
</label>
) : null}
{kind === "chamfer" ? <EdgeModifierSlider label="Angle" value={chamferAngle} min={5} max={85} step={1} unit="deg" workspace={workspace} onChange={onChamferAngleChange} /> : null}
<label className="edge-modifier-field">
<span>Sharp-edge threshold</span>
<div className="edge-modifier-value-row">
<input type="range" min="1" max="120" step="1" value={sharpAngle} onChange={(event) => onSharpAngleChange(Number(event.currentTarget.value))} />
<input type="number" min="1" max="120" step="1" value={sharpAngle} onChange={(event) => onSharpAngleChange(Number(event.currentTarget.value))} />
<span>°</span>
</div>
</label>
<EdgeModifierSlider label="Sharp-edge threshold" value={sharpAngle} min={1} max={120} step={1} unit="deg" workspace={workspace} onChange={onSharpAngleChange} />
<label className="edge-modifier-check">
<input type="checkbox" checked={tangentChain} onChange={(event) => onTangentChainChange(event.currentTarget.checked)} />
@@ -1,10 +1,11 @@
"use client";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen } from "lucide-react";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen, Split } from "lucide-react";
import { useEffect, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { ToolbarHideSelectedIcon } from "@/components/icons";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import { fallbackSolidColor, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { GridSize, MeasurementAccuracy, WorkplaneShape } from "@/types/sketchforge";
import type { GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
const MIN_SHAPE_SIZE = 0.01;
@@ -73,9 +74,13 @@ function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function formatPanelNumber(value: number, accuracy: MeasurementAccuracy) {
const zeroThreshold = 0.5 * 10 ** -accuracy;
return (Math.abs(value) < zeroThreshold ? 0 : value).toFixed(accuracy);
function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step: number) {
if (step >= 1) return String(Math.round(value));
return formatMeasurementNumber(value, accuracy, step);
}
function propertyUsesLengthUnit(label: string) {
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness"].includes(label);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
@@ -92,8 +97,6 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
if (shape.kind === "box") {
return [
{ label: "Radius", value: shape.radius ?? 0, min: 0, max: 10, onChange: (radius) => onUpdate({ radius }) },
{ label: "Steps", value: shape.steps ?? 10, min: 1, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
@@ -197,22 +200,26 @@ export function ShapeInspector({
shape,
snap,
snapOpen,
accuracy,
workspace,
onUpdate,
onClose,
onSnapChange,
onSnapOpenChange,
onEditSketch,
canSeparateParts = false,
onSeparateParts,
}: {
shape: WorkplaneShape;
snap: GridSize;
snapOpen: boolean;
accuracy: MeasurementAccuracy;
workspace: WorkplaneWorkspaceSettings;
onUpdate: ShapeInspectorUpdate;
onClose: () => void;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
onEditSketch?: () => void;
canSeparateParts?: boolean;
onSeparateParts?: () => void;
}) {
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
@@ -310,6 +317,13 @@ export function ShapeInspector({
</button>
) : null}
{canSeparateParts && onSeparateParts ? (
<button className="inspector-action-button" type="button" disabled={locked} onClick={onSeparateParts}>
<Split size={17} strokeWidth={2.5} />
<span>Separate Parts</span>
</button>
) : null}
<div className="property-card">
<button
className="property-card-header"
@@ -330,7 +344,7 @@ export function ShapeInspector({
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={locked} />;
}
return <RangeProperty key={property.label} {...property} accuracy={accuracy} disabled={locked} />;
return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={locked} />;
})}
</div>
) : null}
@@ -386,76 +400,81 @@ function RangeProperty({
min,
max,
step = 0.01,
accuracy,
workspace,
disabled,
onChange,
}: RangePropertyConfig & { accuracy: MeasurementAccuracy; disabled?: boolean }) {
}: RangePropertyConfig & { workspace: WorkplaneWorkspaceSettings; disabled?: boolean }) {
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height";
const isLength = propertyUsesLengthUnit(label);
const accuracy = workspace.accuracy;
const actualValue = Math.max(min, Number.isFinite(value) ? value : min);
const sliderValue = clamp(actualValue, min, max);
const position = ((sliderValue - min) / Math.max(1, max - min)) * 100;
const controlValue = isLength ? millimetersToDisplay(actualValue, workspace) : actualValue;
const controlMin = isLength ? millimetersToDisplay(min, workspace) : min;
const controlMax = isLength ? millimetersToDisplay(max, workspace) : max;
const controlStep = isLength ? displayStepFromMillimeters(step, workspace) : step;
const sliderValue = clamp(controlValue, controlMin, controlMax);
const position = ((sliderValue - controlMin) / Math.max(Number.EPSILON, controlMax - controlMin)) * 100;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatPanelNumber(actualValue, accuracy));
const [draft, setDraft] = useState(formatPropertyNumber(controlValue, accuracy, controlStep));
const unit = isLength ? lengthDisplayUnit(workspace).label : null;
useEffect(() => {
if (!editing) {
setDraft(formatPanelNumber(actualValue, accuracy));
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
}
}, [accuracy, actualValue, editing]);
}, [accuracy, controlStep, controlValue, editing]);
const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const finiteNext = Number.isFinite(next) ? next : actualValue;
onChange(allowsAboveSliderMax ? Math.max(min, finiteNext) : clamp(finiteNext, min, max));
const finiteNext = Number.isFinite(next) ? next : controlValue;
const nextModelValue = toModelValue(finiteNext);
onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max));
setEditing(false);
};
const handleSliderChange = (nextValue: number) => {
const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax);
onChange(clamp(toModelValue(next), min, max));
setDraft(formatPropertyNumber(next, accuracy, controlStep));
};
return (
<label className="range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
<span>{label}</span>
<div className="range-control">
{editing ? (
<span className="range-property-header">
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
className="range-value-input"
type="number"
min={min}
max={allowsAboveSliderMax ? undefined : max}
step={step}
value={draft}
autoFocus
min={controlMin}
max={allowsAboveSliderMax ? undefined : controlMax}
step={controlStep}
value={editing ? draft : formatPropertyNumber(controlValue, accuracy, controlStep)}
disabled={disabled}
inputMode="decimal"
onFocus={() => {
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
setEditing(true);
}}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.currentTarget.blur();
} else if (event.key === "Escape") {
setDraft(formatPanelNumber(actualValue, accuracy));
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
setEditing(false);
}
}}
/>
) : (
<output
onDoubleClick={(event) => {
if (disabled) {
return;
}
event.preventDefault();
setDraft(formatPanelNumber(actualValue, accuracy));
setEditing(true);
}}
>
{formatPanelNumber(actualValue, accuracy)}
</output>
)}
{unit ? <span className="range-value-unit">{unit}</span> : null}
</span>
</span>
<div className="range-control">
<input
type="range"
min={min}
max={max}
step={step}
min={controlMin}
max={controlMax}
step={controlStep}
value={sliderValue}
disabled={disabled}
onChange={(event) => {
const next = Number(event.currentTarget.value);
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
}}
onChange={(event) => handleSliderChange(Number(event.currentTarget.value))}
/>
</div>
</label>
@@ -2,6 +2,7 @@
import { Grid3X3, Palette, Ruler, X } from "lucide-react";
import { useState, type CSSProperties } from "react";
import { normalizeScaleForUnits, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -51,9 +52,12 @@ export function WorkspaceSettingsModal({
}) {
const [defaultSaved, setDefaultSaved] = useState(false);
const [activeSection, setActiveSection] = useState<WorkspaceSettingsSection>("appearance");
const scaleOptions = scaleOptionsForUnits(workspace.units);
const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false);
onWorkspaceChange({ ...workspace, ...patch });
const next = { ...workspace, ...patch };
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
};
const setDimension = (key: "width" | "depth", value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
@@ -151,13 +155,13 @@ export function WorkspaceSettingsModal({
<WorkspaceSelect
label="Units"
value={workspace.units}
options={["Metric (Default)", "Imperial", "Bricks"]}
options={WORKSPACE_UNIT_OPTIONS}
onChange={(units) => patchWorkspace({ units })}
/>
<WorkspaceSelect
label="Scale"
value={workspace.scale}
options={["1:1 (millimeters)", "1:10 (centimeters)", "1:100 (meters)", "1:1000 (meters)"]}
value={scaleValue}
options={scaleOptions}
onChange={(scale) => patchWorkspace({ scale })}
/>
<WorkspaceSelect