checkpoint: stabilize editor geometry and workspace settings

This commit is contained in:
Formsmith
2026-06-19 21:47:13 +03:00
parent 272fac5069
commit 2d0ed7ef23
8 changed files with 316 additions and 85 deletions
+87 -41
View File
@@ -118,6 +118,7 @@ const CUTTER_PADDING = 0.05;
const POINT_TOLERANCE = 0.0001;
const CUTTER_RESIDUAL_INSET = CUTTER_PADDING * 0.4;
const MIN_SHAPE_DIMENSION = 0.01;
const MODEL_DIMENSION_PRECISION = 3;
const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000;
const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02;
const svgLoader = new SVGLoader();
@@ -133,6 +134,18 @@ const booleanTextFonts: Record<string, Font> = {
};
let manifoldRuntimePromise: Promise<ManifoldToplevel> | null = null;
function cleanModelDimension(value: number) {
return Math.max(MIN_SHAPE_DIMENSION, Number(value.toFixed(MODEL_DIMENSION_PRECISION)));
}
function meshYawDegrees(shape: WorkplaneShape) {
const isRoundPrimitive = !shape.importedMesh && (shape.kind === "cylinder" || shape.kind === "cone");
const isCircular = Math.abs(shapeWidth(shape) - shapeDepth(shape)) < 0.0005;
// A circular cylinder/cone is invariant around Y. Ignoring that purely visual
// yaw keeps its tessellated export at the requested diameter after grouping.
return isRoundPrimitive && isCircular ? 0 : shape.rotation;
}
function readSharedClipboard() {
if (typeof window === "undefined") {
return [];
@@ -695,7 +708,7 @@ function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData {
const matrix = new THREE.Matrix4().makeRotationFromEuler(
new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
THREE.MathUtils.degToRad(shape.rotation),
THREE.MathUtils.degToRad(meshYawDegrees(shape)),
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
"XYZ",
),
@@ -1228,9 +1241,12 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
const width = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const height = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const depth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const rawWidth = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const rawHeight = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const rawDepth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const width = cleanModelDimension(rawWidth);
const height = cleanModelDimension(rawHeight);
const depth = cleanModelDimension(rawDepth);
const positions: number[] = [];
mesh.faces.forEach(([ai, bi, ci]) => {
@@ -1257,9 +1273,9 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
mirrorZ: undefined,
importedMesh: {
positions,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
baseWidth: rawWidth,
baseDepth: rawDepth,
baseHeight: rawHeight,
triangleCount: mesh.faces.length,
sourceFormat: "json",
},
@@ -2600,9 +2616,12 @@ function booleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
const centerX = (groupBounds.minX + groupBounds.maxX) / 2;
const centerZ = (groupBounds.minZ + groupBounds.maxZ) / 2;
const minY = groupBounds.minY;
const width = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxX - groupBounds.minX);
const height = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxY - groupBounds.minY);
const depth = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxZ - groupBounds.minZ);
const rawWidth = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxX - groupBounds.minX);
const rawHeight = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxY - groupBounds.minY);
const rawDepth = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxZ - groupBounds.minZ);
const width = cleanModelDimension(rawWidth);
const height = cleanModelDimension(rawHeight);
const depth = cleanModelDimension(rawDepth);
const positions: number[] = [];
for (let i = 0; i < resultPositions.length; i += 3) {
@@ -2630,9 +2649,9 @@ function booleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
rotation: 0,
importedMesh: {
positions,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
baseWidth: rawWidth,
baseDepth: rawDepth,
baseHeight: rawHeight,
triangleCount: nextTriangleCount,
sourceFormat: "json",
},
@@ -2663,9 +2682,12 @@ function resultGeometryToMeshShape(
const centerX = (groupBounds.minX + groupBounds.maxX) / 2;
const centerZ = (groupBounds.minZ + groupBounds.maxZ) / 2;
const minY = groupBounds.minY;
const width = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxX - groupBounds.minX);
const height = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxY - groupBounds.minY);
const depth = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxZ - groupBounds.minZ);
const rawWidth = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxX - groupBounds.minX);
const rawHeight = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxY - groupBounds.minY);
const rawDepth = Math.max(MIN_SHAPE_DIMENSION, groupBounds.maxZ - groupBounds.minZ);
const width = cleanModelDimension(rawWidth);
const height = cleanModelDimension(rawHeight);
const depth = cleanModelDimension(rawDepth);
const positions: number[] = [];
for (let i = 0; i < resultPositions.length; i += 3) {
@@ -2689,9 +2711,9 @@ function resultGeometryToMeshShape(
rotation: 0,
importedMesh: {
positions,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
baseWidth: rawWidth,
baseDepth: rawDepth,
baseHeight: rawHeight,
triangleCount: Math.floor(positions.length / 9),
sourceFormat: "json",
},
@@ -2829,7 +2851,7 @@ function shapeRotationQuaternion(shape: WorkplaneShape) {
return new THREE.Quaternion().setFromEuler(
new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
THREE.MathUtils.degToRad(shape.rotation),
THREE.MathUtils.degToRad(meshYawDegrees(shape)),
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
"XYZ",
),
@@ -2992,9 +3014,12 @@ function meshPositionsToGroupShape(selection: WorkplaneShape[], solids: Workplan
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
const width = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const height = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const depth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const rawWidth = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const rawHeight = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const rawDepth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const width = cleanModelDimension(rawWidth);
const height = cleanModelDimension(rawHeight);
const depth = cleanModelDimension(rawDepth);
const normalizedPositions: number[] = [];
for (let i = 0; i < positions.length; i += 3) {
normalizedPositions.push(positions[i] - centerX, positions[i + 1] - minY, positions[i + 2] - centerZ);
@@ -3016,9 +3041,9 @@ function meshPositionsToGroupShape(selection: WorkplaneShape[], solids: Workplan
rotation: 0,
importedMesh: {
positions: normalizedPositions,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
baseWidth: rawWidth,
baseDepth: rawDepth,
baseHeight: rawHeight,
triangleCount: Math.floor(normalizedPositions.length / 9),
sourceFormat: "json",
},
@@ -3570,9 +3595,12 @@ function hollowClipMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
const width = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const height = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const depth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const rawWidth = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const rawHeight = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const rawDepth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const width = cleanModelDimension(rawWidth);
const height = cleanModelDimension(rawHeight);
const depth = cleanModelDimension(rawDepth);
const normalizedPositions: number[] = [];
for (let i = 0; i < positions.length; i += 3) {
normalizedPositions.push(positions[i] - centerX, positions[i + 1] - minY, positions[i + 2] - centerZ);
@@ -3594,9 +3622,9 @@ function hollowClipMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null
rotation: 0,
importedMesh: {
positions: normalizedPositions,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
baseWidth: rawWidth,
baseDepth: rawDepth,
baseHeight: rawHeight,
triangleCount: Math.floor(normalizedPositions.length / 9),
sourceFormat: "json",
},
@@ -3671,9 +3699,12 @@ function mergedMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
const width = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const height = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const depth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const rawWidth = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const rawHeight = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const rawDepth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const width = cleanModelDimension(rawWidth);
const height = cleanModelDimension(rawHeight);
const depth = cleanModelDimension(rawDepth);
const positions: number[] = [];
faces.forEach(([ai, bi, ci]) => {
@@ -3701,9 +3732,9 @@ function mergedMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
rotation: 0,
importedMesh: {
positions,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
baseWidth: rawWidth,
baseDepth: rawDepth,
baseHeight: rawHeight,
triangleCount: faces.length,
sourceFormat: "json",
},
@@ -3731,9 +3762,9 @@ function groupedShape(selection: WorkplaneShape[]): WorkplaneShape | null {
const maxZ = groupBounds.maxZ;
const centerX = (minX + maxX) / 2;
const centerZ = (minZ + maxZ) / 2;
const width = Math.max(MIN_SHAPE_DIMENSION, maxX - minX);
const depth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ);
const height = Math.max(MIN_SHAPE_DIMENSION, maxY - minY);
const width = cleanModelDimension(Math.max(MIN_SHAPE_DIMENSION, maxX - minX));
const depth = cleanModelDimension(Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ));
const height = cleanModelDimension(Math.max(MIN_SHAPE_DIMENSION, maxY - minY));
const firstSolid = groupable.find((shape) => !shape.hole) ?? groupable[0];
const holeOnly = groupable.every((shape) => shape.hole);
@@ -4020,6 +4051,21 @@ export function SketchForgeEditor({
const interactionHistoryTimerRef = useRef<number | null>(null);
const [projectInteractionActive, setProjectInteractionActive] = useState(false);
useEffect(() => {
const warmBooleanRuntime = () => {
void getManifoldRuntime().catch(() => {
// Allow a real grouping action to retry if an idle preload was interrupted.
manifoldRuntimePromise = null;
});
};
if ("requestIdleCallback" in window) {
const idleId = window.requestIdleCallback(warmBooleanRuntime, { timeout: 1500 });
return () => window.cancelIdleCallback(idleId);
}
const timer = globalThis.setTimeout(warmBooleanRuntime, 250);
return () => globalThis.clearTimeout(timer);
}, []);
useEffect(() => {
const applyTitles = () => {
document.querySelectorAll<HTMLButtonElement>("button").forEach((button) => {
+121 -20
View File
@@ -34,16 +34,18 @@ import {
type TransformHandleKind,
type TransformOverlayState,
} from "@/components/workplane/TransformOverlay";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, MeasurementAccuracy, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const WORKPLANE_WIDTH = 200;
const WORKPLANE_DEPTH = 140;
const MIN_GRID_BLOCK_SIZE = 1;
const MAX_GRID_BLOCK_SIZE = 200;
const WORKSPACE_DEFAULTS_STORAGE_PREFIX = "sketchForge.workspaceDefault.";
const DEFAULT_WORKSPACE = DEFAULT_WORKPLANE_WORKSPACE;
const CAMERA_HOME = new THREE.Vector3(118, 96, 118);
const CAMERA_TARGET = new THREE.Vector3(0, 0, 0);
const MIN_SHAPE_SIZE = 0.01;
const CUT_PREVIEW_PADDING = 0.01;
const MIN_ELEVATION = -180;
const MAX_ELEVATION = 220;
const CAMERA_MIN_TARGET_Y = -70;
@@ -147,6 +149,27 @@ type WorkplaneViewportProps = {
type WorkspaceSettings = WorkplaneWorkspaceSettings;
function readSavedWorkspaceDefault(key: string | null) {
if (!key || typeof window === "undefined") {
return null;
}
try {
const parsed = JSON.parse(window.localStorage.getItem(`${WORKSPACE_DEFAULTS_STORAGE_PREFIX}${key}`) ?? "null") as {
workspace?: unknown;
snap?: unknown;
} | null;
if (!parsed) {
return null;
}
return {
workspace: normalizeWorkspaceSettings(parsed.workspace),
snap: normalizeSnapGrid(parsed.snap, DEFAULT_SNAP_GRID),
};
} catch {
return null;
}
}
type ThreeState = {
renderer: THREE.WebGLRenderer;
scene: THREE.Scene;
@@ -494,6 +517,7 @@ function syncRulerOverlay(
model: RulerModel,
overlayRef: MutableRefObject<RulerOverlayState | null>,
setOverlay: Dispatch<SetStateAction<RulerOverlayState | null>>,
accuracy: MeasurementAccuracy,
) {
const projectedPoints = new Map<string, { screenX: number; screenY: number }>();
const points = model.points.map((point) => {
@@ -519,7 +543,7 @@ function syncRulerOverlay(
y2: endScreen.screenY,
labelX: (startScreen.screenX + endScreen.screenX) / 2,
labelY: (startScreen.screenY + endScreen.screenY) / 2 - 18,
label: formatMeasure(Math.hypot(end.x - start.x, end.z - start.z)),
label: formatMeasure(Math.hypot(end.x - start.x, end.z - start.z), accuracy),
},
];
});
@@ -1165,8 +1189,10 @@ export function WorkplaneViewport({
workspaceSettingsKeyRef.current = nextKey;
lastWorkspaceSettingsSyncRef.current = "";
}
setSnap(normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID));
setWorkspace(normalizeWorkspaceSettings(initialWorkspace));
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));
}, [initialSnap, initialWorkspace, workspaceSettingsKey]);
useEffect(() => {
@@ -1180,6 +1206,23 @@ export function WorkplaneViewport({
onWorkspaceSettingsChange?.({ workspace: normalizedWorkspace, snap: normalizedSnap });
}, [onWorkspaceSettingsChange, snap, workspace]);
const makeWorkspaceDefault = useCallback(() => {
const normalizedWorkspace = normalizeWorkspaceSettings(workspace);
const normalizedSnap = normalizeSnapGrid(snap, DEFAULT_SNAP_GRID);
const key = workspaceSettingsKeyRef.current;
if (key) {
try {
window.localStorage.setItem(
`${WORKSPACE_DEFAULTS_STORAGE_PREFIX}${key}`,
JSON.stringify({ workspace: normalizedWorkspace, snap: normalizedSnap }),
);
} catch {
// Project persistence below is still attempted if browser storage is unavailable.
}
}
onWorkspaceSettingsChange?.({ workspace: normalizedWorkspace, snap: normalizedSnap });
}, [onWorkspaceSettingsChange, snap, workspace]);
useEffect(() => {
const openWorkspaceSettings = () => setSettingsOpen(true);
window.addEventListener("sketchforge:open-workspace-settings", openWorkspaceSettings);
@@ -1190,7 +1233,15 @@ export function WorkplaneViewport({
shapesRef.current = shapes;
rebuildShapes(threeRef.current, shapes, selectedIdsRef.current, !transformRef.current && !dragRef.current);
if (threeRef.current) {
syncTransformOverlay(threeRef.current, shapes, selectedIdsRef.current, transformOverlayRef, setTransformOverlay, Boolean(transformRef.current || dragRef.current));
syncTransformOverlay(
threeRef.current,
shapes,
selectedIdsRef.current,
transformOverlayRef,
setTransformOverlay,
workspaceRef.current.accuracy,
Boolean(transformRef.current || dragRef.current),
);
syncAlignOverlay(threeRef.current, alignReferenceShapesRef.current, selectedIdsRef.current, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay);
syncMirrorOverlay(threeRef.current, mirrorReferenceShapesRef.current, selectedIdsRef.current, mirrorModeRef.current, mirrorOverlayRef, setMirrorOverlay);
threeRef.current.needsRender = true;
@@ -1229,7 +1280,15 @@ export function WorkplaneViewport({
selectedIdsRef.current = selectedIds;
rebuildShapes(threeRef.current, shapesRef.current, selectedIds, !transformRef.current && !dragRef.current);
if (threeRef.current) {
syncTransformOverlay(threeRef.current, shapesRef.current, selectedIds, transformOverlayRef, setTransformOverlay, Boolean(transformRef.current || dragRef.current));
syncTransformOverlay(
threeRef.current,
shapesRef.current,
selectedIds,
transformOverlayRef,
setTransformOverlay,
workspaceRef.current.accuracy,
Boolean(transformRef.current || dragRef.current),
);
syncAlignOverlay(threeRef.current, alignReferenceShapesRef.current, selectedIds, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay);
syncMirrorOverlay(threeRef.current, mirrorReferenceShapesRef.current, selectedIds, mirrorModeRef.current, mirrorOverlayRef, setMirrorOverlay);
threeRef.current.needsRender = true;
@@ -1265,7 +1324,7 @@ export function WorkplaneViewport({
useEffect(() => {
rulerModelRef.current = rulerModel;
if (threeRef.current) {
syncRulerOverlay(threeRef.current, rulerModel, rulerOverlayRef, setRulerOverlay);
syncRulerOverlay(threeRef.current, rulerModel, rulerOverlayRef, setRulerOverlay, workspaceRef.current.accuracy);
threeRef.current.needsRender = true;
}
}, [rulerModel]);
@@ -1282,6 +1341,16 @@ export function WorkplaneViewport({
workspaceRef.current = workspace;
rebuildWorkplane(threeRef.current, workspace);
if (threeRef.current) {
syncTransformOverlay(
threeRef.current,
shapesRef.current,
selectedIdsRef.current,
transformOverlayRef,
setTransformOverlay,
workspace.accuracy,
Boolean(transformRef.current || dragRef.current),
);
syncRulerOverlay(threeRef.current, rulerModelRef.current, rulerOverlayRef, setRulerOverlay, workspace.accuracy);
threeRef.current.needsRender = true;
}
}, [workspace]);
@@ -1333,11 +1402,12 @@ export function WorkplaneViewport({
selectedIdsRef.current,
transformOverlayRef,
setTransformOverlay,
workspaceRef.current.accuracy,
Boolean(transformRef.current || dragRef.current),
);
syncAlignOverlay(state, alignReferenceShapesRef.current, selectedIdsRef.current, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay);
syncMirrorOverlay(state, mirrorReferenceShapesRef.current, selectedIdsRef.current, mirrorModeRef.current, mirrorOverlayRef, setMirrorOverlay);
syncRulerOverlay(state, rulerModelRef.current, rulerOverlayRef, setRulerOverlay);
syncRulerOverlay(state, rulerModelRef.current, rulerOverlayRef, setRulerOverlay, workspaceRef.current.accuracy);
state.lastOverlaySync = now;
}
const renderStart = performance.now();
@@ -1732,7 +1802,7 @@ export function WorkplaneViewport({
setRotationReadout({
x: event.clientX - renderRect.left + 22,
y: event.clientY - renderRect.top - 34,
text: formatMeasure(yBounds.min),
text: formatMeasure(yBounds.min, workspaceRef.current.accuracy),
});
} else {
setRotationReadout(null);
@@ -1818,7 +1888,7 @@ export function WorkplaneViewport({
setRotationReadout({
x: readoutPoint.x + 28,
y: readoutPoint.y - 30,
text: formatMeasure(nextBottom),
text: formatMeasure(nextBottom, workspaceRef.current.accuracy),
});
}
return true;
@@ -1964,7 +2034,7 @@ export function WorkplaneViewport({
axis: "elevation",
x: clamp(editX, 44, Math.max(44, (transformOverlayRef.current?.width ?? 900) - 44)),
y: clamp(editY, 34, Math.max(34, (transformOverlayRef.current?.height ?? 600) - 34)),
value: formatMeasure(yBounds.min),
value: formatMeasure(yBounds.min, workspaceRef.current.accuracy),
});
}, []);
@@ -2243,7 +2313,7 @@ export function WorkplaneViewport({
setRotationReadout({
x: event.clientX - rect.left + 22,
y: event.clientY - rect.top - 34,
text: formatMeasure(yBounds.min),
text: formatMeasure(yBounds.min, workspaceRef.current.accuracy),
});
} else {
setRotationReadout(null);
@@ -2425,7 +2495,15 @@ export function WorkplaneViewport({
if (threeRef.current) {
const previewShapes = previewShapesForDrag(shapesRef.current, drag);
updateSelectedGroundFootprintPreviews(threeRef.current, drag);
syncTransformOverlay(threeRef.current, previewShapes, selectedIdsRef.current, transformOverlayRef, setTransformOverlay, true);
syncTransformOverlay(
threeRef.current,
previewShapes,
selectedIdsRef.current,
transformOverlayRef,
setTransformOverlay,
workspaceRef.current.accuracy,
true,
);
threeRef.current.lastOverlaySync = performance.now();
threeRef.current.needsRender = true;
}
@@ -2509,19 +2587,25 @@ export function WorkplaneViewport({
event.currentTarget.releasePointerCapture(drag.pointerId);
}
let movedShape = false;
drag.items.forEach((item) => {
if (item.visual && item.hadPreviewSimplified) {
setComplexEdgeVisibility(item.visual, true);
}
const shape = shapesRef.current.find((entry) => entry.id === item.id);
if (shape && (shape.x !== item.nextX || shape.z !== item.nextZ)) {
movedShape = true;
onUpdateShape(item.id, { x: item.nextX, z: item.nextZ });
}
});
dragRef.current = null;
if (state) {
syncCutPreviewOverlays(state, previewShapesForDrag(shapesRef.current, drag));
// A moved shape triggers the shapes effect, which rebuilds this preview.
// Running it here as well makes cylinder/hole CSG execute twice on release.
if (!movedShape) {
syncCutPreviewOverlays(state, shapesRef.current);
}
state.controls.enabled = true;
state.needsRender = true;
}
@@ -2750,6 +2834,7 @@ export function WorkplaneViewport({
shape={selectedShape}
snap={snap}
snapOpen={snapOpen}
accuracy={workspace.accuracy}
onUpdate={(patch, options) => onUpdateShape(selectedShape.id, patchWithResizeAnchor(selectedShape, patch, options?.resizeAxis, lastResizeAnchorRef.current))}
onClose={() => onSelectShape(null)}
onSnapChange={setSnap}
@@ -2769,6 +2854,7 @@ export function WorkplaneViewport({
snap={snap}
onWorkspaceChange={setWorkspace}
onSnapChange={setSnap}
onMakeDefault={makeWorkspaceDefault}
onClose={() => setSettingsOpen(false)}
/>
) : null}
@@ -3135,6 +3221,19 @@ function cutPreviewActualIntersectionGeometry(state: ThreeState, solid: Workplan
return null;
}
// Equal-height cylinders have coplanar caps. Feeding those surfaces directly
// to three-bvh-csg can turn a few hundred input triangles into hundreds of
// thousands of preview triangles. A tiny local expansion preserves the
// visible cut while keeping the preview topology bounded.
const holeScale = new THREE.Matrix4().makeScale(
(shapeWidth(hole) + CUT_PREVIEW_PADDING * 2) / Math.max(MIN_SHAPE_SIZE, shapeWidth(hole)),
(hole.height + CUT_PREVIEW_PADDING * 2) / Math.max(MIN_SHAPE_SIZE, hole.height),
(shapeDepth(hole) + CUT_PREVIEW_PADDING * 2) / Math.max(MIN_SHAPE_SIZE, shapeDepth(hole)),
);
const paddedHoleMatrix = holeBrush.matrix.clone().multiply(holeScale);
holeBrush.matrix.copy(paddedHoleMatrix);
holeBrush.matrixWorld.copy(paddedHoleMatrix);
try {
const result = cutPreviewEvaluator.evaluate(solidBrush, holeBrush, HOLLOW_INTERSECTION);
const position = result.geometry.getAttribute("position");
@@ -3267,8 +3366,9 @@ function setSelectionHelpersVisible(state: ThreeState | null, visible: boolean)
state.needsRender = true;
}
function formatMeasure(value: number) {
return cleanNearZero(value).toFixed(2);
function formatMeasure(value: number, accuracy: MeasurementAccuracy = DEFAULT_WORKSPACE.accuracy) {
const zeroThreshold = 0.5 * 10 ** -accuracy;
return cleanNearZero(value, zeroThreshold).toFixed(accuracy);
}
function makeDimensionMark(
@@ -3340,6 +3440,7 @@ function syncTransformOverlay(
selectedIds: string[],
overlayRef: MutableRefObject<TransformOverlayState | null>,
setOverlay: Dispatch<SetStateAction<TransformOverlayState | null>>,
accuracy: MeasurementAccuracy,
keepVisibleDuringInteraction = false,
) {
if (selectedIds.length < 1) {
@@ -3455,9 +3556,9 @@ function syncTransformOverlay(
{ x1: bottom.farRight.x, y1: bottom.farRight.y, x2: bottom.farLeft.x, y2: bottom.farLeft.y },
{ x1: bottom.farLeft.x, y1: bottom.farLeft.y, x2: bottom.nearLeft.x, y2: bottom.nearLeft.y },
];
const widthLabel = formatMeasure(frame.width);
const depthLabel = formatMeasure(frame.depth);
const heightLabel = formatMeasure(frame.height);
const widthLabel = formatMeasure(frame.width, accuracy);
const depthLabel = formatMeasure(frame.depth, accuracy);
const heightLabel = formatMeasure(frame.height, accuracy);
const nearOut = zFootAxis;
const farOut = zFootAxis.clone().multiplyScalar(-1);
const rightOut = xFootAxis;
@@ -3465,7 +3566,7 @@ function syncTransformOverlay(
const heightHandleKey = showLowerHandles ? "bottom-height" : "top-height";
const liftHandleKey = showLowerHandles ? "lower-shape" : "lift-shape";
const workplaneAnchor = new THREE.Vector3(worldCenterX, 0, worldCenterZ);
const liftLabel = formatMeasure(worldMinY);
const liftLabel = formatMeasure(worldMinY, accuracy);
const makeFootprintDimensionMark = (handleKey: string, axis: "width" | "depth") => {
if (axis === "width") {
const useFarSide = handleKey.includes("far") || handleKey.includes("left");
@@ -1,10 +1,10 @@
"use client";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen } from "lucide-react";
import { useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { useEffect, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { ToolbarHideSelectedIcon } from "@/components/icons";
import { fallbackSolidColor, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { GridSize, WorkplaneShape } from "@/types/sketchforge";
import type { GridSize, MeasurementAccuracy, WorkplaneShape } 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,8 +73,9 @@ function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function formatPanelNumber(value: number) {
return (Math.abs(value) < 0.005 ? 0 : value).toFixed(2);
function formatPanelNumber(value: number, accuracy: MeasurementAccuracy) {
const zeroThreshold = 0.5 * 10 ** -accuracy;
return (Math.abs(value) < zeroThreshold ? 0 : value).toFixed(accuracy);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
@@ -196,6 +197,7 @@ export function ShapeInspector({
shape,
snap,
snapOpen,
accuracy,
onUpdate,
onClose,
onSnapChange,
@@ -204,6 +206,7 @@ export function ShapeInspector({
shape: WorkplaneShape;
snap: GridSize;
snapOpen: boolean;
accuracy: MeasurementAccuracy;
onUpdate: ShapeInspectorUpdate;
onClose: () => void;
onSnapChange: Dispatch<SetStateAction<GridSize>>;
@@ -319,7 +322,7 @@ export function ShapeInspector({
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={locked} />;
}
return <RangeProperty key={property.label} {...property} disabled={locked} />;
return <RangeProperty key={property.label} {...property} accuracy={accuracy} disabled={locked} />;
})}
</div>
) : null}
@@ -369,14 +372,31 @@ export function SnapGridControl({
);
}
function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange }: RangePropertyConfig & { disabled?: boolean }) {
const safeValue = clamp(value, min, max);
const position = ((safeValue - min) / Math.max(1, max - min)) * 100;
function RangeProperty({
label,
value,
min,
max,
step = 0.01,
accuracy,
disabled,
onChange,
}: RangePropertyConfig & { accuracy: MeasurementAccuracy; disabled?: boolean }) {
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height";
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 [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatPanelNumber(safeValue));
const [draft, setDraft] = useState(formatPanelNumber(actualValue, accuracy));
useEffect(() => {
if (!editing) {
setDraft(formatPanelNumber(actualValue, accuracy));
}
}, [accuracy, actualValue, editing]);
const commitDraft = () => {
const next = Number(draft);
onChange(clamp(Number.isFinite(next) ? next : safeValue, min, max));
const finiteNext = Number.isFinite(next) ? next : actualValue;
onChange(allowsAboveSliderMax ? Math.max(min, finiteNext) : clamp(finiteNext, min, max));
setEditing(false);
};
return (
@@ -388,7 +408,7 @@ function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange
className="range-value-input"
type="number"
min={min}
max={max}
max={allowsAboveSliderMax ? undefined : max}
step={step}
value={draft}
autoFocus
@@ -398,7 +418,7 @@ function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange
if (event.key === "Enter") {
event.currentTarget.blur();
} else if (event.key === "Escape") {
setDraft(formatPanelNumber(safeValue));
setDraft(formatPanelNumber(actualValue, accuracy));
setEditing(false);
}
}}
@@ -410,11 +430,11 @@ function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange
return;
}
event.preventDefault();
setDraft(formatPanelNumber(safeValue));
setDraft(formatPanelNumber(actualValue, accuracy));
setEditing(true);
}}
>
{formatPanelNumber(safeValue)}
{formatPanelNumber(actualValue, accuracy)}
</output>
)}
<input
@@ -422,7 +442,7 @@ function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange
min={min}
max={max}
step={step}
value={safeValue}
value={sliderValue}
disabled={disabled}
onChange={(event) => {
const next = Number(event.currentTarget.value);
@@ -1,7 +1,7 @@
"use client";
import { X } from "lucide-react";
import type { CSSProperties } from "react";
import { useState, type CSSProperties } from "react";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -38,15 +38,21 @@ export function WorkspaceSettingsModal({
snap,
onWorkspaceChange,
onSnapChange,
onMakeDefault,
onClose,
}: {
workspace: WorkspaceSettings;
snap: GridSize;
onWorkspaceChange: (next: WorkspaceSettings) => void;
onSnapChange: (next: GridSize) => void;
onMakeDefault: () => void;
onClose: () => void;
}) {
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => onWorkspaceChange({ ...workspace, ...patch });
const [defaultSaved, setDefaultSaved] = useState(false);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false);
onWorkspaceChange({ ...workspace, ...patch });
};
const setDimension = (key: "width" | "depth", value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
@@ -122,7 +128,21 @@ export function WorkspaceSettingsModal({
options={["1:1 (millimeters)", "1:10 (centimeters)", "1:100 (meters)", "1:1000 (meters)"]}
onChange={(scale) => patchWorkspace({ scale })}
/>
<WorkspaceSelect label="Snap Grid" value={snap} options={GRID_SIZES} onChange={(next) => onSnapChange(next as GridSize)} />
<WorkspaceSelect
label="Accuracy"
value={`0.${"0".repeat(workspace.accuracy)}`}
options={["0.0", "0.00", "0.000"]}
onChange={(accuracy) => patchWorkspace({ accuracy: accuracy.slice(2).length as WorkspaceSettings["accuracy"] })}
/>
<WorkspaceSelect
label="Snap Grid"
value={snap}
options={GRID_SIZES}
onChange={(next) => {
setDefaultSaved(false);
onSnapChange(next as GridSize);
}}
/>
<WorkspaceSelect
label="Workplane size"
value={workspace.sizePreset}
@@ -135,7 +155,7 @@ export function WorkspaceSettingsModal({
<span>Width</span>
<input
type="number"
value={workspace.width.toFixed(2)}
value={workspace.width.toFixed(workspace.accuracy)}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
@@ -146,7 +166,7 @@ export function WorkspaceSettingsModal({
<span>Length</span>
<input
type="number"
value={workspace.depth.toFixed(2)}
value={workspace.depth.toFixed(workspace.accuracy)}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
@@ -161,7 +181,7 @@ export function WorkspaceSettingsModal({
<span>Block size</span>
<input
type="number"
value={workspace.gridBlockSize.toFixed(2)}
value={workspace.gridBlockSize.toFixed(workspace.accuracy)}
min={MIN_GRID_BLOCK_SIZE}
max={MAX_GRID_BLOCK_SIZE}
step={0.5}
@@ -171,8 +191,14 @@ export function WorkspaceSettingsModal({
</div>
) : null}
<button className="make-default-button" onClick={() => onWorkspaceChange(DEFAULT_WORKPLANE_WORKSPACE)}>
Make default
<button
className="make-default-button"
onClick={() => {
onMakeDefault();
setDefaultSaved(true);
}}
>
{defaultSaved ? "Default saved" : "Make default"}
</button>
</div>
</div>
+7 -1
View File
@@ -1,4 +1,4 @@
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { GridSize, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
@@ -15,6 +15,7 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
zoomSpeed: 5,
units: "Metric (Default)",
scale: "1:1 (millimeters)",
accuracy: 2,
};
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
@@ -31,6 +32,10 @@ function booleanOrDefault(value: unknown, fallback: boolean) {
return typeof value === "boolean" ? value : fallback;
}
function accuracyOrDefault(value: unknown, fallback: MeasurementAccuracy) {
return value === 1 || value === 2 || value === 3 ? value : fallback;
}
export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_SNAP_GRID): GridSize {
return snapGridOptions.includes(value as GridSize) ? (value as GridSize) : fallback;
}
@@ -50,6 +55,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
zoomSpeed: numberOrDefault(candidate.zoomSpeed, fallback.zoomSpeed),
units: stringOrDefault(candidate.units, fallback.units),
scale: stringOrDefault(candidate.scale, fallback.scale),
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
};
}
+2
View File
@@ -28,6 +28,7 @@ export type ShapeAsset = {
};
export type GridSize = "Off" | "0.1 mm" | "0.25 mm" | "0.5 mm" | "1.0 mm" | "2.0 mm" | "5.0 mm" | "Brick";
export type MeasurementAccuracy = 1 | 2 | 3;
export type WorkplaneWorkspaceSettings = {
width: number;
@@ -42,6 +43,7 @@ export type WorkplaneWorkspaceSettings = {
zoomSpeed: number;
units: string;
scale: string;
accuracy: MeasurementAccuracy;
};
export type AlignAxis = "x" | "y" | "z";
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import * as THREE from "three";
import { Brush, Evaluator, HOLLOW_INTERSECTION } from "three-bvh-csg";
describe("cylinder cut preview", () => {
it("keeps a padded overlapping cylinder preview bounded", () => {
const solidGeometry = new THREE.CylinderGeometry(10, 10, 20, 96, 1);
solidGeometry.translate(0, 10, 0);
const holeGeometry = new THREE.CylinderGeometry(10.01, 10.01, 20.02, 96, 1);
holeGeometry.translate(4, 10, 0);
const solid = new Brush(solidGeometry);
const hole = new Brush(holeGeometry);
solid.updateMatrixWorld(true);
hole.updateMatrixWorld(true);
const evaluator = new Evaluator();
evaluator.useGroups = false;
evaluator.attributes = ["position", "normal"];
const result = evaluator.evaluate(solid, hole, HOLLOW_INTERSECTION);
const triangleCount = Math.floor((result.geometry.getAttribute("position")?.count ?? 0) / 3);
expect(triangleCount).toBeGreaterThan(0);
expect(triangleCount).toBeLessThan(1_000);
});
});
+4
View File
@@ -33,6 +33,7 @@ describe("workplane settings helpers", () => {
zoomSpeed: Infinity,
units: "Bricks",
scale: "1:10 (centimeters)",
accuracy: 3,
},
fallback,
),
@@ -47,7 +48,10 @@ describe("workplane settings helpers", () => {
cruiseShapes: false,
units: "Bricks",
scale: "1:10 (centimeters)",
accuracy: 3,
});
expect(normalizeWorkspaceSettings({ accuracy: 9 }, fallback).accuracy).toBe(fallback.accuracy);
});
it("fingerprints workspace and snap settings together", () => {