release: publish v0.6.0

This commit is contained in:
Formsmith
2026-07-11 20:34:13 +03:00
parent 458538d3d4
commit 20731043e4
32 changed files with 1707 additions and 320 deletions
+1 -1
View File
@@ -29,8 +29,8 @@ const nextConfig: NextConfig = {
...(isStaticExport
? {
output: "export" as const,
distDir: ".next-export",
trailingSlash: true,
assetPrefix: "./",
}
: {}),
};
+117 -15
View File
@@ -2686,36 +2686,111 @@ button {
.camera-controls {
position: absolute;
top: 173px;
left: 8px;
left: 10px;
z-index: 8;
display: grid;
gap: 4px;
display: flex;
flex-direction: column;
gap: 2px;
padding: 5px;
background: rgba(255, 255, 255, 0.86);
border: 1px solid rgba(194, 209, 219, 0.9);
border-radius: 17px;
box-shadow: 0 10px 30px rgba(32, 64, 84, 0.14), 0 2px 6px rgba(32, 64, 84, 0.08);
backdrop-filter: blur(14px) saturate(1.15);
}
.camera-controls button {
position: relative;
display: grid;
width: 51px;
height: 51px;
width: 44px;
height: 43px;
place-items: center;
color: #173b5a;
background: rgba(255, 255, 255, 0.88);
border: 1px solid #dfe6eb;
border-radius: 999px;
box-shadow: 0 1px 2px rgba(30, 50, 70, 0.08);
background: transparent;
border: 1px solid transparent;
border-radius: 12px;
box-shadow: none;
cursor: pointer;
transition: color 140ms ease, background-color 140ms ease, border-color 140ms ease, transform 140ms ease;
}
.camera-controls button:hover {
color: #000;
border-color: #c4d2dc;
color: #071f32;
background: rgba(223, 239, 247, 0.82);
border-color: rgba(155, 190, 207, 0.7);
transform: translateX(1px);
}
.camera-controls button:focus-visible {
outline: 2px solid #28a9d2;
outline-offset: 1px;
}
.camera-controls.collapsed {
border-radius: 17px;
}
.camera-controls button.active,
.camera-controls button[aria-pressed="true"] {
color: #007eae;
background: #e8f8fd;
border-color: #63cbe8;
box-shadow: 0 0 0 3px rgba(0, 159, 207, 0.14), 0 1px 2px rgba(30, 50, 70, 0.08);
color: #006b94;
background: #def5fb;
border-color: #6fc8df;
box-shadow: inset 3px 0 0 #079bc6;
}
.ruler-control-group {
position: relative;
margin-top: 6px;
}
.ruler-control-group::before {
position: absolute;
top: -5px;
right: 8px;
left: 8px;
height: 1px;
content: "";
background: rgba(117, 144, 160, 0.28);
}
.ruler-tool-popover {
position: absolute;
top: 2px;
left: calc(100% + 10px);
display: flex;
gap: 3px;
padding: 4px;
background: rgba(255, 255, 255, 0.94);
border: 1px solid rgba(194, 209, 219, 0.94);
border-radius: 13px;
box-shadow: 0 8px 24px rgba(32, 64, 84, 0.18), 0 2px 6px rgba(32, 64, 84, 0.1);
backdrop-filter: blur(14px) saturate(1.15);
animation: ruler-tools-in 130ms ease-out;
}
.camera-controls .ruler-tool-popover button {
width: 35px;
height: 35px;
border-radius: 9px;
}
.camera-controls .ruler-tool-popover .ruler-delete-button.active {
color: #b42318;
background: #fff0ee;
border-color: #ee9b92;
box-shadow: inset 3px 0 0 #dc3f36;
}
@keyframes ruler-tools-in {
from {
opacity: 0;
transform: translateX(-4px) scale(0.96);
}
to {
opacity: 1;
transform: translateX(0) scale(1);
}
}
.workplane-wrap {
@@ -2757,6 +2832,11 @@ button {
cursor: crosshair;
}
.workplane-wrap.ruler-delete-mode .three-workplane-host,
.workplane-wrap.ruler-delete-mode .three-workplane-host:active {
cursor: default;
}
.workplane-wrap.modifier-edge-pick .three-workplane-host,
.workplane-wrap.modifier-edge-pick .three-workplane-host:active {
cursor: crosshair;
@@ -2796,6 +2876,7 @@ button {
stroke-width: 2;
vector-effect: non-scaling-stroke;
pointer-events: none;
transition: stroke 120ms ease, stroke-width 120ms ease;
}
.ruler-segment-hit {
@@ -2817,6 +2898,19 @@ button {
.ruler-point {
pointer-events: all;
cursor: pointer;
transition: fill 120ms ease, stroke 120ms ease, filter 120ms ease;
}
.ruler-overlay.delete-mode .ruler-segment-group:hover .ruler-segment {
stroke: #dc3f36;
stroke-width: 3;
filter: drop-shadow(0 0 2px rgba(220, 63, 54, 0.3));
}
.ruler-overlay.delete-mode .ruler-point:hover {
fill: #fff0ee;
stroke: #dc3f36;
filter: drop-shadow(0 0 3px rgba(220, 63, 54, 0.36));
}
.ruler-point.pending {
@@ -4142,6 +4236,14 @@ button {
font-weight: 700;
}
.workspace-global-note {
margin: -10px 0 0 153px;
color: #718697;
font-size: 12px;
font-weight: 650;
line-height: 1.45;
}
.workspace-dimensions {
display: grid;
grid-template-columns: 1fr 1fr;
+1 -1
View File
@@ -16,7 +16,7 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<html lang="en" style={{ colorScheme: "light" }}>
<body suppressHydrationWarning>{children}</body>
</html>
);
+28 -13
View File
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import { createLocalId } from "@/lib/localIds";
import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
type AppView = "dashboard" | "editor";
@@ -260,6 +260,13 @@ export default function Home() {
const projectShapeSaveQueuesRef = useRef<Record<string, Promise<void>>>({});
useEffect(() => {
document.documentElement.removeAttribute("data-theme");
document.documentElement.style.colorScheme = "light";
try {
window.localStorage.removeItem("sketchForge.theme");
} catch {
// Light mode still applies when browser storage is unavailable.
}
const { projects: storedProjects, legacyShapes } = readStoredProjects();
setProjects(storedProjects);
if (Object.keys(legacyShapes).length > 0) {
@@ -486,18 +493,26 @@ export default function Home() {
const version = Date.now();
const workspace = normalizeWorkspaceSettings(snapshot.workspace);
const snapGrid = normalizeSnapGrid(snapshot.snap);
setProjects((current) =>
current.map((project) =>
project.id === snapshot.projectId
? {
...project,
workspace,
snapGrid,
updatedAt: version,
}
: project,
),
);
const nextFingerprint = workplaneSettingsFingerprint(workspace, snapGrid);
setProjects((current) => {
let changed = false;
const next = current.map((project) => {
if (project.id !== snapshot.projectId) return project;
const currentFingerprint = workplaneSettingsFingerprint(
normalizeWorkspaceSettings(project.workspace),
normalizeSnapGrid(project.snapGrid),
);
if (currentFingerprint === nextFingerprint) return project;
changed = true;
return {
...project,
workspace,
snapGrid,
updatedAt: version,
};
});
return changed ? next : current;
});
}, []);
const createAndOpenProject = (name?: string) => {
+159 -178
View File
@@ -9,7 +9,6 @@ import * as THREE from "three";
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js";
import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";
import { FontLoader, type Font, type FontData } from "three/examples/jsm/loaders/FontLoader.js";
import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js";
import droidMonoFontJson from "three/examples/fonts/droid/droid_sans_mono_regular.typeface.json";
import droidSansBoldFontJson from "three/examples/fonts/droid/droid_sans_bold.typeface.json";
import droidSerifBoldFontJson from "three/examples/fonts/droid/droid_serif_bold.typeface.json";
@@ -60,13 +59,24 @@ import {
serializeShapesForSync,
shapeDepth,
shapeWidth,
withHoleMode,
workplaneShapesEqual,
} from "@/lib/workplaneShapes";
import { bakeCadMetadataForShapeTransform, cadBrepTransformForShape, cadModifierPrimitiveForAnalyticBox, cadModifierPrimitiveForBakedShape } from "@/lib/cadBakeMetadata";
import { hasOneToOneCadComponentMapping } from "@/lib/cadModifierGroups";
import {
CAD_MODIFIER_REQUEST_TIMEOUT_MS,
cadModifierTimeoutMessage,
cadModifierWorkerFailureMessage,
type CadModifierRequestPhase,
} from "@/lib/cadModifierRuntime";
import { cloneWorkplaneShapeSnapshot, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory";
import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap";
import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
import { normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import {
SKETCHFORGE_MCP_POLL_MS,
@@ -179,7 +189,6 @@ const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02;
const NORMAL_SELECTION_CAD_EDGE_MIN_ANGLE = 60;
const MIN_EDGE_MODIFIER_AMOUNT = 0.001;
const SEPARATE_PARTS_VERTEX_TOLERANCE = 0.0005;
const svgLoader = new SVGLoader();
const booleanFontLoader = new FontLoader();
const booleanTextFonts: Record<string, Font> = {
Multilanguage: booleanFontLoader.parse(helvetikerBoldFontJson as FontData),
@@ -1074,16 +1083,6 @@ function makeBlockPerfScene(count = 500): WorkplaneShape[] {
});
}
function withHoleMode(shape: WorkplaneShape, hole: boolean, parentColor?: string): WorkplaneShape {
const color = hole ? "#b8c2cc" : (parentColor ?? fallbackSolidColor(shape));
return {
...shape,
hole,
color,
groupedShapes: shape.groupedShapes?.map((child) => withHoleMode(child, hole)),
};
}
function sanitizeName(name: string) {
return name.replace(/[^a-z0-9_-]+/gi, "_") || "shape";
}
@@ -1275,10 +1274,6 @@ function cadModifierComponentPreviews(sourceParts: WorkplaneShape[], components:
return previews;
}
function cloneWorkplaneShapeSnapshot(shape: WorkplaneShape): WorkplaneShape {
return JSON.parse(JSON.stringify(canonicalizeShape(shape))) as WorkplaneShape;
}
function edgeTreatmentLabel(feature: NonNullable<WorkplaneShape["edgeTreatments"]>[number]) {
const size = `${Number(feature.amount.toFixed(2))} mm`;
return `${feature.kind === "fillet" ? "fillet" : "chamfer"} (${size}, ${feature.edgeCount} edge${feature.edgeCount === 1 ? "" : "s"})`;
@@ -1357,7 +1352,10 @@ function groupedShapeWithComponentEdgeTreatment(
feature: NonNullable<WorkplaneShape["edgeTreatments"]>[number],
createdAt: number,
) {
if (!base.groupedShapes?.length || sourceParts.length < 2 || session.componentPreviews.length === 0) {
if (
!base.groupedShapes?.length ||
!hasOneToOneCadComponentMapping(sourceParts.length, session.componentPreviews.map((component) => component.owner))
) {
return null;
}
@@ -1373,6 +1371,9 @@ function groupedShapeWithComponentEdgeTreatment(
}
const ownerToSourceIndex = matchCadComponentsToSources(sourceParts, session.componentPreviews);
if (ownerToSourceIndex.size !== sourceParts.length) {
return null;
}
const componentByOwner = new Map(session.componentPreviews.map((component) => [component.owner, component]));
const updatedSources = [...sourceParts];
let changed = false;
@@ -1443,29 +1444,7 @@ function edgeTreatmentHistoryOptions(shape: WorkplaneShape, path: number[] = [],
}
function restoreOwnLastEdgeTreatment(shape: WorkplaneShape, entry: NonNullable<WorkplaneShape["edgeTreatmentHistory"]>[number]) {
const before = cloneWorkplaneShapeSnapshot(entry.before);
return canonicalizeShape({
...before,
id: shape.id,
name: shape.name,
color: shape.color,
hole: shape.hole || undefined,
x: shape.x,
z: shape.z,
elevation: shape.elevation,
width: shapeWidth(shape),
depth: shapeDepth(shape),
height: shape.height,
size: shape.size,
rotation: shape.rotation,
rotationX: shape.rotationX,
rotationZ: shape.rotationZ,
mirrorX: shape.mirrorX,
mirrorY: shape.mirrorY,
mirrorZ: shape.mirrorZ,
locked: shape.locked,
hidden: shape.hidden,
});
return restoreShapeBeforeEdgeTreatment(shape, entry);
}
async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[], entryId: string): Promise<{ shape: WorkplaneShape; label: string } | null> {
@@ -2099,98 +2078,6 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
};
}
function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
const parsed = svgLoader.parse(source);
const rawPositions: number[] = [];
const rawNormals: number[] = [];
parsed.paths.forEach((path) => {
SVGLoader.createShapes(path).forEach((svgShape) => {
const rawGeometry = new THREE.ExtrudeGeometry(svgShape, {
depth: 4,
bevelEnabled: false,
curveSegments: 16,
steps: 1,
});
rawGeometry.rotateX(-Math.PI / 2);
const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry;
geometry.computeVertexNormals();
const position = geometry.getAttribute("position");
const normal = geometry.getAttribute("normal");
for (let i = 0; i < position.count; i += 1) {
rawPositions.push(position.getX(i), position.getY(i), position.getZ(i));
if (normal) {
rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
}
}
if (geometry !== rawGeometry) geometry.dispose();
rawGeometry.dispose();
});
});
if (rawPositions.length < 9) {
throw new Error("SVG has no readable filled paths");
}
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let i = 0; i < rawPositions.length; i += 3) {
minX = Math.min(minX, rawPositions[i]);
minY = Math.min(minY, rawPositions[i + 1]);
minZ = Math.min(minZ, rawPositions[i + 2]);
maxX = Math.max(maxX, rawPositions[i]);
maxY = Math.max(maxY, rawPositions[i + 1]);
maxZ = Math.max(maxZ, rawPositions[i + 2]);
}
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
const width = Math.max(1, maxX - minX);
const height = Math.max(1, maxY - minY);
const depth = Math.max(1, maxZ - minZ);
const positions: number[] = [];
const normals: number[] = [];
for (let i = 0; i < rawPositions.length; i += 3) {
positions.push(rawPositions[i] - centerX, rawPositions[i + 1] - minY, rawPositions[i + 2] - centerZ);
if (rawNormals.length === rawPositions.length) {
normals.push(rawNormals[i], rawNormals[i + 1], rawNormals[i + 2]);
}
}
return {
id: createLocalId("uploaded-svg"),
name: fileName.replace(/\.[^.]+$/, "") || "Imported SVG",
kind: "mesh",
color: "#0098c7",
x: 10,
z: -10,
size: Math.max(width, depth),
width,
depth,
height,
rotation: 0,
rotationX: 0,
rotationZ: 0,
importedMesh: {
positions,
normals: normals.length ? normals : undefined,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
triangleCount: Math.floor(positions.length / 9),
sourceFormat: "svg",
},
locked: false,
hidden: false,
};
}
function readFileAsDataUrl(file: File) {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
@@ -5193,14 +5080,86 @@ export function SketchForgeEditor({
const cadModifierBaseShapeRef = useRef<WorkplaneShape | null>(null);
const cadModifierBaseFingerprintRef = useRef("");
const cadModifierSourcePartsRef = useRef<WorkplaneShape[]>([]);
const cadModifierWatchdogRef = useRef<{ requestId: number; phase: CadModifierRequestPhase; timer: number } | null>(null);
const cadModifierWorkerRestartRef = useRef<() => Worker | null>(() => null);
const lastMcpErrorRef = useRef<string | null>(null);
const executeMcpCommandRef = useRef<((command: SketchForgeMcpCommand) => Promise<unknown>) | null>(null);
const clearCadModifierWatchdog = useCallback((requestId?: number) => {
const active = cadModifierWatchdogRef.current;
if (!active || (requestId !== undefined && active.requestId !== requestId)) return;
window.clearTimeout(active.timer);
cadModifierWatchdogRef.current = null;
}, []);
const armCadModifierWatchdog = useCallback((requestId: number, phase: CadModifierRequestPhase) => {
clearCadModifierWatchdog();
const timer = window.setTimeout(() => {
const active = cadModifierWatchdogRef.current;
if (!active || active.requestId !== requestId) return;
cadModifierWatchdogRef.current = null;
cadModifierWorkerRef.current?.terminate();
cadModifierWorkerRef.current = null;
cadModifierWorkerRestartRef.current();
const message = cadModifierTimeoutMessage(phase);
setEdgeModifier((current) => current ? {
...current,
busy: false,
prepared: false,
preview: null,
error: message,
} : current);
setNotice(message);
}, CAD_MODIFIER_REQUEST_TIMEOUT_MS);
cadModifierWatchdogRef.current = { requestId, phase, timer };
}, [clearCadModifierWatchdog]);
useEffect(() => {
const worker = new Worker(new URL("../workers/cadModifier.worker.ts", import.meta.url), { type: "module" });
cadModifierWorkerRef.current = worker;
worker.onmessage = (event: MessageEvent<CadModifierWorkerResponse>) => {
let disposed = false;
const rejectPendingRequests = (message: string) => {
cadModifierPendingRef.current.forEach((pending) => {
window.clearTimeout(pending.timer);
pending.reject(new Error(message));
});
cadModifierPendingRef.current.clear();
};
const reportWorkerFailure = (worker: Worker | null) => {
if (worker && cadModifierWorkerRef.current !== worker) return;
clearCadModifierWatchdog();
worker?.terminate();
cadModifierWorkerRef.current = null;
rejectPendingRequests("The CAD worker could not start");
const requestId = cadModifierRequestRef.current + 1;
cadModifierRequestRef.current = requestId;
cadModifierPrepareRef.current = requestId;
cadModifierLatestPreviewRef.current = requestId;
if (cadModifierBaseShapeRef.current) {
const message = cadModifierWorkerFailureMessage();
setEdgeModifier((current) => current ? { ...current, busy: false, prepared: false, preview: null, error: message } : current);
setNotice(message);
}
};
const createWorker = () => {
if (disposed) return null;
cadModifierWorkerRef.current?.terminate();
try {
const worker = new Worker(new URL("../workers/cadModifier.worker.ts", import.meta.url), { type: "module" });
cadModifierWorkerRef.current = worker;
worker.onmessage = handleWorkerMessage;
worker.onerror = (event) => {
event.preventDefault();
reportWorkerFailure(worker);
};
worker.onmessageerror = () => reportWorkerFailure(worker);
return worker;
} catch {
reportWorkerFailure(null);
return null;
}
};
function handleWorkerMessage(event: MessageEvent<CadModifierWorkerResponse>) {
const message = event.data;
clearCadModifierWatchdog(message.requestId);
const pending = cadModifierPendingRef.current.get(message.requestId);
if (pending) {
window.clearTimeout(pending.timer);
@@ -5263,24 +5222,23 @@ export function SketchForgeEditor({
setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: message.message } : current);
setNotice("Edge treatment needs adjustment");
}
};
worker.onerror = () => {
setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: "The CAD worker could not start" } : current);
};
}
cadModifierWorkerRestartRef.current = createWorker;
createWorker();
return () => {
cadModifierPendingRef.current.forEach((pending) => {
window.clearTimeout(pending.timer);
pending.reject(new Error("The CAD worker was closed"));
});
cadModifierPendingRef.current.clear();
worker.terminate();
disposed = true;
clearCadModifierWatchdog();
cadModifierWorkerRestartRef.current = () => null;
rejectPendingRequests("The CAD worker was closed");
cadModifierWorkerRef.current?.terminate();
cadModifierWorkerRef.current = null;
};
}, []);
}, [clearCadModifierWatchdog]);
const invalidateCadModifierSession = useCallback(() => {
const wasActive = cadModifierBaseShapeRef.current !== null;
if (!wasActive) return false;
clearCadModifierWatchdog();
const requestId = cadModifierRequestRef.current + 1;
cadModifierRequestRef.current = requestId;
cadModifierLatestPreviewRef.current = requestId;
@@ -5291,7 +5249,7 @@ export function SketchForgeEditor({
cadModifierSourcePartsRef.current = [];
setEdgeModifier(null);
return true;
}, []);
}, [clearCadModifierWatchdog]);
useEffect(() => {
const warmBooleanRuntime = () => {
@@ -6344,14 +6302,22 @@ export function SketchForgeEditor({
}, []);
const postCadModifierRequest = useCallback((request: CadModifierWorkerPayload, transfer: Transferable[] = []) => {
const worker = cadModifierWorkerRef.current ?? cadModifierWorkerRestartRef.current();
if (!worker) return null;
const requestId = cadModifierRequestRef.current + 1;
cadModifierRequestRef.current = requestId;
cadModifierWorkerRef.current?.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer);
try {
worker.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer);
} catch {
worker.terminate();
if (cadModifierWorkerRef.current === worker) cadModifierWorkerRef.current = null;
return null;
}
return requestId;
}, []);
const postCadModifierRequestAsync = useCallback((request: CadModifierWorkerPayload, transfer: Transferable[] = [], timeoutMs = 20000) => {
const worker = cadModifierWorkerRef.current;
const worker = cadModifierWorkerRef.current ?? cadModifierWorkerRestartRef.current();
if (!worker) {
return Promise.reject(new Error("The CAD worker is not ready"));
}
@@ -6363,7 +6329,13 @@ export function SketchForgeEditor({
reject(new Error("Timed out waiting for the CAD worker"));
}, timeoutMs);
cadModifierPendingRef.current.set(requestId, { resolve, reject, timer });
worker.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer);
try {
worker.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer);
} catch (error) {
window.clearTimeout(timer);
cadModifierPendingRef.current.delete(requestId);
reject(error instanceof Error ? error : new Error("The CAD worker rejected the request"));
}
});
}, []);
@@ -6430,13 +6402,21 @@ export function SketchForgeEditor({
if (part.primitive) return { primitive: part.primitive, hole: Boolean(part.shape.hole) };
return { ...meshDataToCadTransfer(part.mesh as MeshData), hole: Boolean(part.shape.hole) };
});
cadModifierPrepareRef.current = postCadModifierRequest({
const prepareRequestId = postCadModifierRequest({
type: "prepare",
parts,
sharpAngle: 25,
suppressTreatmentDetailEdges: appliedEdgeTreatmentCount > 0,
}, parts.flatMap((part) => part.positions && part.indices ? [part.positions.buffer, part.indices.buffer] : []));
}, [postCadModifierRequest, selectedShape, selectedShapes.length]);
if (prepareRequestId === null) {
const message = cadModifierWorkerFailureMessage();
setEdgeModifier((current) => current ? { ...current, busy: false, prepared: false, error: message } : current);
setNotice(message);
return;
}
cadModifierPrepareRef.current = prepareRequestId;
armCadModifierWatchdog(prepareRequestId, "prepare");
}, [armCadModifierWatchdog, postCadModifierRequest, selectedShape, selectedShapes.length]);
const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => {
if (shape.locked || shape.hole) {
@@ -6632,8 +6612,6 @@ export function SketchForgeEditor({
useEffect(() => {
if (!edgeModifier?.prepared || edgeModifier.selectedEdgeIds.length === 0) return;
const worker = cadModifierWorkerRef.current;
if (!worker) return;
const timer = window.setTimeout(() => {
const requestId = postCadModifierRequest({
type: "preview",
@@ -6643,11 +6621,18 @@ export function SketchForgeEditor({
quality: edgeModifier.quality,
chamferAngle: edgeModifier.chamferAngle,
});
if (requestId === null) {
const message = cadModifierWorkerFailureMessage();
setEdgeModifier((current) => current ? { ...current, busy: false, prepared: false, preview: null, error: message } : current);
setNotice(message);
return;
}
cadModifierLatestPreviewRef.current = requestId;
armCadModifierWatchdog(requestId, "preview");
setEdgeModifier((current) => current ? { ...current, busy: true, error: null } : current);
}, 120);
return () => window.clearTimeout(timer);
}, [edgeModifier?.amount, edgeModifier?.chamferAngle, edgeModifier?.kind, edgeModifier?.prepared, edgeModifier?.quality, edgeModifier?.selectedEdgeIds, postCadModifierRequest]);
}, [armCadModifierWatchdog, edgeModifier?.amount, edgeModifier?.chamferAngle, edgeModifier?.kind, edgeModifier?.prepared, edgeModifier?.quality, edgeModifier?.selectedEdgeIds, postCadModifierRequest]);
const snapSelected = useCallback(() => {
if (!hasSelection) {
@@ -6655,27 +6640,17 @@ export function SketchForgeEditor({
return;
}
const selected = new Set(selectedIds);
const grid = 1;
const snapValue = (value: number) => Math.round(value / grid) * grid;
const grid = visibleGridStep(workspaceSettings);
commitShapes(
shapes.map((shape) =>
selected.has(shape.id) && !shape.locked
? {
...shape,
x: snapValue(shape.x),
z: snapValue(shape.z),
elevation: snapValue(shape.elevation ?? 0),
width: Math.max(grid, snapValue(shape.width)),
depth: Math.max(grid, snapValue(shape.depth)),
height: Math.max(grid, snapValue(shape.height)),
size: Math.max(grid, snapValue(shape.size)),
}
? snapShapeFootprintToVisibleGrid(shape, meshAabb(shape), workspaceSettings)
: shape,
),
selectedIds,
`Snapped ${selectedShapes.length} shape${selectedShapes.length === 1 ? "" : "s"} to 1 mm grid`,
`Snapped ${selectedShapes.length} shape${selectedShapes.length === 1 ? "" : "s"} to ${grid} mm visible grid`,
);
}, [commitShapes, hasSelection, selectedIds, selectedShapes.length, shapes]);
}, [commitShapes, hasSelection, selectedIds, selectedShapes.length, shapes, workspaceSettings]);
const toggleHidden = useCallback(() => {
if (!hasSelection) {
@@ -7460,6 +7435,11 @@ export function SketchForgeEditor({
setNotice(hasSelection ? "Select at least one solid shape before exporting" : "Add a solid shape before exporting");
return;
}
const invalidSvg = exportable.map(invalidSvgMeshReason).find((reason): reason is string => Boolean(reason));
if (invalidSvg) {
setNotice(`${invalidSvg}. Re-import the source SVG after fixing its contours`);
return;
}
const meshes = exportable.map(meshForShape);
const selectedNotice = `Exported ${exportable.length} selected shape${exportable.length === 1 ? "" : "s"}`;
const finishNotice = (label: string, result: DownloadResult) => {
@@ -8002,12 +7982,13 @@ export function SketchForgeEditor({
selectedCount={edgeModifier.selectedEdgeIds.length}
availableCount={modifierAvailableEdgeIds.length}
busy={edgeModifier.busy}
prepared={edgeModifier.prepared}
error={edgeModifier.error}
onAmountChange={(value) => setEdgeModifier((current) => current ? { ...current, amount: Math.max(MIN_EDGE_MODIFIER_AMOUNT, Math.min(edgeModifierMaxAmount, value)), preview: null, busy: true, error: null } : current)}
onChamferAngleChange={(value) => setEdgeModifier((current) => current ? { ...current, chamferAngle: Math.max(5, Math.min(85, value)), preview: null, busy: true, error: null } : current)}
onQualityChange={(quality) => setEdgeModifier((current) => current ? { ...current, quality, preview: null, busy: true, error: null } : current)}
onAmountChange={(value) => setEdgeModifier((current) => current?.prepared ? { ...current, amount: Math.max(MIN_EDGE_MODIFIER_AMOUNT, Math.min(edgeModifierMaxAmount, value)), preview: null, busy: true, error: null } : current)}
onChamferAngleChange={(value) => setEdgeModifier((current) => current?.prepared ? { ...current, chamferAngle: Math.max(5, Math.min(85, value)), preview: null, busy: true, error: null } : current)}
onQualityChange={(quality) => setEdgeModifier((current) => current?.prepared ? { ...current, quality, preview: null, busy: true, error: null } : current)}
onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => {
if (!current) return current;
if (!current?.prepared) return current;
const nextAngle = Math.max(1, Math.min(120, sharpAngle));
const availableIds = new Set(current.edges
.filter((edge) => selectableCadModifierEdge(edge, nextAngle))
@@ -8022,10 +8003,10 @@ export function SketchForgeEditor({
error: availableIds.size === 0 ? "No sharp edges match this threshold" : selectedEdgeIds.length ? null : "Select at least one highlighted edge",
};
})}
onTangentChainChange={(tangentChain) => setEdgeModifier((current) => current ? { ...current, tangentChain } : current)}
onPreserveEdgeSizeChange={(preserveEdgeSize) => setEdgeModifier((current) => current ? { ...current, preserveEdgeSize } : current)}
onSelectAll={() => setEdgeModifier((current) => current ? { ...current, selectedEdgeIds: modifierAvailableEdgeIds, preview: null, busy: modifierAvailableEdgeIds.length > 0, error: modifierAvailableEdgeIds.length ? null : current.error } : current)}
onClear={() => setEdgeModifier((current) => current ? { ...current, selectedEdgeIds: [], preview: null, busy: false, error: "Select at least one highlighted edge" } : current)}
onTangentChainChange={(tangentChain) => setEdgeModifier((current) => current?.prepared ? { ...current, tangentChain } : current)}
onPreserveEdgeSizeChange={(preserveEdgeSize) => setEdgeModifier((current) => current?.prepared ? { ...current, preserveEdgeSize } : current)}
onSelectAll={() => setEdgeModifier((current) => current?.prepared ? { ...current, selectedEdgeIds: modifierAvailableEdgeIds, preview: null, busy: modifierAvailableEdgeIds.length > 0, error: modifierAvailableEdgeIds.length ? null : current.error } : current)}
onClear={() => setEdgeModifier((current) => current?.prepared ? { ...current, selectedEdgeIds: [], preview: null, busy: false, error: "Select at least one highlighted edge" } : current)}
onRemoveFeature={removeEdgeTreatment}
onApply={applyEdgeModifier}
onCancel={cancelEdgeModifier}
@@ -8390,7 +8371,7 @@ function SecondaryToolbar({
</div>
</div>
<div className="toolbar-section toolbar-actions-section">
<div className="toolbar-section-label">Output</div>
<div className="toolbar-section-label">Manage</div>
<div className="action-buttons">
<button className="action-icon-button" aria-label="Import" title="Import" onClick={() => onTopPanel("import")}>
<ToolbarImportIcon />
+151 -74
View File
@@ -1,6 +1,6 @@
"use client";
import { Home, Minus, Plus } from "lucide-react";
import { ChevronLeft, ChevronRight, Home, Minus, Plus, Ruler, X } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react";
import * as THREE from "three";
import { Brush, Evaluator, HOLLOW_INTERSECTION } from "three-bvh-csg";
@@ -18,6 +18,7 @@ import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlay
import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector";
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION } from "@/lib/workplaneGrid";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
import {
@@ -279,18 +280,6 @@ type RulerCandidate = {
pointId?: string;
};
function RulerGlyph() {
return (
<svg viewBox="0 0 32 32" width="30" height="30" aria-hidden="true">
<path d="M5 9.5 24.5 5 27 16 7.5 20.5 5 9.5Z" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinejoin="round" />
<path d="m10 8.5 1 4.2m4-5.3.7 2.9m4.3-4 .9 4.2m-12.3 7 1.7-3.8m4.1 2.8 1.2-2.7m4 1.6 1.5-3.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
<circle cx="7.5" cy="24.5" r="2" fill="currentColor" />
<circle cx="24.5" cy="24.5" r="2" fill="currentColor" />
<path d="M9.5 24.5h13" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
</svg>
);
}
type RotationHandleSide = "near" | "right" | "far" | "left";
type RotationHandleSides = Record<RotationAxis, RotationHandleSide>;
type ShapeUpdatePatch = Partial<WorkplaneShape> & { bakeTransform?: boolean };
@@ -639,20 +628,22 @@ function RulerOverlay({
overlay,
startPointId,
active,
deleteMode,
onPointPointerDown,
onSegmentPointerDown,
}: {
overlay: RulerOverlayState;
startPointId: string | null;
active: boolean;
deleteMode: boolean;
onPointPointerDown: (event: ReactPointerEvent<SVGCircleElement>, pointId: string) => void;
onSegmentPointerDown: (event: ReactPointerEvent<SVGLineElement>, segmentId: string) => void;
}) {
return (
<div className={`ruler-overlay ${active ? "active" : ""}`} aria-label="Ruler measurements">
<div className={`ruler-overlay ${active ? "active" : ""} ${deleteMode ? "delete-mode" : ""}`} aria-label="Ruler measurements">
<svg className="ruler-guides" width="100%" height="100%" aria-hidden="true">
{overlay.segments.map((segment) => (
<g key={segment.id}>
<g key={segment.id} className="ruler-segment-group">
<line className="ruler-segment" x1={segment.x1} y1={segment.y1} x2={segment.x2} y2={segment.y2} />
<line
className="ruler-segment-hit"
@@ -1191,6 +1182,9 @@ export function WorkplaneViewport({
const [editingDimension, setEditingDimension] = useState<EditingDimension>(null);
const [editingRotation, setEditingRotation] = useState<EditingRotation>(null);
const [rulerMode, setRulerMode] = useState(false);
const [rulerDeleteMode, setRulerDeleteMode] = useState(false);
const [rulerToolsOpen, setRulerToolsOpen] = useState(false);
const [cameraControlsCollapsed, setCameraControlsCollapsed] = useState(false);
const [rulerModel, setRulerModel] = useState<RulerModel>({ points: [], segments: [], startPointId: null, hover: null });
const [rulerOverlay, setRulerOverlay] = useState<RulerOverlayState | null>(null);
const hostRef = useRef<HTMLDivElement | null>(null);
@@ -1213,6 +1207,7 @@ export function WorkplaneViewport({
const alignOverlayRef = useRef<AlignOverlayState | null>(null);
const mirrorOverlayRef = useRef<MirrorOverlayState | null>(null);
const rulerModeRef = useRef(false);
const rulerDeleteModeRef = useRef(false);
const rulerModelRef = useRef(rulerModel);
const rulerOverlayRef = useRef<RulerOverlayState | null>(null);
const rulerIdRef = useRef(0);
@@ -1273,8 +1268,17 @@ export function WorkplaneViewport({
}
const shouldUseSavedDefault = nextKey === "local-workplane" || (initialSnap === undefined && initialWorkspace === undefined);
const savedDefault = shouldUseSavedDefault ? readSavedWorkspaceDefault(nextKey) : null;
setSnap(savedDefault?.snap ?? normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID));
setWorkspace(savedDefault?.workspace ?? normalizeWorkspaceSettings(initialWorkspace));
const nextSnap = savedDefault?.snap ?? normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID);
const nextWorkspace = savedDefault?.workspace ?? normalizeWorkspaceSettings(initialWorkspace);
const nextFingerprint = workplaneSettingsFingerprint(nextWorkspace, nextSnap);
// Prop hydration must not echo back to the parent. Parent persistence creates
// new object references even when the values are unchanged, which previously
// caused this effect and its callback effect to update each other indefinitely.
lastWorkspaceSettingsSyncRef.current = nextFingerprint;
setSnap((current) => (current === nextSnap ? current : nextSnap));
setWorkspace((current) => (
workplaneSettingsFingerprint(current, nextSnap) === nextFingerprint ? current : nextWorkspace
));
}, [initialSnap, initialWorkspace, workspaceSettingsKey]);
useEffect(() => {
@@ -1424,6 +1428,10 @@ export function WorkplaneViewport({
rulerModeRef.current = rulerMode;
}, [rulerMode]);
useEffect(() => {
rulerDeleteModeRef.current = rulerDeleteMode;
}, [rulerDeleteMode]);
useEffect(() => {
rulerModelRef.current = rulerModel;
if (threeRef.current) {
@@ -1470,6 +1478,7 @@ export function WorkplaneViewport({
const state = createThreeScene(host);
threeRef.current = state;
rebuildWorkplane(state, workspaceRef.current);
window.sketchforgeCaptureCanvas = () => {
state.camera.updateMatrixWorld();
state.renderer.render(state.scene, state.camera);
@@ -1736,8 +1745,6 @@ export function WorkplaneViewport({
? current.segments
: [...current.segments, { id: `ruler-segment-${++rulerIdRef.current}`, startId: current.startPointId, endId: point.id }];
storeRulerModel({ points, segments, startPointId: null, hover: null });
rulerModeRef.current = false;
setRulerMode(false);
},
[storeRulerModel],
);
@@ -1772,14 +1779,16 @@ export function WorkplaneViewport({
const removeRulerPoint = useCallback(
(pointId: string) => {
const current = rulerModelRef.current;
const connected = current.segments.filter((segment) => segment.startId === pointId || segment.endId === pointId);
if (connected.length > 0) {
removeRulerSegment(connected[connected.length - 1].id);
return;
}
storeRulerModel({ ...current, points: current.points.filter((point) => point.id !== pointId), startPointId: current.startPointId === pointId ? null : current.startPointId });
const segments = current.segments.filter((segment) => segment.startId !== pointId && segment.endId !== pointId);
const points = current.points.filter((point) => point.id !== pointId);
storeRulerModel({
...current,
points,
segments,
startPointId: current.startPointId === pointId ? null : current.startPointId,
});
},
[removeRulerSegment, storeRulerModel],
[storeRulerModel],
);
const setMarqueeFromState = useCallback((marquee: MarqueeState | null) => {
@@ -2332,6 +2341,11 @@ export function WorkplaneViewport({
return;
}
if (rulerDeleteModeRef.current) {
event.preventDefault();
return;
}
if (rulerModeRef.current) {
event.preventDefault();
const candidate = resolveRulerCandidate(event.clientX, event.clientY);
@@ -2804,27 +2818,54 @@ export function WorkplaneViewport({
state.needsRender = true;
}, []);
const toggleRulerMode = useCallback(() => {
const next = !rulerModeRef.current;
rulerModeRef.current = next;
setRulerMode(next);
const current = rulerModelRef.current;
storeRulerModel({ ...current, startPointId: null, hover: null });
const toggleRulerTools = useCallback(() => {
const next = !rulerToolsOpen;
setRulerToolsOpen(next);
setRulerActive(false);
rulerDeleteModeRef.current = false;
setRulerDeleteMode(false);
if (next) {
onWorkplaneModeChange(false);
onSelectShape(null);
}
}, [onSelectShape, onWorkplaneModeChange, storeRulerModel]);
}, [onSelectShape, onWorkplaneModeChange, rulerToolsOpen, setRulerActive]);
const activateRulerAdd = useCallback(() => {
rulerDeleteModeRef.current = false;
setRulerDeleteMode(false);
setRulerActive(true);
onWorkplaneModeChange(false);
onSelectShape(null);
}, [onSelectShape, onWorkplaneModeChange, setRulerActive]);
const activateRulerDelete = useCallback(() => {
setRulerActive(false);
rulerDeleteModeRef.current = true;
setRulerDeleteMode(true);
onWorkplaneModeChange(false);
onSelectShape(null);
}, [onSelectShape, onWorkplaneModeChange, setRulerActive]);
const collapseCameraControls = useCallback(() => {
setCameraControlsCollapsed(true);
setRulerToolsOpen(false);
setRulerActive(false);
rulerDeleteModeRef.current = false;
setRulerDeleteMode(false);
}, [setRulerActive]);
const handleRulerPointPointerDown = useCallback(
(event: ReactPointerEvent<SVGCircleElement>, pointId: string) => {
if (event.button === 1) {
if (event.button !== 0) {
return;
}
if (rulerDeleteModeRef.current) {
event.preventDefault();
event.stopPropagation();
removeRulerPoint(pointId);
return;
}
if (event.button !== 0 || !rulerModeRef.current) {
if (!rulerModeRef.current) {
return;
}
const point = rulerModelRef.current.points.find((candidate) => candidate.id === pointId);
@@ -2840,13 +2881,16 @@ export function WorkplaneViewport({
const handleRulerSegmentPointerDown = useCallback(
(event: ReactPointerEvent<SVGLineElement>, segmentId: string) => {
if (event.button === 1) {
if (event.button !== 0) {
return;
}
if (rulerDeleteModeRef.current) {
event.preventDefault();
event.stopPropagation();
removeRulerSegment(segmentId);
return;
}
if (event.button !== 0 || !rulerModeRef.current) {
if (!rulerModeRef.current) {
return;
}
event.preventDefault();
@@ -2873,9 +2917,12 @@ export function WorkplaneViewport({
}
const key = event.key.toLowerCase();
if (event.key === "Escape" && rulerModeRef.current) {
if (event.key === "Escape" && (rulerToolsOpen || rulerModeRef.current || rulerDeleteModeRef.current)) {
event.preventDefault();
setRulerActive(false);
rulerDeleteModeRef.current = false;
setRulerDeleteMode(false);
setRulerToolsOpen(false);
} else if (key === "f" || event.key === "Home") {
event.preventDefault();
resetView();
@@ -2890,7 +2937,7 @@ export function WorkplaneViewport({
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [resetView, setRulerActive, zoomCamera]);
}, [resetView, rulerToolsOpen, setRulerActive, zoomCamera]);
return (
<main className="workplane-stage">
@@ -2905,22 +2952,52 @@ export function WorkplaneViewport({
</div>
</div>
<div className="camera-controls" aria-label="Camera controls">
<button aria-label="Home" onClick={resetView}>
<Home size={28} />
</button>
<button aria-label="Zoom in" onClick={() => zoomCamera(0.7)}>
<Plus size={33} />
</button>
<button aria-label="Zoom out" onClick={() => zoomCamera(1.35)}>
<Minus size={33} />
</button>
<button className={rulerMode ? "active" : ""} aria-label="Ruler" title="Ruler" aria-pressed={rulerMode} onClick={toggleRulerMode}>
<RulerGlyph />
</button>
<div className={`camera-controls ${cameraControlsCollapsed ? "collapsed" : ""}`} aria-label="Camera controls">
{cameraControlsCollapsed ? (
<button className="camera-controls-toggle" aria-label="Show camera controls" title="Show controls" aria-expanded={false} onClick={() => setCameraControlsCollapsed(false)}>
<ChevronRight size={24} strokeWidth={2.25} aria-hidden="true" />
</button>
) : (
<>
<button className="camera-controls-toggle" aria-label="Hide camera controls" title="Hide controls" aria-expanded={true} onClick={collapseCameraControls}>
<ChevronLeft size={24} strokeWidth={2.25} aria-hidden="true" />
</button>
<button aria-label="Home" onClick={resetView}>
<Home size={24} strokeWidth={2.25} />
</button>
<button aria-label="Zoom in" onClick={() => zoomCamera(0.7)}>
<Plus size={28} strokeWidth={2.15} />
</button>
<button aria-label="Zoom out" onClick={() => zoomCamera(1.35)}>
<Minus size={28} strokeWidth={2.15} />
</button>
<div className="ruler-control-group">
<button
className={`ruler-trigger ${rulerToolsOpen ? "active" : ""}`}
aria-label="Ruler tools"
title="Ruler tools"
aria-expanded={rulerToolsOpen}
aria-controls="ruler-tool-popover"
onClick={toggleRulerTools}
>
<Ruler size={26} strokeWidth={2.2} aria-hidden="true" />
</button>
{rulerToolsOpen ? (
<div id="ruler-tool-popover" className="ruler-tool-popover" aria-label="Ruler actions">
<button className={rulerMode ? "active" : ""} aria-label="Add measurement" title="Add measurement" aria-pressed={rulerMode} onClick={activateRulerAdd}>
<Plus size={21} strokeWidth={2.4} aria-hidden="true" />
</button>
<button className={`ruler-delete-button ${rulerDeleteMode ? "active" : ""}`} aria-label="Delete measurement part" title="Delete measurement part" aria-pressed={rulerDeleteMode} onClick={activateRulerDelete}>
<X size={20} strokeWidth={2.4} aria-hidden="true" />
</button>
</div>
) : null}
</div>
</>
)}
</div>
<section className={`workplane-wrap ${workplaneMode ? "placing-workplane" : ""} ${rulerMode ? "ruler-mode" : ""} ${modifierActive ? "modifier-edge-pick" : ""}`} aria-label="Workplane">
<section className={`workplane-wrap ${workplaneMode ? "placing-workplane" : ""} ${rulerMode ? "ruler-mode" : ""} ${rulerDeleteMode ? "ruler-delete-mode" : ""} ${modifierActive ? "modifier-edge-pick" : ""}`} aria-label="Workplane">
<div className="workplane-plane">
<div
className="three-workplane-host"
@@ -2972,6 +3049,7 @@ export function WorkplaneViewport({
overlay={rulerOverlay}
startPointId={rulerModel.startPointId}
active={rulerMode}
deleteMode={rulerDeleteMode}
onPointPointerDown={handleRulerPointPointerDown}
onSegmentPointerDown={handleRulerSegmentPointerDown}
/>
@@ -3221,6 +3299,9 @@ function rebuildWorkplane(state: ThreeState | null, workspace: WorkspaceSettings
opacity: 0.68,
roughness: 0.92,
side: THREE.FrontSide,
polygonOffset: true,
polygonOffsetFactor: 1,
polygonOffsetUnits: 1,
}),
);
base.name = "WorkplaneBase";
@@ -3235,9 +3316,10 @@ function rebuildWorkplane(state: ThreeState | null, workspace: WorkspaceSettings
function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, blockSize = DEFAULT_WORKSPACE.gridBlockSize) {
const group = new THREE.Group();
const minor = new THREE.LineBasicMaterial({ color: "#91dff0", transparent: true, opacity: 0.55 });
const major = new THREE.LineBasicMaterial({ color: "#4bbddf", transparent: true, opacity: 0.7 });
const axis = new THREE.LineBasicMaterial({ color: "#34aad2", transparent: true, opacity: 0.88 });
const palette = workplaneGridPalette();
const minor = new THREE.LineBasicMaterial({ ...palette.minor, transparent: true, depthWrite: false });
const major = new THREE.LineBasicMaterial({ ...palette.major, transparent: true, depthWrite: false });
const axis = new THREE.LineBasicMaterial({ ...palette.axis, transparent: true, depthWrite: false });
const minorPoints: number[] = [];
const majorPoints: number[] = [];
const axisPoints: number[] = [];
@@ -3247,28 +3329,21 @@ function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, block
};
const step = clamp(blockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
const majorEvery = 4;
const xCount = Math.floor(width / step);
const zCount = Math.floor(depth / step);
for (let index = 0; index <= xCount; index += 1) {
const x = -width / 2 + index * step;
const centeredX = Math.abs(x) < 0.0001 ? 0 : x;
for (const { coordinate: centeredX, index } of interiorWorkplaneGridCoordinates(width, step)) {
const points = centeredX === 0 ? axisPoints : index % majorEvery === 0 ? majorPoints : minorPoints;
pushLine(points, [centeredX, 0.04, -depth / 2], [centeredX, 0.04, depth / 2]);
pushLine(points, [centeredX, WORKPLANE_LINE_ELEVATION, -depth / 2], [centeredX, WORKPLANE_LINE_ELEVATION, depth / 2]);
}
for (let index = 0; index <= zCount; index += 1) {
const z = -depth / 2 + index * step;
const centeredZ = Math.abs(z) < 0.0001 ? 0 : z;
for (const { coordinate: centeredZ, index } of interiorWorkplaneGridCoordinates(depth, step)) {
const points = centeredZ === 0 ? axisPoints : index % majorEvery === 0 ? majorPoints : minorPoints;
pushLine(points, [-width / 2, 0.04, centeredZ], [width / 2, 0.04, centeredZ]);
pushLine(points, [-width / 2, WORKPLANE_LINE_ELEVATION, centeredZ], [width / 2, WORKPLANE_LINE_ELEVATION, centeredZ]);
}
const border = new THREE.LineBasicMaterial({ color: "#58c5e6", transparent: true, opacity: 0.9 });
pushLine(borderPoints, [-width / 2, 0.08, -depth / 2], [width / 2, 0.08, -depth / 2]);
pushLine(borderPoints, [width / 2, 0.08, -depth / 2], [width / 2, 0.08, depth / 2]);
pushLine(borderPoints, [width / 2, 0.08, depth / 2], [-width / 2, 0.08, depth / 2]);
pushLine(borderPoints, [-width / 2, 0.08, depth / 2], [-width / 2, 0.08, -depth / 2]);
const border = new THREE.LineBasicMaterial({ ...palette.border, transparent: true, depthWrite: false });
pushLine(borderPoints, [-width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2], [width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2]);
pushLine(borderPoints, [width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2], [width / 2, WORKPLANE_LINE_ELEVATION, depth / 2]);
pushLine(borderPoints, [width / 2, WORKPLANE_LINE_ELEVATION, depth / 2], [-width / 2, WORKPLANE_LINE_ELEVATION, depth / 2]);
pushLine(borderPoints, [-width / 2, WORKPLANE_LINE_ELEVATION, depth / 2], [-width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2]);
group.add(linesFromPoints(minorPoints, minor));
group.add(linesFromPoints(majorPoints, major));
@@ -3281,7 +3356,9 @@ function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, block
function linesFromPoints(points: number[], material: THREE.LineBasicMaterial) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(points, 3));
return new THREE.LineSegments(geometry, material);
const lines = new THREE.LineSegments(geometry, material);
lines.renderOrder = 1;
return lines;
}
type CutPreviewShapeFrame = {
@@ -4437,7 +4514,7 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1,
roughness: shape.hole ? 0.88 : 0.57,
metalness: 0.02,
side: shape.importedMesh?.sourceFormat === "json" || shape.importedMesh?.sourceFormat === "svg" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide,
side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide,
});
const width = shapeWidth(shape);
@@ -4,6 +4,7 @@ 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 { edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const MIN_EDGE_MODIFIER_AMOUNT = 0.001;
@@ -34,6 +35,7 @@ function EdgeModifierSlider({
unit,
workspace,
length = false,
disabled = false,
onChange,
}: {
label: string;
@@ -44,6 +46,7 @@ function EdgeModifierSlider({
unit?: string;
workspace: WorkplaneWorkspaceSettings;
length?: boolean;
disabled?: boolean;
onChange: (value: number) => void;
}) {
const safeMin = Number.isFinite(min) ? min : 0;
@@ -92,6 +95,7 @@ function EdgeModifierSlider({
step={controlStep}
value={editing ? draft : formatSliderValue(controlValue, workspace.accuracy, controlStep)}
inputMode="decimal"
disabled={disabled}
onFocus={() => {
setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep));
setEditing(true);
@@ -117,6 +121,7 @@ function EdgeModifierSlider({
max={controlMax}
step={controlStep}
value={sliderValue}
disabled={disabled}
onChange={(event) => handleSliderChange(Number(event.currentTarget.value))}
/>
</div>
@@ -142,6 +147,7 @@ export function EdgeModifierPanel({
selectedCount,
availableCount,
busy,
prepared,
error,
onAmountChange,
onChamferAngleChange,
@@ -172,6 +178,7 @@ export function EdgeModifierPanel({
selectedCount: number;
availableCount: number;
busy: boolean;
prepared: boolean;
error: string | null;
onAmountChange: (value: number) => void;
onChamferAngleChange: (value: number) => void;
@@ -194,7 +201,7 @@ export function EdgeModifierPanel({
<div className="edge-modifier-header">
<div>
<strong>{title}</strong>
<span>{selectedCount} of {availableCount} sharp edges selected</span>
<span>{edgeModifierSelectionStatus(prepared, selectedCount, availableCount)}</span>
</div>
<button type="button" aria-label={`Cancel ${kind}`} onClick={onCancel}><X size={20} /></button>
</div>
@@ -205,12 +212,12 @@ export function EdgeModifierPanel({
</div>
<div className="edge-modifier-selection-help">
Click highlighted model edges to toggle them. Hold Shift to add or remove a single edge.
{prepared ? "Click highlighted model edges to toggle them. Hold Shift to add or remove a single edge." : "Loading CAD edge data from the local browser worker."}
</div>
<div className="edge-modifier-quick-actions">
<button type="button" onClick={onSelectAll}>All sharp edges</button>
<button type="button" onClick={onClear}>Clear</button>
<button type="button" disabled={!prepared} onClick={onSelectAll}>All sharp edges</button>
<button type="button" disabled={!prepared} onClick={onClear}>Clear</button>
</div>
{appliedFeatureCount > 0 ? (
@@ -253,26 +260,27 @@ export function EdgeModifierPanel({
step={EDGE_MODIFIER_AMOUNT_STEP}
workspace={workspace}
length
disabled={!prepared}
onChange={onAmountChange}
/>
{kind === "chamfer" ? <EdgeModifierSlider label="Angle" value={chamferAngle} min={5} max={85} step={1} unit="deg" workspace={workspace} onChange={onChamferAngleChange} /> : null}
{kind === "chamfer" ? <EdgeModifierSlider label="Angle" value={chamferAngle} min={5} max={85} step={1} unit="deg" workspace={workspace} disabled={!prepared} onChange={onChamferAngleChange} /> : null}
<EdgeModifierSlider label="Sharp-edge threshold" value={sharpAngle} min={1} max={120} step={1} unit="deg" workspace={workspace} onChange={onSharpAngleChange} />
<EdgeModifierSlider label="Sharp-edge threshold" value={sharpAngle} min={1} max={120} step={1} unit="deg" workspace={workspace} disabled={!prepared} onChange={onSharpAngleChange} />
<label className="edge-modifier-check">
<input type="checkbox" checked={tangentChain} onChange={(event) => onTangentChainChange(event.currentTarget.checked)} />
<input type="checkbox" checked={tangentChain} disabled={!prepared} onChange={(event) => onTangentChainChange(event.currentTarget.checked)} />
<span>Select tangent chains</span>
</label>
<label className="edge-modifier-check">
<input type="checkbox" checked={preserveEdgeSize} onChange={(event) => onPreserveEdgeSizeChange(event.currentTarget.checked)} />
<input type="checkbox" checked={preserveEdgeSize} disabled={!prepared} onChange={(event) => onPreserveEdgeSizeChange(event.currentTarget.checked)} />
<span>Keep edge size when resizing</span>
</label>
<label className="edge-modifier-field">
<span>Preview quality</span>
<select value={quality} onChange={(event) => onQualityChange(event.currentTarget.value as CadModifierQuality)}>
<select value={quality} disabled={!prepared} onChange={(event) => onQualityChange(event.currentTarget.value as CadModifierQuality)}>
<option value="draft">Draft</option>
<option value="standard">Standard</option>
<option value="fine">Fine</option>
@@ -282,7 +290,7 @@ export function EdgeModifierPanel({
{error ? <div className="edge-modifier-error" role="alert">{error}</div> : null}
<div className="edge-modifier-footer">
<button type="button" className="secondary" onClick={onCancel}>Cancel</button>
<button type="button" className="primary" disabled={busy || selectedCount === 0 || Boolean(error)} onClick={onApply}>
<button type="button" className="primary" disabled={!prepared || busy || selectedCount === 0 || Boolean(error)} onClick={onApply}>
{busy ? <LoaderCircle className="edge-modifier-spinner" size={17} /> : <Check size={17} />}
Apply
</button>
@@ -1,7 +1,7 @@
"use client";
import { Grid3X3, Palette, Ruler, X } from "lucide-react";
import { useState, type CSSProperties } from "react";
import { useEffect, useState } 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";
@@ -52,15 +52,27 @@ export function WorkspaceSettingsModal({
}) {
const [defaultSaved, setDefaultSaved] = useState(false);
const [activeSection, setActiveSection] = useState<WorkspaceSettingsSection>("appearance");
const [dimensionDrafts, setDimensionDrafts] = useState(() => ({
width: workspace.width.toFixed(workspace.accuracy),
depth: workspace.depth.toFixed(workspace.accuracy),
}));
const scaleOptions = scaleOptionsForUnits(workspace.units);
const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale);
useEffect(() => {
setDimensionDrafts({
width: workspace.width.toFixed(workspace.accuracy),
depth: workspace.depth.toFixed(workspace.accuracy),
});
}, [workspace.accuracy, workspace.depth, workspace.width]);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false);
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);
const parsed = Number.parseFloat(value);
const next = clamp(Number.isFinite(parsed) ? parsed : workspace[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
setDimensionDrafts((current) => ({ ...current, [key]: next.toFixed(workspace.accuracy) }));
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
};
const setWorkspaceSizePreset = (sizePreset: string) => {
@@ -113,15 +125,6 @@ export function WorkspaceSettingsModal({
<strong>Appearance</strong>
<span>Adjust the canvas and navigation behavior.</span>
</div>
<div className="workspace-row">
<span>Background color</span>
<button
className="workspace-color-button"
style={{ "--workspace-bg": workspace.background } as CSSProperties}
aria-label="Background color"
onClick={() => patchWorkspace({ background: workspace.background === "#f8fbfc" ? "#eaf7fb" : "#f8fbfc" })}
/>
</div>
<WorkspaceToggle label="Show shadows" checked={workspace.showShadows} onChange={(showShadows) => patchWorkspace({ showShadows })} />
<WorkspaceToggle label="Show grid" checked={workspace.showGrid} onChange={(showGrid) => patchWorkspace({ showGrid })} />
<WorkspaceToggle
@@ -199,22 +202,36 @@ export function WorkspaceSettingsModal({
<span>Width</span>
<input
type="number"
value={workspace.width.toFixed(workspace.accuracy)}
value={dimensionDrafts.width}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => setDimension("width", event.currentTarget.value)}
onChange={(event) => {
const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, width: value }));
}}
onBlur={(event) => setDimension("width", event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
</label>
<label>
<span>Length</span>
<input
type="number"
value={workspace.depth.toFixed(workspace.accuracy)}
value={dimensionDrafts.depth}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => setDimension("depth", event.currentTarget.value)}
onChange={(event) => {
const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, depth: value }));
}}
onBlur={(event) => setDimension("depth", event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
</label>
</div>
+14
View File
@@ -0,0 +1,14 @@
export function hasOneToOneCadComponentMapping(sourceCount: number, componentOwners: number[]) {
if (!Number.isInteger(sourceCount) || sourceCount < 2 || componentOwners.length !== sourceCount) {
return false;
}
const owners = new Set<number>();
for (const owner of componentOwners) {
if (!Number.isInteger(owner) || owner < 0 || owner >= sourceCount || owners.has(owner)) {
return false;
}
owners.add(owner);
}
return owners.size === sourceCount;
}
+19
View File
@@ -0,0 +1,19 @@
export const CAD_MODIFIER_RUNTIME_BASE = "/occt";
export const CAD_MODIFIER_REQUEST_TIMEOUT_MS = 30_000;
export type CadModifierRequestPhase = "prepare" | "preview";
export function edgeModifierSelectionStatus(prepared: boolean, selectedCount: number, availableCount: number) {
return prepared ? `${selectedCount} of ${availableCount} sharp edges selected` : "Preparing edges\u2026";
}
export function cadModifierTimeoutMessage(phase: CadModifierRequestPhase) {
if (phase === "preview") {
return "The edge preview timed out. Cancel the tool and try again.";
}
return "Edge preparation timed out. Update to Firefox 121+, Chrome/Brave 114+, or Safari 17.2+, then try again.";
}
export function cadModifierWorkerFailureMessage() {
return "The CAD worker could not start. Update to Firefox 121+, Chrome/Brave 114+, or Safari 17.2+, then try again.";
}
+19
View File
@@ -0,0 +1,19 @@
import { canonicalizeShape } from "@/lib/workplaneShapes";
import type { EdgeTreatmentHistoryEntry, WorkplaneShape } from "@/types/sketchforge";
export function cloneWorkplaneShapeSnapshot(shape: WorkplaneShape): WorkplaneShape {
return JSON.parse(JSON.stringify(canonicalizeShape(shape))) as WorkplaneShape;
}
export function restoreShapeBeforeEdgeTreatment(shape: WorkplaneShape, entry: EdgeTreatmentHistoryEntry) {
const before = cloneWorkplaneShapeSnapshot(entry.before);
return canonicalizeShape({
...before,
id: shape.id,
name: shape.name,
color: shape.color,
hole: shape.hole || undefined,
locked: shape.locked,
hidden: shape.hidden,
});
}
+42
View File
@@ -0,0 +1,42 @@
import type { WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const MIN_VISIBLE_GRID_STEP = 1;
const MAX_VISIBLE_GRID_STEP = 200;
export type GridFootprintBounds = {
minX: number;
minZ: number;
};
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function cleanCoordinate(value: number) {
const rounded = Number(value.toFixed(6));
return Math.abs(rounded) < 1e-6 ? 0 : rounded;
}
export function visibleGridStep(workspace: WorkplaneWorkspaceSettings) {
return clamp(workspace.gridBlockSize, MIN_VISIBLE_GRID_STEP, MAX_VISIBLE_GRID_STEP);
}
function nearestVisibleGridLine(value: number, workspaceSize: number, step: number) {
const gridOrigin = -workspaceSize / 2;
return gridOrigin + Math.round((value - gridOrigin) / step) * step;
}
export function snapShapeFootprintToVisibleGrid(
shape: WorkplaneShape,
bounds: GridFootprintBounds,
workspace: WorkplaneWorkspaceSettings,
) {
const step = visibleGridStep(workspace);
const snappedMinX = nearestVisibleGridLine(bounds.minX, workspace.width, step);
const snappedMinZ = nearestVisibleGridLine(bounds.minZ, workspace.depth, step);
return {
...shape,
x: cleanCoordinate(shape.x + snappedMinX - bounds.minX),
z: cleanCoordinate(shape.z + snappedMinZ - bounds.minZ),
};
}
+547
View File
@@ -0,0 +1,547 @@
import * as THREE from "three";
import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js";
import { createLocalId } from "@/lib/localIds";
import type { WorkplaneShape } from "@/types/sketchforge";
export const MAX_SVG_BYTES = 2 * 1024 * 1024;
export const MAX_SVG_XML_ELEMENTS = 10_000;
export const MAX_SVG_GEOMETRY_ELEMENTS = 2_000;
export const MAX_SVG_PATH_COMMANDS = 50_000;
export const MAX_SVG_TRIANGLES = 200_000;
const SVG_EXTRUSION_DEPTH = 4;
const SVG_CURVE_SEGMENTS = 16;
const MIN_VISIBLE_ALPHA = 1e-6;
const svgLoader = new SVGLoader();
type SvgPathStyle = {
fill?: string;
fillOpacity?: number;
opacity?: number;
visibility?: string;
};
export type TriangleSoupAnalysis = {
triangleCount: number;
vertexCount: number;
surfaceArea: number;
volume: number;
degenerateTriangles: number;
boundaryEdges: number;
nonManifoldEdges: number;
width: number;
height: number;
depth: number;
volumeTolerance: number;
};
type SvgRing = {
points: THREE.Vector2[];
area: number;
parent: number | null;
depth: number;
};
function sourceByteLength(source: string) {
return new TextEncoder().encode(source).byteLength;
}
function attributeValues(source: string, name: string) {
const values: string[] = [];
const expression = new RegExp(`\\b${name}\\s*=\\s*(["'])(.*?)\\1`, "gis");
let match: RegExpExecArray | null;
while ((match = expression.exec(source))) values.push(match[2]);
return values;
}
export function validateSvgSourcePreflight(source: string) {
if (!source.trim()) throw new Error("SVG file is empty");
if (sourceByteLength(source) > MAX_SVG_BYTES) {
throw new Error(`SVG is too large. The maximum supported size is ${MAX_SVG_BYTES / 1024 / 1024} MB`);
}
if (/<!DOCTYPE|<!ENTITY/i.test(source)) {
throw new Error("SVG document types and entities are not supported");
}
const xmlElementCount = source.match(/<[a-z][^!?/\s>]*/gi)?.length ?? 0;
if (xmlElementCount > MAX_SVG_XML_ELEMENTS) {
throw new Error(`SVG is too complex (${xmlElementCount} elements; maximum ${MAX_SVG_XML_ELEMENTS})`);
}
const geometryElementCount = source.match(/<(?:path|rect|polygon|polyline|circle|ellipse|line|use)\b/gi)?.length ?? 0;
if (geometryElementCount > MAX_SVG_GEOMETRY_ELEMENTS) {
throw new Error(`SVG has too many geometry elements (${geometryElementCount}; maximum ${MAX_SVG_GEOMETRY_ELEMENTS})`);
}
let pathCommandCount = 0;
for (const pathData of attributeValues(source, "d")) {
pathCommandCount += pathData.match(/[MmZzLlHhVvCcSsQqTtAa]/g)?.length ?? 0;
if (pathCommandCount > MAX_SVG_PATH_COMMANDS) {
throw new Error(`SVG has too many path commands (maximum ${MAX_SVG_PATH_COMMANDS})`);
}
}
for (const href of [...attributeValues(source, "href"), ...attributeValues(source, "xlink:href")]) {
if (href && !href.trim().startsWith("#")) {
throw new Error("SVG external references are not supported; embed referenced artwork in the file");
}
}
}
export function normalizeSvgUseReferences(source: string) {
if (!/<use\b/i.test(source)) return source;
let normalized = source.replace(/<use\b[^>]*>/gi, (tag) => {
if (/\bxlink:href\s*=/i.test(tag)) return tag;
return tag.replace(/\bhref(\s*=)/i, "xlink:href$1");
});
if (/\bxlink:href\s*=/i.test(normalized) && !/\bxmlns:xlink\s*=/i.test(normalized)) {
normalized = normalized.replace(/<svg\b/i, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}
return normalized;
}
function numericStyleValue(value: unknown, fallback = 1) {
const parsed = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
return Number.isFinite(parsed) ? parsed : fallback;
}
function fillAlpha(fill: string | undefined) {
const normalized = fill?.trim().toLowerCase();
if (!normalized || normalized === "none" || normalized === "transparent") return normalized ? 0 : 1;
const shortHexAlpha = normalized.match(/^#[0-9a-f]{3}([0-9a-f])$/i)?.[1];
if (shortHexAlpha) return Number.parseInt(shortHexAlpha + shortHexAlpha, 16) / 255;
const longHexAlpha = normalized.match(/^#[0-9a-f]{6}([0-9a-f]{2})$/i)?.[1];
if (longHexAlpha) return Number.parseInt(longHexAlpha, 16) / 255;
const functional = normalized.match(/^(?:rgba|hsla)\([^,]+,[^,]+,[^,]+,\s*([^)]+)\)$/i)?.[1];
if (!functional) return 1;
if (functional.trim().endsWith("%")) return Number.parseFloat(functional) / 100;
return Number.parseFloat(functional);
}
function elementStyleValue(element: Element, property: string) {
const style = (element as Element & { style?: CSSStyleDeclaration }).style;
const fromStyle = style?.getPropertyValue(property);
if (fromStyle) return fromStyle;
const camelCase = property.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());
const direct = style?.[camelCase as keyof CSSStyleDeclaration];
return typeof direct === "string" ? direct : element.getAttribute(property);
}
function elementOrAncestorSuppressesRendering(element: Element | null | undefined) {
let current = element;
while (current) {
const display = elementStyleValue(current, "display")?.trim().toLowerCase();
if (display === "none" || current.hasAttribute("hidden")) return true;
const opacity = elementStyleValue(current, "opacity");
if (opacity !== null && opacity !== undefined && numericStyleValue(opacity) <= MIN_VISIBLE_ALPHA) return true;
current = current.parentElement;
}
return false;
}
function pathIsFilledAndVisible(path: THREE.ShapePath) {
const userData = (path as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData;
const style = userData?.style ?? {};
const visibility = style.visibility?.trim().toLowerCase();
if (visibility === "hidden" || visibility === "collapse") return false;
if (numericStyleValue(style.opacity) <= MIN_VISIBLE_ALPHA) return false;
if (numericStyleValue(style.fillOpacity) <= MIN_VISIBLE_ALPHA) return false;
if (fillAlpha(style.fill) <= MIN_VISIBLE_ALPHA) return false;
return !elementOrAncestorSuppressesRendering(userData?.node);
}
function cleanRingPoints(points: THREE.Vector2[]) {
const cleaned: THREE.Vector2[] = [];
for (const point of points) {
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) continue;
if (!cleaned.length || cleaned[cleaned.length - 1].distanceToSquared(point) > 1e-20) cleaned.push(point.clone());
}
if (cleaned.length > 1 && cleaned[0].distanceToSquared(cleaned[cleaned.length - 1]) <= 1e-20) cleaned.pop();
return cleaned;
}
function ringSamplePoint(points: THREE.Vector2[]) {
const triangles = THREE.ShapeUtils.triangulateShape(points, []);
const triangle = triangles[0];
if (!triangle) return points[0].clone();
return points[triangle[0]].clone().add(points[triangle[1]]).add(points[triangle[2]]).multiplyScalar(1 / 3);
}
function pointOnSegment(point: THREE.Vector2, a: THREE.Vector2, b: THREE.Vector2, tolerance: number) {
const ab = b.clone().sub(a);
const ap = point.clone().sub(a);
const cross = Math.abs(ab.x * ap.y - ab.y * ap.x);
if (cross > tolerance * Math.max(1, ab.length())) return false;
const dot = ap.dot(ab);
return dot >= -tolerance && dot <= ab.lengthSq() + tolerance;
}
function pointInRing(point: THREE.Vector2, ring: THREE.Vector2[]) {
let inside = false;
const extent = ring.reduce((largest, entry) => Math.max(largest, Math.abs(entry.x), Math.abs(entry.y)), 1);
const tolerance = extent * 1e-9;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
const a = ring[j];
const b = ring[i];
if (pointOnSegment(point, a, b, tolerance)) return true;
if ((a.y > point.y) !== (b.y > point.y) && point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
}
return inside;
}
function orientation(a: THREE.Vector2, b: THREE.Vector2, c: THREE.Vector2) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
function ringsIntersect(a: THREE.Vector2[], b: THREE.Vector2[]) {
const scale = [...a, ...b].reduce((largest, point) => Math.max(largest, Math.abs(point.x), Math.abs(point.y)), 1);
const tolerance = scale * 1e-9;
for (let ai = 0; ai < a.length; ai += 1) {
const a0 = a[ai];
const a1 = a[(ai + 1) % a.length];
for (let bi = 0; bi < b.length; bi += 1) {
const b0 = b[bi];
const b1 = b[(bi + 1) % b.length];
const o1 = orientation(a0, a1, b0);
const o2 = orientation(a0, a1, b1);
const o3 = orientation(b0, b1, a0);
const o4 = orientation(b0, b1, a1);
if (((o1 > tolerance && o2 < -tolerance) || (o1 < -tolerance && o2 > tolerance)) &&
((o3 > tolerance && o4 < -tolerance) || (o3 < -tolerance && o4 > tolerance))) return true;
if (Math.abs(o1) <= tolerance && pointOnSegment(b0, a0, a1, tolerance)) return true;
if (Math.abs(o2) <= tolerance && pointOnSegment(b1, a0, a1, tolerance)) return true;
if (Math.abs(o3) <= tolerance && pointOnSegment(a0, b0, b1, tolerance)) return true;
if (Math.abs(o4) <= tolerance && pointOnSegment(a1, b0, b1, tolerance)) return true;
}
}
return false;
}
function composeNestedRings(shapes: THREE.Shape[]) {
const rings: SvgRing[] = [];
for (const shape of shapes) {
const extracted = shape.extractPoints(SVG_CURVE_SEGMENTS);
for (const rawPoints of [extracted.shape, ...extracted.holes]) {
const points = cleanRingPoints(rawPoints);
if (points.length < 3) continue;
const area = Math.abs(THREE.ShapeUtils.area(points));
const extent = points.reduce((largest, point) => Math.max(largest, Math.abs(point.x), Math.abs(point.y)), 1);
if (!Number.isFinite(area) || area <= (extent * 1e-9) ** 2) {
continue;
}
rings.push({ points, area, parent: null, depth: 0 });
}
}
if (!rings.length) throw new Error("SVG has no readable filled paths");
rings.sort((a, b) => b.area - a.area);
for (let index = 0; index < rings.length; index += 1) {
const ring = rings[index];
const sample = ringSamplePoint(ring.points);
for (let candidate = index - 1; candidate >= 0; candidate -= 1) {
const possibleParent = rings[candidate];
if (possibleParent.area <= ring.area || !pointInRing(sample, possibleParent.points)) continue;
if (ringsIntersect(ring.points, possibleParent.points)) continue;
if (ring.parent === null || possibleParent.area < rings[ring.parent].area) ring.parent = candidate;
}
ring.depth = ring.parent === null ? 0 : rings[ring.parent].depth + 1;
}
const composed: THREE.Shape[] = [];
const shapeByRing = new Map<number, THREE.Shape>();
for (let index = 0; index < rings.length; index += 1) {
const ring = rings[index];
if (ring.depth % 2 !== 0) continue;
const shape = new THREE.Shape(ring.points);
shape.autoClose = true;
composed.push(shape);
shapeByRing.set(index, shape);
}
for (let index = 0; index < rings.length; index += 1) {
const ring = rings[index];
if (ring.depth % 2 === 0 || ring.parent === null) continue;
let solidParent: number | null = ring.parent;
while (solidParent !== null && rings[solidParent].depth % 2 !== 0) solidParent = rings[solidParent].parent;
const shape = solidParent === null ? undefined : shapeByRing.get(solidParent);
if (!shape) continue;
const hole = new THREE.Path(ring.points);
hole.autoClose = true;
shape.holes.push(hole);
}
return composed;
}
function edgeKey(a: number, b: number) {
return a < b ? `${a}:${b}` : `${b}:${a}`;
}
export function analyzeTriangleSoup(positions: readonly number[]): TriangleSoupAnalysis {
if (positions.length < 9 || positions.length % 9 !== 0) {
throw new Error("Mesh does not contain complete triangles");
}
if (positions.some((value) => !Number.isFinite(value))) throw new Error("Mesh contains non-finite coordinates");
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let index = 0; index < positions.length; index += 3) {
minX = Math.min(minX, positions[index]);
minY = Math.min(minY, positions[index + 1]);
minZ = Math.min(minZ, positions[index + 2]);
maxX = Math.max(maxX, positions[index]);
maxY = Math.max(maxY, positions[index + 1]);
maxZ = Math.max(maxZ, positions[index + 2]);
}
const width = maxX - minX;
const height = maxY - minY;
const depth = maxZ - minZ;
const largestDimension = Math.max(width, height, depth);
const quantization = Math.max(largestDimension * 1e-7, 1e-9);
const areaTolerance = quantization * quantization;
const volumeTolerance = Math.max(width * height * depth * 1e-9, quantization ** 3);
const vertexIds = new Map<string, number>();
const parent: number[] = [];
const find = (value: number): number => {
let root = value;
while (parent[root] !== root) root = parent[root];
while (parent[value] !== value) {
const next = parent[value];
parent[value] = root;
value = next;
}
return root;
};
const union = (a: number, b: number) => {
const rootA = find(a);
const rootB = find(b);
if (rootA !== rootB) parent[rootB] = rootA;
};
const idForVertex = (x: number, y: number, z: number) => {
const key = `${Math.round(x / quantization)},${Math.round(y / quantization)},${Math.round(z / quantization)}`;
const existing = vertexIds.get(key);
if (existing !== undefined) return existing;
const id = vertexIds.size;
vertexIds.set(key, id);
parent.push(id);
return id;
};
const edges = new Map<string, number>();
const triangleComponents: Array<{ vertex: number; signedVolume: number }> = [];
let surfaceArea = 0;
let degenerateTriangles = 0;
for (let index = 0; index < positions.length; index += 9) {
const ax = positions[index];
const ay = positions[index + 1];
const az = positions[index + 2];
const bx = positions[index + 3];
const by = positions[index + 4];
const bz = positions[index + 5];
const cx = positions[index + 6];
const cy = positions[index + 7];
const cz = positions[index + 8];
const a = idForVertex(ax, ay, az);
const b = idForVertex(bx, by, bz);
const c = idForVertex(cx, cy, cz);
union(a, b);
union(b, c);
const abx = bx - ax;
const aby = by - ay;
const abz = bz - az;
const acx = cx - ax;
const acy = cy - ay;
const acz = cz - az;
const crossX = aby * acz - abz * acy;
const crossY = abz * acx - abx * acz;
const crossZ = abx * acy - aby * acx;
const area = Math.hypot(crossX, crossY, crossZ) / 2;
if (a === b || b === c || c === a || area <= areaTolerance) degenerateTriangles += 1;
surfaceArea += area;
edges.set(edgeKey(a, b), (edges.get(edgeKey(a, b)) ?? 0) + 1);
edges.set(edgeKey(b, c), (edges.get(edgeKey(b, c)) ?? 0) + 1);
edges.set(edgeKey(c, a), (edges.get(edgeKey(c, a)) ?? 0) + 1);
const signedVolume = (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6;
triangleComponents.push({ vertex: a, signedVolume });
}
const componentVolumes = new Map<number, number>();
for (const triangle of triangleComponents) {
const root = find(triangle.vertex);
componentVolumes.set(root, (componentVolumes.get(root) ?? 0) + triangle.signedVolume);
}
let boundaryEdges = 0;
let nonManifoldEdges = 0;
for (const count of edges.values()) {
if (count === 1) boundaryEdges += 1;
else if (count !== 2) nonManifoldEdges += 1;
}
return {
triangleCount: positions.length / 9,
vertexCount: vertexIds.size,
surfaceArea,
volume: [...componentVolumes.values()].reduce((total, value) => total + Math.abs(value), 0),
degenerateTriangles,
boundaryEdges,
nonManifoldEdges,
width,
height,
depth,
volumeTolerance,
};
}
export function validateClosedSolidTriangleSoup(positions: readonly number[], label = "SVG") {
const analysis = analyzeTriangleSoup(positions);
if (analysis.triangleCount > MAX_SVG_TRIANGLES) {
throw new Error(`${label} is too complex (${analysis.triangleCount} triangles; maximum ${MAX_SVG_TRIANGLES})`);
}
if (analysis.degenerateTriangles > 0) {
throw new Error(`${label} contains ${analysis.degenerateTriangles} zero-area triangle${analysis.degenerateTriangles === 1 ? "" : "s"}`);
}
if (analysis.boundaryEdges > 0 || analysis.nonManifoldEdges > 0) {
throw new Error(`${label} is not a watertight manifold (${analysis.boundaryEdges} open edge${analysis.boundaryEdges === 1 ? "" : "s"}, ${analysis.nonManifoldEdges} non-manifold edge${analysis.nonManifoldEdges === 1 ? "" : "s"})`);
}
if (analysis.width <= 0 || analysis.height <= 0 || analysis.depth <= 0 || analysis.surfaceArea <= 0 || analysis.volume <= analysis.volumeTolerance) {
throw new Error(`${label} does not enclose a non-zero volume`);
}
return analysis;
}
export function buildSvgExtrusionFromPaths(paths: readonly THREE.ShapePath[]) {
const visiblePaths = paths.filter(pathIsFilledAndVisible);
if (!visiblePaths.length) throw new Error("SVG has no readable visible filled paths");
const sourceShapes = visiblePaths.flatMap((path) => SVGLoader.createShapes(path));
const shapes = composeNestedRings(sourceShapes);
const rawPositions: number[] = [];
const acceptedAnalyses: TriangleSoupAnalysis[] = [];
for (const shape of shapes) {
const rawGeometry = new THREE.ExtrudeGeometry(shape, {
depth: SVG_EXTRUSION_DEPTH,
bevelEnabled: false,
curveSegments: SVG_CURVE_SEGMENTS,
steps: 1,
});
rawGeometry.rotateX(-Math.PI / 2);
const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry;
const position = geometry.getAttribute("position");
const candidatePositions: number[] = [];
for (let index = 0; index < position.count; index += 1) {
candidatePositions.push(position.getX(index), position.getY(index), position.getZ(index));
}
let candidateAnalysis: TriangleSoupAnalysis | null = null;
try {
candidateAnalysis = validateClosedSolidTriangleSoup(candidatePositions);
} catch {
candidateAnalysis = null;
}
if (candidateAnalysis && rawPositions.length / 9 + candidateAnalysis.triangleCount > MAX_SVG_TRIANGLES) {
if (geometry !== rawGeometry) geometry.dispose();
rawGeometry.dispose();
throw new Error(`SVG is too complex (maximum ${MAX_SVG_TRIANGLES} triangles)`);
}
if (candidateAnalysis) {
rawPositions.push(...candidatePositions);
acceptedAnalyses.push(candidateAnalysis);
}
if (geometry !== rawGeometry) geometry.dispose();
rawGeometry.dispose();
}
if (!rawPositions.length) throw new Error("SVG has no filled contours that can be converted into a solid");
const combinedAnalysis = analyzeTriangleSoup(rawPositions);
const analysis: TriangleSoupAnalysis = {
...combinedAnalysis,
surfaceArea: acceptedAnalyses.reduce((total, entry) => total + entry.surfaceArea, 0),
volume: acceptedAnalyses.reduce((total, entry) => total + entry.volume, 0),
degenerateTriangles: 0,
boundaryEdges: 0,
nonManifoldEdges: 0,
};
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(rawPositions, 3));
geometry.computeVertexNormals();
const normal = geometry.getAttribute("normal");
const rawNormals: number[] = [];
for (let index = 0; index < normal.count; index += 1) rawNormals.push(normal.getX(index), normal.getY(index), normal.getZ(index));
geometry.dispose();
return { rawPositions, rawNormals, analysis };
}
export function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
validateSvgSourcePreflight(source);
const parsed = svgLoader.parse(normalizeSvgUseReferences(source));
const parsedXml = parsed.xml as unknown as XMLDocument | Element;
const root = "documentElement" in parsedXml ? parsedXml.documentElement : parsedXml;
if (root.localName !== "svg" || root.querySelector("parsererror")) {
throw new Error("SVG is not valid XML");
}
const { rawPositions, rawNormals, analysis } = buildSvgExtrusionFromPaths(parsed.paths);
const centerX = analysis.width / 2;
const centerZ = analysis.depth / 2;
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
for (let index = 0; index < rawPositions.length; index += 3) {
minX = Math.min(minX, rawPositions[index]);
minY = Math.min(minY, rawPositions[index + 1]);
minZ = Math.min(minZ, rawPositions[index + 2]);
}
const positions: number[] = [];
for (let index = 0; index < rawPositions.length; index += 3) {
positions.push(rawPositions[index] - minX - centerX, rawPositions[index + 1] - minY, rawPositions[index + 2] - minZ - centerZ);
}
return {
id: createLocalId("uploaded-svg"),
name: fileName.replace(/\.[^.]+$/, "") || "Imported SVG",
kind: "mesh",
color: "#0098c7",
x: 10,
z: -10,
size: Math.max(analysis.width, analysis.depth),
width: analysis.width,
depth: analysis.depth,
height: analysis.height,
rotation: 0,
rotationX: 0,
rotationZ: 0,
importedMesh: {
positions,
normals: rawNormals,
baseWidth: analysis.width,
baseDepth: analysis.depth,
baseHeight: analysis.height,
triangleCount: analysis.triangleCount,
sourceFormat: "svg",
},
locked: false,
hidden: false,
};
}
export function invalidSvgMeshReason(shape: WorkplaneShape) {
if (shape.importedMesh?.sourceFormat !== "svg") return null;
try {
validateClosedSolidTriangleSoup(shape.importedMesh.positions, `SVG mesh "${shape.name}"`);
return null;
} catch (error) {
return error instanceof Error ? error.message : `SVG mesh "${shape.name}" is invalid`;
}
}
+45
View File
@@ -0,0 +1,45 @@
const WORKPLANE_BOUNDARY_EPSILON = 0.0001;
export const WORKPLANE_LINE_ELEVATION = 0;
export type WorkplaneGridCoordinate = {
coordinate: number;
index: number;
};
export type WorkplaneGridPalette = {
minor: { color: string; opacity: number };
major: { color: string; opacity: number };
axis: { color: string; opacity: number };
border: { color: string; opacity: number };
};
export function workplaneGridPalette(): WorkplaneGridPalette {
return {
minor: { color: "#91dff0", opacity: 0.55 },
major: { color: "#4bbddf", opacity: 0.7 },
axis: { color: "#34aad2", opacity: 0.88 },
border: { color: "#58c5e6", opacity: 0.9 },
};
}
export function interiorWorkplaneGridCoordinates(span: number, step: number): WorkplaneGridCoordinate[] {
if (!Number.isFinite(span) || !Number.isFinite(step) || span <= 0 || step <= 0) {
return [];
}
const halfSpan = span / 2;
const count = Math.floor(span / step);
const coordinates: WorkplaneGridCoordinate[] = [];
for (let index = 0; index <= count; index += 1) {
const rawCoordinate = -halfSpan + index * step;
const coordinate = Math.abs(rawCoordinate) < WORKPLANE_BOUNDARY_EPSILON ? 0 : rawCoordinate;
const isBoundary = Math.abs(Math.abs(coordinate) - halfSpan) < WORKPLANE_BOUNDARY_EPSILON;
if (!isBoundary) {
coordinates.push({ coordinate, index });
}
}
return coordinates;
}
+10
View File
@@ -98,6 +98,16 @@ export function fallbackSolidColor(shape: WorkplaneShape) {
return "#d41721";
}
export function withHoleMode(shape: WorkplaneShape, hole: boolean, parentColor?: string): WorkplaneShape {
const color = hole ? "#b8c2cc" : (parentColor ?? fallbackSolidColor(shape));
return {
...shape,
hole,
color,
groupedShapes: shape.groupedShapes?.map((child) => withHoleMode(child, hole, parentColor)),
};
}
export function mirrorSign(value?: boolean) {
return value ? -1 : 1;
}
+3 -2
View File
@@ -2,6 +2,7 @@
import { OcctKernel, type ShapeHandle } from "occt-wasm";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import { CAD_MODIFIER_RUNTIME_BASE } from "@/lib/cadModifierRuntime";
const HASH_UPPER_BOUND = 2_147_483_647;
const CAD_EDGE_WIREFRAME_DEFLECTION = 0.035;
@@ -25,9 +26,9 @@ function post(message: CadModifierWorkerResponse, transfer: Transferable[] = [])
}
function kernel() {
const moduleUrl = "/assets/occt/occt-wasm.js";
const moduleUrl = `${CAD_MODIFIER_RUNTIME_BASE}/occt-wasm.js`;
kernelPromise ??= import(/* webpackIgnore: true */ moduleUrl).then((imported: { default: (options?: { locateFile?: (path: string) => string }) => Promise<unknown> }) => imported.default({
locateFile: (path) => path.endsWith(".wasm") ? "/assets/occt/occt-wasm.wasm" : path,
locateFile: (path) => path.endsWith(".wasm") ? `${CAD_MODIFIER_RUNTIME_BASE}/occt-wasm.wasm` : path,
})).then((module) => {
const KernelConstructor = OcctKernel as unknown as new (rawModule: unknown) => OcctKernel;
return new KernelConstructor(module);