diff --git a/apps/web/public/assets/sketchforge/toolbar-copy.png b/apps/web/public/assets/sketchforge/toolbar-copy.png new file mode 100644 index 0000000..197c42f Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-copy.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-drop-workplane.png b/apps/web/public/assets/sketchforge/toolbar-drop-workplane.png new file mode 100644 index 0000000..7706988 Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-drop-workplane.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-duplicate.png b/apps/web/public/assets/sketchforge/toolbar-duplicate.png new file mode 100644 index 0000000..de6b190 Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-duplicate.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-group.png b/apps/web/public/assets/sketchforge/toolbar-group.png new file mode 100644 index 0000000..9507584 Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-group.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-snap-grid.png b/apps/web/public/assets/sketchforge/toolbar-snap-grid.png new file mode 100644 index 0000000..227a4a6 Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-snap-grid.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-ungroup.png b/apps/web/public/assets/sketchforge/toolbar-ungroup.png new file mode 100644 index 0000000..f7c6ca7 Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-ungroup.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-workplane.png b/apps/web/public/assets/sketchforge/toolbar-workplane.png new file mode 100644 index 0000000..74bac37 Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-workplane.png differ diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 82a5522..a296195 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -985,11 +985,34 @@ button { .toolbar-icon svg, .toolbar-icon .toolbar-sprite-icon, -.toolbar-icon .vector-toolbar-sprite-icon { +.toolbar-icon .vector-toolbar-sprite-icon, +.toolbar-icon .toolbar-command-icon { width: 32px; height: 32px; } +.toolbar-command-icon { + display: block; + object-fit: contain; + opacity: 0.96; + transition: filter 120ms ease, opacity 120ms ease; +} + +.toolbar-icon.disabled .toolbar-command-icon { + filter: grayscale(1) brightness(1.25); + opacity: 0.22; +} + +.toolbar-icon:not(.disabled):hover .toolbar-command-icon { + filter: contrast(1.08) brightness(0.94) drop-shadow(0 0 4px rgba(0, 156, 222, 0.3)); + opacity: 1; +} + +.toolbar-icon.active .toolbar-command-icon { + filter: contrast(1.12) brightness(0.9) drop-shadow(0 0 5px rgba(0, 156, 222, 0.38)); + opacity: 1; +} + .toolbar-sprite-icon { display: block; background-repeat: no-repeat; @@ -1482,7 +1505,7 @@ button { position: absolute; top: 173px; left: 8px; - z-index: 4; + z-index: 8; display: grid; gap: 4px; } @@ -1505,6 +1528,14 @@ button { border-color: #c4d2dc; } +.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); +} + .workplane-wrap { position: absolute; inset: 0; @@ -1539,6 +1570,11 @@ button { cursor: crosshair; } +.workplane-wrap.ruler-mode .three-workplane-host, +.workplane-wrap.ruler-mode .three-workplane-host:active { + cursor: crosshair; +} + .three-workplane-host canvas { display: block; width: 100%; @@ -1554,6 +1590,78 @@ button { pointer-events: none; } +.ruler-overlay { + position: absolute; + inset: 0; + z-index: 7; + pointer-events: none; +} + +.ruler-guides { + position: absolute; + inset: 0; + overflow: visible; + pointer-events: none; +} + +.ruler-segment { + stroke: #173b5a; + stroke-width: 2; + vector-effect: non-scaling-stroke; + pointer-events: none; +} + +.ruler-segment-hit { + stroke: transparent; + stroke-width: 14; + vector-effect: non-scaling-stroke; + pointer-events: stroke; + cursor: pointer; +} + +.ruler-point, +.ruler-hover-point { + fill: #ffffff; + stroke: #008fbe; + stroke-width: 2.4; + vector-effect: non-scaling-stroke; +} + +.ruler-point { + pointer-events: all; + cursor: pointer; +} + +.ruler-point.pending { + fill: #00a7d8; + stroke: #ffffff; + filter: drop-shadow(0 0 3px rgba(0, 126, 174, 0.72)); +} + +.ruler-hover-point { + fill: rgba(0, 167, 216, 0.28); + stroke-dasharray: 3 2; + pointer-events: none; +} + +.ruler-label { + position: absolute; + z-index: 2; + min-width: 46px; + padding: 5px 9px; + color: #16283a; + background: rgba(255, 255, 255, 0.96); + border: 1px solid rgba(190, 211, 224, 0.96); + border-radius: 999px; + box-shadow: 0 1px 4px rgba(20, 42, 58, 0.12); + font-size: 13px; + font-weight: 600; + line-height: 1; + text-align: center; + pointer-events: none; + transform: translate(-50%, -50%); +} + .transform-overlay { position: absolute; inset: 0; @@ -2732,9 +2840,11 @@ button { cursor: pointer; } -.sidebar-tool svg { +.sidebar-tool svg, +.sidebar-tool .toolbar-command-icon { width: 58px; height: 58px; + object-fit: contain; } .sidebar-tool:hover { diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index ffd5f08..958728f 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -4,6 +4,7 @@ import { Clock3, FileUp, Grid3X3, HomeIcon, List, Plus, Search, Settings, Slider import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl } 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 type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; @@ -512,8 +513,7 @@ export default function Home() { const importStlFileFromDashboard = useCallback( async (file: File) => { - const extension = file.name.split(".").pop()?.toLowerCase(); - if (extension !== "stl") { + if (!importExtensionSupported(file.name)) { setDashboardNotice("Unsupported file type. Use STL."); return; } diff --git a/apps/web/src/components/ShapesSidebar.tsx b/apps/web/src/components/ShapesSidebar.tsx index ba0b44a..92f60e7 100644 --- a/apps/web/src/components/ShapesSidebar.tsx +++ b/apps/web/src/components/ShapesSidebar.tsx @@ -2,7 +2,7 @@ import { ChevronDown, Search } from "lucide-react"; import { useState } from "react"; -import { NotesToolIcon, RulerToolIcon, WorkplaneToolIcon } from "./icons"; +import { NotesToolIcon, WorkplaneToolIcon } from "./icons"; import type { ShapeAsset } from "@/types/sketchforge"; const categories = [ @@ -55,9 +55,6 @@ export function ShapesSidebar({ onAddShape }: ShapesSidebarProps) { - diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index df8548f..1d7cf2c 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -23,22 +23,22 @@ import { ToolbarCaretDownIcon, ToolbarCopyIcon, ToolbarDuplicateIcon, + ToolbarDropToWorkplaneIcon, ToolbarExportIcon, ToolbarGroupIcon, ToolbarHideSelectedIcon, ToolbarImportIcon, - ToolbarMagnetIcon, ToolbarMirrorIcon, ToolbarPasteIcon, ToolbarRedoIcon, - ToolbarBringForwardIcon, - ToolbarSendBackwardIcon, + ToolbarSnapGridIcon, ToolbarSettingsIcon, ToolbarShapeAddIcon, ToolbarTrashIcon, ToolbarUngroupIcon, ToolbarUndoIcon, ToolbarVectorExportIcon, + ToolbarWorkplaneIcon, } from "./icons"; import { WorkplaneViewport } from "./WorkplaneViewport"; import { @@ -56,7 +56,7 @@ import { } from "@/lib/workplaneShapes"; import { createLocalId } from "@/lib/localIds"; import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog"; -import { importedShapeFromStl } from "@/lib/stlImport"; +import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"; import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; export { importedShapeFromStl }; @@ -4833,8 +4833,7 @@ export function SketchForgeEditor({ }, [commitShapes, shapes]); const selectFile = useCallback(async (file: File) => { - const extension = file.name.split(".").pop()?.toLowerCase(); - if (extension !== "stl") { + if (!importExtensionSupported(file.name)) { setNotice("Unsupported file type. Use STL."); return; } @@ -5311,9 +5310,9 @@ function SecondaryToolbar({ { label: "Ungroup", icon: ToolbarUngroupIcon, action: onUngroup, enabled: canUngroup }, { label: "Align", icon: ToolbarAlignIcon, action: onAlign, enabled: canAlign, active: alignMode }, { label: "Mirror", icon: ToolbarMirrorIcon, action: onMirror, enabled: hasSelection, active: mirrorMode }, - { label: "Snap to grid", icon: ToolbarMagnetIcon, action: onSnap, enabled: hasSelection }, - { label: "Workplane", icon: ToolbarSendBackwardIcon, action: onWorkplaneTool, enabled: true, active: workplaneMode }, - { label: "Drop to workplane", icon: ToolbarBringForwardIcon, action: onDropToWorkplane, enabled: hasSelection }, + { label: "Snap to grid", icon: ToolbarSnapGridIcon, action: onSnap, enabled: hasSelection }, + { label: "Workplane", icon: ToolbarWorkplaneIcon, action: onWorkplaneTool, enabled: true, active: workplaneMode }, + { label: "Drop to workplane", icon: ToolbarDropToWorkplaneIcon, action: onDropToWorkplane, enabled: hasSelection }, ]; const renderToolButton = (tool: (typeof leftTools)[number] | (typeof rightTools)[number]) => { const { icon: Icon, action, enabled, label } = tool; diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 943edbf..baf8b48 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -1,8 +1,9 @@ "use client"; -import { Box, Check, Expand, Home, Minus, Plus } from "lucide-react"; +import { Home, Minus, Plus } 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"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js"; import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js"; @@ -208,6 +209,49 @@ type MarqueeState = { hasMoved: boolean; }; +type RulerPoint = { + id: string; + x: number; + z: number; +}; + +type RulerSegment = { + id: string; + startId: string; + endId: string; +}; + +type RulerModel = { + points: RulerPoint[]; + segments: RulerSegment[]; + startPointId: string | null; + hover: { x: number; z: number } | null; +}; + +type RulerOverlayState = { + points: Array; + segments: Array; + hover: { screenX: number; screenY: number } | null; +}; + +type RulerCandidate = { + x: number; + z: number; + pointId?: string; +}; + +function RulerGlyph() { + return ( + + ); +} + type RotationHandleSide = "near" | "right" | "far" | "left"; type RotationHandleSides = Record; type ShapeUpdatePatch = Partial & { bakeTransform?: boolean }; @@ -445,6 +489,117 @@ function projectToScreen(point: THREE.Vector3, state: ThreeState) { }; } +function syncRulerOverlay( + state: ThreeState, + model: RulerModel, + overlayRef: MutableRefObject, + setOverlay: Dispatch>, +) { + const projectedPoints = new Map(); + const points = model.points.map((point) => { + const screen = projectToScreen(new THREE.Vector3(point.x, 0.12, point.z), state); + const projected = { screenX: screen.x, screenY: screen.y }; + projectedPoints.set(point.id, projected); + return { ...point, ...projected }; + }); + const segments = model.segments.flatMap((segment) => { + const start = model.points.find((point) => point.id === segment.startId); + const end = model.points.find((point) => point.id === segment.endId); + const startScreen = projectedPoints.get(segment.startId); + const endScreen = projectedPoints.get(segment.endId); + if (!start || !end || !startScreen || !endScreen) { + return []; + } + return [ + { + ...segment, + x1: startScreen.screenX, + y1: startScreen.screenY, + x2: endScreen.screenX, + 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)), + }, + ]; + }); + const hoverScreen = model.hover ? projectToScreen(new THREE.Vector3(model.hover.x, 0.14, model.hover.z), state) : null; + const next: RulerOverlayState = { + points, + segments, + hover: hoverScreen ? { screenX: hoverScreen.x, screenY: hoverScreen.y } : null, + }; + const previous = overlayRef.current; + const unchanged = + previous && + previous.points.length === next.points.length && + previous.segments.length === next.segments.length && + previous.points.every((point, index) => { + const candidate = next.points[index]; + return point.id === candidate.id && Math.abs(point.screenX - candidate.screenX) < 0.2 && Math.abs(point.screenY - candidate.screenY) < 0.2; + }) && + previous.segments.every((segment, index) => { + const candidate = next.segments[index]; + return segment.id === candidate.id && Math.abs(segment.labelX - candidate.labelX) < 0.2 && Math.abs(segment.labelY - candidate.labelY) < 0.2; + }) && + ((!previous.hover && !next.hover) || + (previous.hover && next.hover && Math.abs(previous.hover.screenX - next.hover.screenX) < 0.2 && Math.abs(previous.hover.screenY - next.hover.screenY) < 0.2)); + if (!unchanged) { + overlayRef.current = next; + setOverlay(next); + } +} + +function RulerOverlay({ + overlay, + startPointId, + active, + onPointPointerDown, + onSegmentPointerDown, +}: { + overlay: RulerOverlayState; + startPointId: string | null; + active: boolean; + onPointPointerDown: (event: ReactPointerEvent, pointId: string) => void; + onSegmentPointerDown: (event: ReactPointerEvent, segmentId: string) => void; +}) { + return ( +
+ + {overlay.segments.map((segment) => ( + + {segment.label} + + ))} +
+ ); +} + function shapeCenter(shape: WorkplaneShape) { return new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); } @@ -942,6 +1097,9 @@ export function WorkplaneViewport({ const [pinnedRotationWheelView, setPinnedRotationWheelView] = useState(null); const [editingDimension, setEditingDimension] = useState(null); const [editingRotation, setEditingRotation] = useState(null); + const [rulerMode, setRulerMode] = useState(false); + const [rulerModel, setRulerModel] = useState({ points: [], segments: [], startPointId: null, hover: null }); + const [rulerOverlay, setRulerOverlay] = useState(null); const hostRef = useRef(null); const threeRef = useRef(null); const shapesRef = useRef(shapes); @@ -961,6 +1119,10 @@ export function WorkplaneViewport({ const transformOverlayRef = useRef(null); const alignOverlayRef = useRef(null); const mirrorOverlayRef = useRef(null); + const rulerModeRef = useRef(false); + const rulerModelRef = useRef(rulerModel); + const rulerOverlayRef = useRef(null); + const rulerIdRef = useRef(0); const alignModeRef = useRef(alignMode); const alignAnchorIdRef = useRef(alignAnchorId); const alignHandlesRef = useRef(alignHandles); @@ -1026,7 +1188,7 @@ export function WorkplaneViewport({ useEffect(() => { shapesRef.current = shapes; - rebuildShapes(threeRef.current, shapes, selectedIdsRef.current); + 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)); syncAlignOverlay(threeRef.current, alignReferenceShapesRef.current, selectedIdsRef.current, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay); @@ -1065,7 +1227,7 @@ export function WorkplaneViewport({ setActiveTransformKind(null); } selectedIdsRef.current = selectedIds; - rebuildShapes(threeRef.current, shapesRef.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)); syncAlignOverlay(threeRef.current, alignReferenceShapesRef.current, selectedIds, alignModeRef.current, alignAnchorIdRef.current, alignHandlesRef.current, alignOverlayRef, setAlignOverlay); @@ -1096,6 +1258,18 @@ export function WorkplaneViewport({ snapRef.current = snap; }, [snap]); + useEffect(() => { + rulerModeRef.current = rulerMode; + }, [rulerMode]); + + useEffect(() => { + rulerModelRef.current = rulerModel; + if (threeRef.current) { + syncRulerOverlay(threeRef.current, rulerModel, rulerOverlayRef, setRulerOverlay); + threeRef.current.needsRender = true; + } + }, [rulerModel]); + useEffect(() => { placementElevationRef.current = placementElevation; }, [placementElevation]); @@ -1163,6 +1337,7 @@ export function WorkplaneViewport({ ); 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); state.lastOverlaySync = now; } const renderStart = performance.now(); @@ -1259,6 +1434,166 @@ export function WorkplaneViewport({ }, [toRawPlanePoint]); const toPlanePoint = useCallback((clientX: number, clientY: number) => toPlanePointAtY(clientX, clientY, 0), [toPlanePointAtY]); + const storeRulerModel = useCallback((next: RulerModel) => { + rulerModelRef.current = next; + setRulerModel(next); + }, []); + + const setRulerActive = useCallback((active: boolean) => { + rulerModeRef.current = active; + setRulerMode(active); + if (!active) { + const current = rulerModelRef.current; + storeRulerModel({ ...current, startPointId: null, hover: null }); + } + }, [storeRulerModel]); + + const resolveRulerCandidate = useCallback( + (clientX: number, clientY: number): RulerCandidate | null => { + const state = threeRef.current; + if (!state) { + return null; + } + const raw = toRawPlanePoint(clientX, clientY, state.dragPlane); + if (!raw) { + return null; + } + const step = snapStep(snapRef.current); + const bounds = workspaceRef.current; + const snapped = { + x: clamp(snapValue(raw.x, step), -bounds.width / 2, bounds.width / 2), + z: clamp(snapValue(raw.z, step), -bounds.depth / 2, bounds.depth / 2), + }; + + const model = rulerModelRef.current; + const rect = state.renderer.domElement.getBoundingClientRect(); + const localX = clientX - rect.left; + const localY = clientY - rect.top; + const closestPoint = model.points.reduce<{ point: RulerPoint; distance: number } | null>((closest, point) => { + const screen = projectToScreen(new THREE.Vector3(point.x, 0.12, point.z), state); + const distance = Math.hypot(screen.x - localX, screen.y - localY); + if (distance <= 12 && (!closest || distance < closest.distance)) { + return { point, distance }; + } + return closest; + }, null); + if (closestPoint) { + return { x: closestPoint.point.x, z: closestPoint.point.z, pointId: closestPoint.point.id }; + } + + const closestSegment = model.segments.reduce<{ segment: RulerSegment; distance: number } | null>((closest, segment) => { + const start = model.points.find((point) => point.id === segment.startId); + const end = model.points.find((point) => point.id === segment.endId); + if (!start || !end) { + return closest; + } + const a = projectToScreen(new THREE.Vector3(start.x, 0.12, start.z), state); + const b = projectToScreen(new THREE.Vector3(end.x, 0.12, end.z), state); + const dx = b.x - a.x; + const dy = b.y - a.y; + const amount = dx * dx + dy * dy > 0.001 ? clamp(((localX - a.x) * dx + (localY - a.y) * dy) / (dx * dx + dy * dy), 0, 1) : 0; + const distance = Math.hypot(localX - (a.x + dx * amount), localY - (a.y + dy * amount)); + if (distance <= 10 && (!closest || distance < closest.distance)) { + return { segment, distance }; + } + return closest; + }, null); + + if (closestSegment) { + const start = model.points.find((point) => point.id === closestSegment.segment.startId); + const end = model.points.find((point) => point.id === closestSegment.segment.endId); + if (start && end) { + const dx = end.x - start.x; + const dz = end.z - start.z; + const length = Math.hypot(dx, dz); + if (length > 0.001) { + const directionX = dx / length; + const directionZ = dz / length; + const rawAlong = clamp((raw.x - start.x) * directionX + (raw.z - start.z) * directionZ, 0, length); + const along = clamp(step > 0 ? snapValue(rawAlong, step) : rawAlong, 0, length); + const x = start.x + directionX * along; + const z = start.z + directionZ * along; + const existing = model.points.find((point) => Math.hypot(point.x - x, point.z - z) < 0.001); + return { x, z, pointId: existing?.id }; + } + } + } + + const existing = model.points.find((point) => Math.hypot(point.x - snapped.x, point.z - snapped.z) < 0.001); + return { ...snapped, pointId: existing?.id }; + }, + [toRawPlanePoint], + ); + + const selectRulerCandidate = useCallback( + (candidate: RulerCandidate) => { + const current = rulerModelRef.current; + const existing = candidate.pointId ? current.points.find((point) => point.id === candidate.pointId) : current.points.find((point) => Math.hypot(point.x - candidate.x, point.z - candidate.z) < 0.001); + const point = existing ?? { id: `ruler-point-${++rulerIdRef.current}`, x: candidate.x, z: candidate.z }; + const points = existing ? current.points : [...current.points, point]; + if (!current.startPointId) { + storeRulerModel({ ...current, points, startPointId: point.id, hover: { x: point.x, z: point.z } }); + return; + } + if (current.startPointId === point.id) { + return; + } + + const duplicate = current.segments.some( + (segment) => + (segment.startId === current.startPointId && segment.endId === point.id) || + (segment.startId === point.id && segment.endId === current.startPointId), + ); + const segments = duplicate + ? 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], + ); + + const updateRulerHover = useCallback( + (clientX: number, clientY: number) => { + if (!rulerModeRef.current) { + return; + } + const candidate = resolveRulerCandidate(clientX, clientY); + const current = rulerModelRef.current; + const hover = candidate ? { x: candidate.x, z: candidate.z } : null; + if ((!current.hover && !hover) || (current.hover && hover && Math.hypot(current.hover.x - hover.x, current.hover.z - hover.z) < 0.0001)) { + return; + } + storeRulerModel({ ...current, hover }); + }, + [resolveRulerCandidate, storeRulerModel], + ); + + const removeRulerSegment = useCallback( + (segmentId: string) => { + const current = rulerModelRef.current; + const segments = current.segments.filter((segment) => segment.id !== segmentId); + const usedPointIds = new Set(segments.flatMap((segment) => [segment.startId, segment.endId])); + const points = current.points.filter((point) => usedPointIds.has(point.id) || point.id === current.startPointId); + storeRulerModel({ ...current, points, segments }); + }, + [storeRulerModel], + ); + + 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 }); + }, + [removeRulerSegment, storeRulerModel], + ); + const setMarqueeFromState = useCallback((marquee: MarqueeState | null) => { if (!marquee) { setMarqueeRect(null); @@ -1403,6 +1738,8 @@ export function WorkplaneViewport({ setRotationReadout(null); } if (state) { + clearCutPreviewOverlays(state); + state.needsRender = true; state.controls.enabled = false; } onInteractionActiveChange?.(true); @@ -1586,8 +1923,10 @@ export function WorkplaneViewport({ setPinnedRotationWheelView(null); setRotationReadout(null); if (threeRef.current) { + syncCutPreviewOverlays(threeRef.current, shapesRef.current); setSelectionHelpersVisible(threeRef.current, true); threeRef.current.controls.enabled = true; + threeRef.current.needsRender = true; } onInteractionActiveChange?.(false); bakeRotatedShapes.forEach((id) => onUpdateShape(id, { bakeTransform: true })); @@ -1780,6 +2119,15 @@ export function WorkplaneViewport({ } const rect = state.renderer.domElement.getBoundingClientRect(); + if (rulerModeRef.current) { + event.preventDefault(); + const candidate = resolveRulerCandidate(event.clientX, event.clientY); + if (candidate) { + selectRulerCandidate(candidate); + } + return; + } + if (workplaneModeRef.current) { event.preventDefault(); const id = pickShape(event.clientX, event.clientY); @@ -1900,6 +2248,8 @@ export function WorkplaneViewport({ } else { setRotationReadout(null); } + clearCutPreviewOverlays(state); + state.needsRender = true; state.controls.enabled = false; onInteractionActiveChange?.(true); return; @@ -1987,6 +2337,8 @@ export function WorkplaneViewport({ primaryStartZ: shape.z, items, }; + clearCutPreviewOverlays(state); + state.needsRender = true; state.controls.enabled = false; onInteractionActiveChange?.(true); }, @@ -1998,6 +2350,8 @@ export function WorkplaneViewport({ onWorkplaneModeChange, pickShape, pickTransformHandle, + resolveRulerCandidate, + selectRulerCandidate, setMarqueeFromState, toPlanePoint, toPlanePointAtY, @@ -2007,6 +2361,10 @@ export function WorkplaneViewport({ const handlePointerMove = useCallback( (event: ReactPointerEvent) => { + if (rulerModeRef.current) { + updateRulerHover(event.clientX, event.clientY); + return; + } const transform = transformRef.current; if (transform) { updateTransform(event.clientX, event.clientY, event.shiftKey, event.altKey); @@ -2072,7 +2430,7 @@ export function WorkplaneViewport({ threeRef.current.needsRender = true; } }, - [setMarqueeFromState, toPlanePoint, updateTransform], + [setMarqueeFromState, toPlanePoint, updateRulerHover, updateTransform], ); const finishDrag = useCallback( @@ -2097,8 +2455,10 @@ export function WorkplaneViewport({ setActiveTransformKind(null); setRotationReadout(null); if (state) { + syncCutPreviewOverlays(state, shapesRef.current); setSelectionHelpersVisible(state, true); state.controls.enabled = true; + state.needsRender = true; } onInteractionActiveChange?.(false); return; @@ -2161,7 +2521,9 @@ export function WorkplaneViewport({ dragRef.current = null; if (state) { + syncCutPreviewOverlays(state, previewShapesForDrag(shapesRef.current, drag)); state.controls.enabled = true; + state.needsRender = true; } onInteractionActiveChange?.(false); }, @@ -2209,6 +2571,61 @@ 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 }); + if (next) { + onWorkplaneModeChange(false); + onSelectShape(null); + } + }, [onSelectShape, onWorkplaneModeChange, storeRulerModel]); + + const handleRulerPointPointerDown = useCallback( + (event: ReactPointerEvent, pointId: string) => { + if (event.button === 1) { + event.preventDefault(); + event.stopPropagation(); + removeRulerPoint(pointId); + return; + } + if (event.button !== 0 || !rulerModeRef.current) { + return; + } + const point = rulerModelRef.current.points.find((candidate) => candidate.id === pointId); + if (!point) { + return; + } + event.preventDefault(); + event.stopPropagation(); + selectRulerCandidate({ x: point.x, z: point.z, pointId }); + }, + [removeRulerPoint, selectRulerCandidate], + ); + + const handleRulerSegmentPointerDown = useCallback( + (event: ReactPointerEvent, segmentId: string) => { + if (event.button === 1) { + event.preventDefault(); + event.stopPropagation(); + removeRulerSegment(segmentId); + return; + } + if (event.button !== 0 || !rulerModeRef.current) { + return; + } + event.preventDefault(); + event.stopPropagation(); + const candidate = resolveRulerCandidate(event.clientX, event.clientY); + if (candidate) { + selectRulerCandidate(candidate); + } + }, + [removeRulerSegment, resolveRulerCandidate, selectRulerCandidate], + ); + useEffect(() => { const isTypingTarget = (target: EventTarget | null) => { if (!(target instanceof HTMLElement)) { @@ -2223,7 +2640,10 @@ export function WorkplaneViewport({ } const key = event.key.toLowerCase(); - if (key === "f" || event.key === "Home") { + if (event.key === "Escape" && rulerModeRef.current) { + event.preventDefault(); + setRulerActive(false); + } else if (key === "f" || event.key === "Home") { event.preventDefault(); resetView(); } else if (event.key === "+" || event.key === "=") { @@ -2237,7 +2657,7 @@ export function WorkplaneViewport({ window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); - }, [resetView, zoomCamera]); + }, [resetView, setRulerActive, zoomCamera]); return (
@@ -2256,21 +2676,18 @@ export function WorkplaneViewport({ - - -
+
{marqueeRect ?
: null} - {transformOverlay && !alignMode && !mirrorMode ? ( + {transformOverlay && !alignMode && !mirrorMode && !rulerMode ? ( : null} {mirrorOverlay ? : null} + {rulerOverlay && (rulerOverlay.points.length > 0 || rulerOverlay.hover) ? ( + + ) : null}
@@ -2593,7 +3019,206 @@ function linesFromPoints(points: number[], material: THREE.LineBasicMaterial) { return new THREE.LineSegments(geometry, material); } -function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selectedIds: string[]) { +type CutPreviewShapeFrame = { + shape: WorkplaneShape; + worldBounds: THREE.Box3; +}; + +function shapeCutPreviewFrames(state: ThreeState, shapes: WorkplaneShape[]) { + return shapes.reduce>((frames, shape) => { + const object = findShapeObject(state, shape.id); + if (!object) { + return frames; + } + object.updateMatrixWorld(true); + const worldBounds = new THREE.Box3().setFromObject(object); + if (!worldBounds.isEmpty()) { + frames[shape.id] = { shape, worldBounds }; + } + return frames; + }, {}); +} + +type CutPreviewBrushCacheEntry = { + signature: string; + brush: Brush; +}; + +const cutPreviewBrushCache = new WeakMap(); +const cutPreviewEvaluator = new Evaluator(); +cutPreviewEvaluator.useGroups = false; +cutPreviewEvaluator.attributes = ["position", "normal"]; + +function cutPreviewObjectSignature(root: THREE.Object3D) { + const parts: string[] = []; + root.updateMatrixWorld(true); + const inverseRoot = root.matrixWorld.clone().invert(); + root.traverse((child) => { + if (!(child instanceof THREE.Mesh) || !child.visible || !(child.geometry instanceof THREE.BufferGeometry)) { + return; + } + const relativeMatrix = inverseRoot.clone().multiply(child.matrixWorld); + parts.push(child.geometry.uuid, ...relativeMatrix.elements.map((value) => value.toFixed(5))); + }); + return parts.join(":"); +} + +function cutPreviewBrushFromObject(root: THREE.Object3D) { + const signature = cutPreviewObjectSignature(root); + const cached = cutPreviewBrushCache.get(root); + if (cached?.signature === signature) { + cached.brush.matrixAutoUpdate = false; + cached.brush.matrix.copy(root.matrixWorld); + cached.brush.matrixWorld.copy(root.matrixWorld); + return cached.brush; + } + + const positions: number[] = []; + const point = new THREE.Vector3(); + const inverseRoot = root.matrixWorld.clone().invert(); + root.traverse((child) => { + if (!(child instanceof THREE.Mesh) || !child.visible || !(child.geometry instanceof THREE.BufferGeometry)) { + return; + } + + const position = child.geometry.getAttribute("position"); + if (!position) { + return; + } + const index = child.geometry.getIndex(); + const count = index?.count ?? position.count; + const relativeMatrix = inverseRoot.clone().multiply(child.matrixWorld); + const mirrored = relativeMatrix.determinant() < 0; + for (let offset = 0; offset + 2 < count; offset += 3) { + const triangle = [0, 1, 2].map((corner) => { + const vertexIndex = index ? index.getX(offset + corner) : offset + corner; + return point + .set(position.getX(vertexIndex), position.getY(vertexIndex), position.getZ(vertexIndex)) + .applyMatrix4(relativeMatrix) + .toArray(); + }); + if (mirrored) { + [triangle[1], triangle[2]] = [triangle[2], triangle[1]]; + } + positions.push(...triangle[0], ...triangle[1], ...triangle[2]); + } + }); + + if (positions.length < 9) { + return null; + } + + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); + geometry.computeVertexNormals(); + const brush = new Brush(geometry); + brush.matrixAutoUpdate = false; + brush.matrix.copy(root.matrixWorld); + brush.matrixWorld.copy(root.matrixWorld); + if (cached) { + cached.brush.geometry.dispose(); + } + cutPreviewBrushCache.set(root, { signature, brush }); + return brush; +} + +function cutPreviewActualIntersectionGeometry(state: ThreeState, solid: WorkplaneShape, hole: WorkplaneShape) { + const solidObject = findShapeObject(state, solid.id); + const holeObject = findShapeObject(state, hole.id); + if (!solidObject || !holeObject) { + return null; + } + + const solidBrush = cutPreviewBrushFromObject(solidObject); + const holeBrush = cutPreviewBrushFromObject(holeObject); + if (!solidBrush || !holeBrush) { + return null; + } + + try { + const result = cutPreviewEvaluator.evaluate(solidBrush, holeBrush, HOLLOW_INTERSECTION); + const position = result.geometry.getAttribute("position"); + if (!position || position.count < 3) { + result.geometry.dispose(); + return null; + } + const geometry = result.geometry.clone(); + geometry.applyMatrix4(result.matrixWorld); + result.geometry.dispose(); + geometry.computeVertexNormals(); + return geometry; + } catch { + return null; + } +} + +function addCutPreviewOverlays(state: ThreeState, holeFrame: CutPreviewShapeFrame, solidFrames: CutPreviewShapeFrame[]) { + solidFrames.forEach((solidFrame) => { + if (!holeFrame.worldBounds.intersectsBox(solidFrame.worldBounds)) { + return; + } + + const geometry = cutPreviewActualIntersectionGeometry(state, solidFrame.shape, holeFrame.shape); + if (!geometry) { + return; + } + const preview = new THREE.Mesh( + geometry, + new THREE.MeshBasicMaterial({ + color: "#30363a", + transparent: true, + opacity: 0.34, + depthTest: false, + depthWrite: false, + side: THREE.DoubleSide, + }), + ); + preview.name = "CutPreviewOverlay"; + preview.renderOrder = 18; + preview.userData.cutPreview = true; + preview.raycast = () => undefined; + state.shapeLayer.add(preview); + }); +} + +function clearCutPreviewOverlays(state: ThreeState) { + const overlays: THREE.Object3D[] = []; + state.shapeLayer.traverse((child) => { + if (child.userData.cutPreview) { + overlays.push(child); + } + }); + overlays.forEach((overlay) => { + overlay.parent?.remove(overlay); + disposeObject(overlay); + }); +} + +function syncCutPreviewOverlays(state: ThreeState, shapes: WorkplaneShape[]) { + clearCutPreviewOverlays(state); + const visibleShapes = shapes.filter((shape) => !shape.hidden); + const cutFrames = shapeCutPreviewFrames(state, visibleShapes); + const solidFrames = visibleShapes + .filter((shape) => !shape.hole) + .map((shape) => cutFrames[shape.id]) + .filter((frame): frame is CutPreviewShapeFrame => Boolean(frame)); + + if (solidFrames.length === 0) { + return; + } + + visibleShapes.forEach((shape) => { + if (!shape.hole) { + return; + } + const holeFrame = cutFrames[shape.id]; + if (holeFrame) { + addCutPreviewOverlays(state, holeFrame, solidFrames); + } + }); +} + +function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selectedIds: string[], showCutPreviews = true) { if (!state) { return; } @@ -2601,16 +3226,17 @@ function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selec disposeChildren(state.shapeLayer); const selected = new Set(selectedIds); - shapes.forEach((shape) => { - if (shape.hidden) { - return; - } + const visibleShapes = shapes.filter((shape) => !shape.hidden); + visibleShapes.forEach((shape) => { const object = createShapeObject(shape, selected.has(shape.id), () => { state.needsRender = true; }); state.shapeLayer.add(object); }); + if (showCutPreviews) { + syncCutPreviewOverlays(state, visibleShapes); + } rebuildSelectionHelpers(state, shapes, selectedIds); } diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsx index d0f760c..346adbd 100644 --- a/apps/web/src/components/icons.tsx +++ b/apps/web/src/components/icons.tsx @@ -107,26 +107,14 @@ export function BlocksModeIcon(props: IconProps) { ); } -export function WorkplaneToolIcon(props: IconProps) { - return ( - - ); +type ToolbarCommandImageProps = { file: string; className?: string }; + +function ToolbarCommandImage({ file, className }: ToolbarCommandImageProps) { + return ; } -export function RulerToolIcon(props: IconProps) { - return ( - - ); +export function WorkplaneToolIcon() { + return ; } export function NotesToolIcon(props: IconProps) { @@ -140,16 +128,16 @@ export function NotesToolIcon(props: IconProps) { ); } -export function ToolbarCopyIcon(props: IconProps) { - return ; +export function ToolbarCopyIcon() { + return ; } export function ToolbarPasteIcon(props: IconProps) { return ; } -export function ToolbarDuplicateIcon(props: IconProps) { - return ; +export function ToolbarDuplicateIcon() { + return ; } export function ToolbarTrashIcon(props: IconProps) { @@ -216,12 +204,12 @@ export function ToolbarCaretDownIcon(props: IconProps) { ); } -export function ToolbarGroupIcon(props: IconProps) { - return ; +export function ToolbarGroupIcon() { + return ; } -export function ToolbarUngroupIcon(props: IconProps) { - return ; +export function ToolbarUngroupIcon() { + return ; } export function ToolbarAlignIcon(props: IconProps) { @@ -232,8 +220,8 @@ export function ToolbarMirrorIcon(props: IconProps) { return ; } -export function ToolbarMagnetIcon(props: IconProps) { - return ; +export function ToolbarSnapGridIcon() { + return ; } export function ToolbarPaintIcon(props: IconProps) { @@ -255,10 +243,10 @@ export function ToolbarExportIcon(props: IconProps) { ); } -export function ToolbarSendBackwardIcon(props: IconProps) { - return ; +export function ToolbarWorkplaneIcon() { + return ; } -export function ToolbarBringForwardIcon(props: IconProps) { - return ; +export function ToolbarDropToWorkplaneIcon() { + return ; } diff --git a/apps/web/src/lib/stlImport.ts b/apps/web/src/lib/stlImport.ts index b4e4b6e..0344299 100644 --- a/apps/web/src/lib/stlImport.ts +++ b/apps/web/src/lib/stlImport.ts @@ -4,10 +4,20 @@ import { createLocalId } from "@/lib/localIds"; import type { WorkplaneShape } from "@/types/sketchforge"; const stlLoader = new STLLoader(); +const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl"]); -export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): WorkplaneShape { - const rawGeometry = stlLoader.parse(buffer); - const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry.clone(); +function fileExtension(fileName: string) { + return fileName.split(".").pop()?.toLowerCase() ?? ""; +} + +function importedShapeFromTriangleSoup(fileName: string, rawPositions: number[], rawNormals: number[] | undefined): WorkplaneShape { + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(rawPositions, 3)); + if (rawNormals?.length === rawPositions.length) { + geometry.setAttribute("normal", new THREE.Float32BufferAttribute(rawNormals, 3)); + } else { + geometry.computeVertexNormals(); + } geometry.computeBoundingBox(); const box = geometry.boundingBox; @@ -70,3 +80,25 @@ export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): Wor hidden: false, }; } + +export function importExtensionSupported(fileName: string) { + return SUPPORTED_IMPORT_EXTENSIONS.has(fileExtension(fileName)); +} + +export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): WorkplaneShape { + const rawGeometry = stlLoader.parse(buffer); + const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry.clone(); + const position = geometry.getAttribute("position"); + const normal = geometry.getAttribute("normal"); + const rawPositions: number[] = []; + const rawNormals: number[] = []; + + 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)); + } + } + + return importedShapeFromTriangleSoup(fileName, rawPositions, rawNormals.length ? rawNormals : undefined); +}