diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..101d939 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,18 @@ +.git +.github +.codex +.codex-run +.codex-remote-attachments +node_modules +**/node_modules +.next +**/.next +**/.next-export +apps/web/out +coverage +playwright-report +test-results +tests +docs +*.log +*.tsbuildinfo diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d83c0f8..315c173 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -35,3 +35,7 @@ The app runs at `http://127.0.0.1:3000/` by default. - Keep UI behavior local to the relevant component unless the behavior is shared. - Use TypeScript types instead of loose object shapes where practical. - Keep comments short and useful. + +## Contribution Licensing + +Unless explicitly agreed otherwise in writing, by submitting a contribution you license it under the MIT License. See [LICENSE](../LICENSE). diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 244c124..21f2f15 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -4,10 +4,15 @@ on: push: branches: - main - - '**' + workflow_dispatch: + +concurrency: + group: docker-publish-${{ github.ref }} + cancel-in-progress: true jobs: build: + timeout-minutes: 30 permissions: packages: write contents: read @@ -16,9 +21,6 @@ jobs: - name: Checkout Repository uses: actions/checkout@v4 - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 @@ -40,11 +42,13 @@ jobs: type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} - name: Build and Push Docker Image - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: context: . file: deploy/docker/Dockerfile platforms: linux/amd64,linux/arm64 push: true tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} \ No newline at end of file + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha,scope=sketchforge-docker + cache-to: type=gha,mode=max,scope=sketchforge-docker diff --git a/.gitignore b/.gitignore index c6b403a..1f93e4f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ node_modules/ # Next.js .next/ +.next-export/ out/ build/ dist/ @@ -32,6 +33,7 @@ playwright-report/ # Local workspace state .codex/ +.codex-run/ .codex-remote-attachments/ # OS/editor noise diff --git a/README.md b/README.md index 43c9cda..76022a2 100644 --- a/README.md +++ b/README.md @@ -17,12 +17,13 @@

MIT license GitHub stars + GitHub Sponsors Local first - Version 0.5.0 + Version 0.6.0

-![SketchForge editor showing a selected box on the workplane](docs/media/sketchforge-editor-v0.5.png) +![SketchForge editor showing a selected box on the workplane](docs/media/sketchforge-editor-v0.6.png) ## Why SketchForge @@ -275,40 +276,6 @@ Build a static export: npm run export ``` -## Project Layout - -```text -apps/web/ Next.js app workspace -apps/web/src/app/ App routes, dashboard, API routes, styles -apps/web/src/components/ Editor, viewport, sidebar, icons, controls -apps/web/src/types/ Shared shape and editor types -apps/web/src/generated/ Generated Manifold runtime source -apps/web/src/lib/ Shared utilities -apps/web/public/assets/ Static app images, icons, logos, shape assets -scripts/ Build and local automation helpers -docs/media/ README screenshots and demo videos -docs/mcp/ MCP client configuration examples -docs/skills/ Optional AI-agent skill bundles -deploy/docker/ Docker, Compose, and Nginx deployment files -.github/ Issue templates and community files -``` - -## Current Status - -SketchForge is alpha, but the core editor loop is usable today: - -- create and reopen local projects -- add, move, resize, rotate, mirror, align, duplicate, hide, and delete shapes -- switch shapes between solid and hole modes -- group and ungroup geometry -- apply and remove chamfer/fillet edge treatments -- import STL files -- import and export STEP files -- export STL or OBJ -- generate project thumbnails - -The next big areas are workflow polish, more geometry edge-case testing, stronger automated editor coverage, and better release documentation. - ## Contributing Contributions are welcome. Good places to help: diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index f714ce3..03ded85 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -29,8 +29,8 @@ const nextConfig: NextConfig = { ...(isStaticExport ? { output: "export" as const, + distDir: ".next-export", trailingSlash: true, - assetPrefix: "./", } : {}), }; diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 279ef7c..2766c4e 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -2797,36 +2797,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 { @@ -2870,6 +2945,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; @@ -2909,6 +2989,7 @@ button { stroke-width: 2; vector-effect: non-scaling-stroke; pointer-events: none; + transition: stroke 120ms ease, stroke-width 120ms ease; } .ruler-segment-hit { @@ -2930,6 +3011,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 { @@ -4255,6 +4349,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; diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx index bf5d35e..6328b61 100644 --- a/apps/web/src/app/layout.tsx +++ b/apps/web/src/app/layout.tsx @@ -16,7 +16,7 @@ export default function RootLayout({ children: React.ReactNode; }>) { return ( - + {children} ); diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 574c6aa..76cbb41 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -2,10 +2,10 @@ import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { SketchForgeEditor, importedShapeFromStl } from "@/components/SketchForgeEditor"; +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"; @@ -236,7 +236,7 @@ function newProject(name: string, index: number, shapeCount = 0): DashboardProje } function projectNameFromFileName(fileName: string) { - return fileName.replace(/\.[^.]+$/, "").trim() || "Imported STL design"; + return fileName.replace(/\.[^.]+$/, "").trim() || "Imported design"; } export default function Home() { @@ -255,11 +255,18 @@ export default function Home() { const [dashboardNotice, setDashboardNotice] = useState(""); const [projectShapesById, setProjectShapesById] = useState>({}); const projectsJsonRef = useRef(""); - const dashboardStlInputRef = useRef(null); + const dashboardImportInputRef = useRef(null); const nextProjectRevisionRef = useRef(0); const projectShapeSaveQueuesRef = useRef>>({}); 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) => { @@ -513,15 +528,18 @@ export default function Home() { openEditor(project.id, { allowMissingFromStorage: true }); }; - const importStlFileFromDashboard = useCallback( + const importFileFromDashboard = useCallback( async (file: File) => { - if (!importExtensionSupported(file.name)) { - setDashboardNotice("Unsupported file type. Use STL."); + const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml"; + if (!isSvg && !importExtensionSupported(file.name)) { + setDashboardNotice("Unsupported file type. Use STL or SVG."); return; } try { - const shape = importedShapeFromStl(file.name, await file.arrayBuffer()); + const shape = isSvg + ? importedShapeFromSvg(file.name, await file.text()) + : importedShapeFromStl(file.name, await file.arrayBuffer()); const project = newProject(projectNameFromFileName(file.name), projects.length, 1); const revision = project.revision ?? project.updatedAt; await saveProjectShapes(project.id, [shape], revision); @@ -608,14 +626,14 @@ export default function Home() { {JSON.stringify(projectDebugSummary)} { const file = event.currentTarget.files?.[0]; if (file) { - void importStlFileFromDashboard(file); + void importFileFromDashboard(file); } event.currentTarget.value = ""; }} @@ -637,7 +655,7 @@ export default function Home() { onDeleteProject={deleteProject} onDownloadFolderChange={setDownloadFolder} onDownloadModeChange={setDownloadMode} - onImportStl={() => dashboardStlInputRef.current?.click()} + onImportFile={() => dashboardImportInputRef.current?.click()} onChallenges={() => { setDashboardSection("challenges"); setDashboardNotice(""); @@ -688,7 +706,7 @@ function Dashboard({ onDeleteProject, onDownloadFolderChange, onDownloadModeChange, - onImportStl, + onImportFile, onChallenges, onDashboardHome, onOpenProject, @@ -714,7 +732,7 @@ function Dashboard({ onDeleteProject: (projectId: string) => void; onDownloadFolderChange: (value: string) => void; onDownloadModeChange: (value: DownloadMode) => void; - onImportStl: () => void; + onImportFile: () => void; onChallenges: () => void; onDashboardHome: () => void; onOpenProject: (projectId: string) => void; @@ -810,11 +828,11 @@ function Dashboard({ Create new 3D design - diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 3b8de9e..356577e 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -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"; @@ -19,6 +19,7 @@ import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } fro import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal"; import { createScrewHoleShape, type ScrewHoleConfig } from "@/lib/screwHoles"; 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 { @@ -283,18 +284,6 @@ type RulerCandidate = { pointId?: string; }; -function RulerGlyph() { - return ( - - ); -} - type RotationHandleSide = "near" | "right" | "far" | "left"; type RotationHandleSides = Record; type ShapeUpdatePatch = Partial & { bakeTransform?: boolean }; @@ -643,20 +632,22 @@ function RulerOverlay({ overlay, startPointId, active, + deleteMode, onPointPointerDown, onSegmentPointerDown, }: { overlay: RulerOverlayState; startPointId: string | null; active: boolean; + deleteMode: boolean; onPointPointerDown: (event: ReactPointerEvent, pointId: string) => void; onSegmentPointerDown: (event: ReactPointerEvent, segmentId: string) => void; }) { return ( -
+
-
- - - - +
+ {cameraControlsCollapsed ? ( + + ) : ( + <> + + + + +
+ + {rulerToolsOpen ? ( +
+ + +
+ ) : null} +
+ + )}
-
+
@@ -3256,6 +3334,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"; @@ -3270,9 +3351,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[] = []; @@ -3282,28 +3364,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)); @@ -3316,7 +3391,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 = { diff --git a/apps/web/src/components/workplane/EdgeModifierPanel.tsx b/apps/web/src/components/workplane/EdgeModifierPanel.tsx index eeda9ed..19c924a 100644 --- a/apps/web/src/components/workplane/EdgeModifierPanel.tsx +++ b/apps/web/src/components/workplane/EdgeModifierPanel.tsx @@ -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))} />
@@ -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({
{title} - {selectedCount} of {availableCount} sharp edges selected + {edgeModifierSelectionStatus(prepared, selectedCount, availableCount)}
@@ -205,12 +212,12 @@ export function EdgeModifierPanel({
- 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."}
- - + +
{appliedFeatureCount > 0 ? ( @@ -253,26 +260,27 @@ export function EdgeModifierPanel({ step={EDGE_MODIFIER_AMOUNT_STEP} workspace={workspace} length + disabled={!prepared} onChange={onAmountChange} /> - {kind === "chamfer" ? : null} + {kind === "chamfer" ? : null} - +
diff --git a/apps/web/src/lib/cadModifierGroups.ts b/apps/web/src/lib/cadModifierGroups.ts new file mode 100644 index 0000000..7bf4284 --- /dev/null +++ b/apps/web/src/lib/cadModifierGroups.ts @@ -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(); + 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; +} diff --git a/apps/web/src/lib/cadModifierRuntime.ts b/apps/web/src/lib/cadModifierRuntime.ts new file mode 100644 index 0000000..9ec4db1 --- /dev/null +++ b/apps/web/src/lib/cadModifierRuntime.ts @@ -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."; +} diff --git a/apps/web/src/lib/edgeTreatmentHistory.ts b/apps/web/src/lib/edgeTreatmentHistory.ts new file mode 100644 index 0000000..7783f10 --- /dev/null +++ b/apps/web/src/lib/edgeTreatmentHistory.ts @@ -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, + }); +} diff --git a/apps/web/src/lib/gridSnap.ts b/apps/web/src/lib/gridSnap.ts new file mode 100644 index 0000000..8e81657 --- /dev/null +++ b/apps/web/src/lib/gridSnap.ts @@ -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), + }; +} diff --git a/apps/web/src/lib/stlImport.ts b/apps/web/src/lib/stlImport.ts index 83aa362..9e546b6 100644 --- a/apps/web/src/lib/stlImport.ts +++ b/apps/web/src/lib/stlImport.ts @@ -4,7 +4,7 @@ import { createLocalId } from "@/lib/localIds"; import type { WorkplaneShape } from "@/types/sketchforge"; const stlLoader = new STLLoader(); -const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl"]); +const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl", "svg"]); function fileExtension(fileName: string) { return fileName.split(".").pop()?.toLowerCase() ?? ""; diff --git a/apps/web/src/lib/svgImport.ts b/apps/web/src/lib/svgImport.ts new file mode 100644 index 0000000..3b515d2 --- /dev/null +++ b/apps/web/src/lib/svgImport.ts @@ -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 (/]*/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 (!/]*>/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(/ 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(); + 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(); + 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(); + 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(); + 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`; + } +} diff --git a/apps/web/src/lib/workplaneGrid.ts b/apps/web/src/lib/workplaneGrid.ts new file mode 100644 index 0000000..e0cbdd6 --- /dev/null +++ b/apps/web/src/lib/workplaneGrid.ts @@ -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; +} diff --git a/apps/web/src/lib/workplaneShapes.ts b/apps/web/src/lib/workplaneShapes.ts index 0e3fae7..b0e864e 100644 --- a/apps/web/src/lib/workplaneShapes.ts +++ b/apps/web/src/lib/workplaneShapes.ts @@ -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; } diff --git a/apps/web/src/workers/cadModifier.worker.ts b/apps/web/src/workers/cadModifier.worker.ts index b238985..b47bee4 100644 --- a/apps/web/src/workers/cadModifier.worker.ts +++ b/apps/web/src/workers/cadModifier.worker.ts @@ -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 }) => 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); diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 3961eaf..f167b6b 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -1,6 +1,8 @@ # syntax=docker/dockerfile:1 -FROM node:22-alpine AS builder +# The exported web app is architecture-independent. Build it once on the +# native GitHub runner instead of repeating npm/Next.js under arm64 QEMU. +FROM --platform=$BUILDPLATFORM node:22-alpine AS builder WORKDIR /app @@ -11,12 +13,12 @@ COPY package.json package-lock.json ./ RUN npm ci COPY . . -RUN npm run build +RUN npm run build && npm run verify:static-worker-assets FROM nginx:stable-alpine AS runner COPY deploy/docker/nginx.conf /etc/nginx/conf.d/default.conf -COPY --from=builder /app/apps/web/out /usr/share/nginx/html +COPY --from=builder /app/apps/web/.next-export /usr/share/nginx/html EXPOSE 80 diff --git a/docs/media/sketchforge-editor-v0.5.png b/docs/media/sketchforge-editor-v0.6.png similarity index 100% rename from docs/media/sketchforge-editor-v0.5.png rename to docs/media/sketchforge-editor-v0.6.png diff --git a/package-lock.json b/package-lock.json index fa1fbcc..57e84de 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,13 @@ { "name": "sketchforge", - "version": "0.5.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sketchforge", - "version": "0.5.0", + "version": "0.6.0", + "license": "MIT", "dependencies": { "@tailwindcss/postcss": "^4.1.8", "@types/three": "^0.184.1", diff --git a/package.json b/package.json index 181bbcd..e593d15 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,16 @@ { "name": "sketchforge", - "version": "0.5.0", + "version": "0.6.0", "private": true, + "license": "MIT", "scripts": { "copy:occt": "node scripts/copy-occt-wasm.mjs", "predev": "npm run copy:occt", "dev": "next dev apps/web", "prebuild": "npm run copy:occt", "build": "next build apps/web", - "export": "set STATIC_EXPORT=true&& next build apps/web", + "export": "set STATIC_EXPORT=true&& next build apps/web && node scripts/verify-static-worker-assets.mjs", + "verify:static-worker-assets": "node scripts/verify-static-worker-assets.mjs", "start": "next start apps/web", "typecheck": "tsc -p apps/web/tsconfig.json --noEmit", "test": "vitest run --config tests/vitest.config.ts", diff --git a/scripts/verify-static-worker-assets.mjs b/scripts/verify-static-worker-assets.mjs new file mode 100644 index 0000000..7f0a4b7 --- /dev/null +++ b/scripts/verify-static-worker-assets.mjs @@ -0,0 +1,47 @@ +import { readdir, readFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repositoryRoot = dirname(dirname(fileURLToPath(import.meta.url))); +const exportRoot = join(repositoryRoot, "apps", "web", ".next-export"); +const chunksRoot = join(exportRoot, "_next", "static", "chunks"); + +async function listJavaScriptFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const files = await Promise.all( + entries.map((entry) => { + const path = join(directory, entry.name); + return entry.isDirectory() ? listJavaScriptFiles(path) : [path]; + }), + ); + + return files.flat().filter((path) => path.endsWith(".js")); +} + +const indexHtml = await readFile(join(exportRoot, "index.html"), "utf8"); +if (indexHtml.includes('="./_next/')) { + throw new Error( + "Static HTML uses a relative ./_next asset prefix. Worker chunks resolve that prefix " + + "relative to their own directory and request a duplicated /_next/static/chunks path.", + ); +} + +const workerChunks = []; +for (const path of await listJavaScriptFiles(chunksRoot)) { + const source = await readFile(path, "utf8"); + if (source.includes("importScripts(") && source.includes("static/chunks/")) { + workerChunks.push({ path, source }); + } +} + +if (workerChunks.length === 0) { + throw new Error("Could not find the generated CAD worker runtime to verify its public path."); +} + +for (const { path, source } of workerChunks) { + if (!source.includes('.p="/_next/"') && !source.includes(".p='/_next/'")) { + throw new Error(`Worker runtime ${path} does not use the root-relative /_next/ public path.`); + } +} + +console.log(`Verified ${workerChunks.length} static worker runtime(s) use /_next/.`); diff --git a/tests/unit/cadModifierGroups.test.ts b/tests/unit/cadModifierGroups.test.ts new file mode 100644 index 0000000..f7b2787 --- /dev/null +++ b/tests/unit/cadModifierGroups.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { hasOneToOneCadComponentMapping } from "@/lib/cadModifierGroups"; + +describe("grouped CAD modifier component tracking", () => { + it("tracks grouped children only when every source still has one distinct CAD component", () => { + expect(hasOneToOneCadComponentMapping(2, [0, 1])).toBe(true); + expect(hasOneToOneCadComponentMapping(3, [2, 0, 1])).toBe(true); + }); + + it("falls back to the cumulative group body when touching parts fuse into fewer components", () => { + expect(hasOneToOneCadComponentMapping(2, [0])).toBe(false); + expect(hasOneToOneCadComponentMapping(2, [0, 0])).toBe(false); + }); +}); diff --git a/tests/unit/cadModifierRuntime.test.ts b/tests/unit/cadModifierRuntime.test.ts new file mode 100644 index 0000000..7355ae6 --- /dev/null +++ b/tests/unit/cadModifierRuntime.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; +import { + CAD_MODIFIER_REQUEST_TIMEOUT_MS, + CAD_MODIFIER_RUNTIME_BASE, + cadModifierTimeoutMessage, + edgeModifierSelectionStatus, +} from "@/lib/cadModifierRuntime"; + +describe("CAD modifier runtime state", () => { + it("uses the build-managed OCCT runtime", () => { + expect(CAD_MODIFIER_RUNTIME_BASE).toBe("/occt"); + }); + + it("does not report zero edges before preparation finishes", () => { + expect(edgeModifierSelectionStatus(false, 0, 0)).toBe("Preparing edges\u2026"); + expect(edgeModifierSelectionStatus(true, 0, 0)).toBe("0 of 0 sharp edges selected"); + expect(edgeModifierSelectionStatus(true, 2, 12)).toBe("2 of 12 sharp edges selected"); + }); + + it("sets a bounded preparation wait and an actionable compatibility error", () => { + expect(CAD_MODIFIER_REQUEST_TIMEOUT_MS).toBeGreaterThanOrEqual(20_000); + expect(CAD_MODIFIER_REQUEST_TIMEOUT_MS).toBeLessThanOrEqual(60_000); + expect(cadModifierTimeoutMessage("prepare")).toContain("Firefox 121+"); + }); +}); diff --git a/tests/unit/edgeTreatmentHistory.test.ts b/tests/unit/edgeTreatmentHistory.test.ts new file mode 100644 index 0000000..63bebae --- /dev/null +++ b/tests/unit/edgeTreatmentHistory.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from "vitest"; +import { restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory"; +import type { EdgeTreatmentHistoryEntry, WorkplaneShape } from "@/types/sketchforge"; + +function box(overrides: Partial = {}): WorkplaneShape { + return { + id: "box", + name: "Box", + kind: "box", + color: "#d41721", + x: 0, + z: 0, + elevation: 0, + size: 20, + width: 20, + depth: 20, + height: 20, + rotation: 0, + locked: false, + hidden: false, + ...overrides, + }; +} + +function historyEntry(before: WorkplaneShape): EdgeTreatmentHistoryEntry { + return { + id: "history-1", + createdAt: 1, + feature: { kind: "chamfer", amount: 1, edgeCount: 1 }, + before, + }; +} + +describe("edge treatment history restoration", () => { + it("restores a grouped snapshot instead of retaining the treated mesh bounding box", () => { + const before = box({ + id: "group-before", + name: "Group", + kind: "mesh", + x: 8, + width: 56, + depth: 24, + height: 60, + size: 56, + groupedBaseWidth: 56, + groupedBaseDepth: 24, + groupedBaseHeight: 60, + groupedShapes: [ + box({ id: "normal-child", x: -18 }), + box({ id: "tall-child", x: 14, width: 8, depth: 10, height: 60, size: 10 }), + ], + }); + const treated = box({ + id: "group-current", + name: "Renamed group", + kind: "mesh", + color: "#12abef", + x: 0, + width: 80, + depth: 40, + height: 60, + size: 80, + importedMesh: { + positions: [-40, 0, -20, 40, 0, -20, 40, 60, 20], + baseWidth: 80, + baseDepth: 40, + baseHeight: 60, + triangleCount: 1, + sourceFormat: "json", + }, + edgeTreatments: [{ kind: "chamfer", amount: 1, edgeCount: 1 }], + }); + + const restored = restoreShapeBeforeEdgeTreatment(treated, historyEntry(before)); + + expect(restored).toMatchObject({ + id: "group-current", + name: "Renamed group", + color: "#12abef", + kind: "mesh", + x: 8, + width: 56, + depth: 24, + height: 60, + }); + expect(restored.importedMesh).toBeUndefined(); + expect(restored.edgeTreatments).toBeUndefined(); + expect(restored.groupedShapes?.map((child) => [child.width, child.depth, child.height])).toEqual([ + [20, 20, 20], + [8, 10, 60], + ]); + }); + + it("does not resize a restored child primitive to a combined component's bounds", () => { + const before = box({ id: "thin-before", x: 18, width: 8, depth: 6, height: 50, size: 8 }); + const combinedComponent = box({ + id: "thin-current", + kind: "mesh", + x: 0, + width: 54, + depth: 30, + height: 50, + size: 54, + importedMesh: { + positions: [-27, 0, -15, 27, 0, -15, 27, 50, 15], + baseWidth: 54, + baseDepth: 30, + baseHeight: 50, + triangleCount: 1, + sourceFormat: "json", + }, + }); + + const restored = restoreShapeBeforeEdgeTreatment(combinedComponent, historyEntry(before)); + + expect(restored).toMatchObject({ kind: "box", x: 18, width: 8, depth: 6, height: 50, size: 8 }); + expect(restored.importedMesh).toBeUndefined(); + }); +}); diff --git a/tests/unit/gridSnap.test.ts b/tests/unit/gridSnap.test.ts new file mode 100644 index 0000000..b84b19d --- /dev/null +++ b/tests/unit/gridSnap.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "vitest"; +import { snapShapeFootprintToVisibleGrid } from "@/lib/gridSnap"; +import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings"; +import type { WorkplaneShape } from "@/types/sketchforge"; + +function groupedShape(): WorkplaneShape { + return { + id: "group", + name: "Group", + kind: "mesh", + color: "#d41721", + x: 3.2, + z: -1.7, + elevation: 2.4, + size: 43.5, + width: 43.5, + depth: 19.8, + height: 31.25, + rotation: 0, + groupedBaseWidth: 43.5, + groupedBaseDepth: 19.8, + groupedBaseHeight: 31.25, + groupedShapes: [ + { + id: "child-a", + name: "Child A", + kind: "box", + color: "#d41721", + x: -10.75, + z: 1.2, + elevation: 0, + size: 20, + width: 20, + depth: 12, + height: 20, + rotation: 0, + }, + { + id: "child-b", + name: "Child B", + kind: "box", + color: "#0098c7", + x: 14.5, + z: -2.8, + elevation: 0, + size: 10, + width: 8, + depth: 10, + height: 31.25, + rotation: 0, + }, + ], + }; +} + +describe("Snap to Grid", () => { + it("translates a group footprint to the visible grid without resizing it or changing child offsets", () => { + const group = groupedShape(); + const snapped = snapShapeFootprintToVisibleGrid( + group, + { minX: -17.3, minZ: -11.4 }, + { ...DEFAULT_WORKPLANE_WORKSPACE, gridBlockSize: 5 }, + ); + + expect(snapped.x).toBe(5.5); + expect(snapped.z).toBe(-0.3); + expect(-17.3 + snapped.x - group.x).toBeCloseTo(-15, 6); + expect(-11.4 + snapped.z - group.z).toBeCloseTo(-10, 6); + expect(snapped).toMatchObject({ + elevation: 2.4, + width: 43.5, + depth: 19.8, + height: 31.25, + size: 43.5, + }); + expect(snapped.groupedShapes).toBe(group.groupedShapes); + }); + + it("uses the rendered grid origin for custom workplane dimensions", () => { + const group = groupedShape(); + const snapped = snapShapeFootprintToVisibleGrid( + group, + { minX: -18, minZ: -13 }, + { ...DEFAULT_WORKPLANE_WORKSPACE, width: 203, depth: 187, gridBlockSize: 10 }, + ); + + expect(-18 + snapped.x - group.x).toBeCloseTo(-21.5, 6); + expect(-13 + snapped.z - group.z).toBeCloseTo(-13.5, 6); + }); +}); diff --git a/tests/unit/importExtensions.test.ts b/tests/unit/importExtensions.test.ts new file mode 100644 index 0000000..627da42 --- /dev/null +++ b/tests/unit/importExtensions.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; +import { importExtensionSupported } from "@/lib/stlImport"; + +describe("importExtensionSupported", () => { + it("accepts STL and SVG imports", () => { + expect(importExtensionSupported("part.stl")).toBe(true); + expect(importExtensionSupported("logo.svg")).toBe(true); + expect(importExtensionSupported("profile.SVG")).toBe(true); + }); + + it("rejects unsupported dashboard import extensions", () => { + expect(importExtensionSupported("drawing.png")).toBe(false); + expect(importExtensionSupported("assembly.step")).toBe(false); + }); +}); diff --git a/tests/unit/svgImport.test.ts b/tests/unit/svgImport.test.ts new file mode 100644 index 0000000..533fa64 --- /dev/null +++ b/tests/unit/svgImport.test.ts @@ -0,0 +1,135 @@ +import { describe, expect, it } from "vitest"; +import * as THREE from "three"; +import { + MAX_SVG_GEOMETRY_ELEMENTS, + analyzeTriangleSoup, + buildSvgExtrusionFromPaths, + normalizeSvgUseReferences, + validateClosedSolidTriangleSoup, + validateSvgSourcePreflight, +} from "@/lib/svgImport"; + +function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill?: string; fillOpacity?: number; opacity?: number } = {}) { + const path = new THREE.ShapePath(); + path.moveTo(points[0][0], points[0][1]); + for (const [x, y] of points.slice(1)) path.lineTo(x, y); + if (options.closed !== false) path.currentPath!.autoClose = true; + (path as THREE.ShapePath & { userData: unknown }).userData = { + style: { + fill: options.fill ?? "#000", + fillOpacity: options.fillOpacity ?? 1, + opacity: options.opacity ?? 1, + visibility: "visible", + }, + }; + return path; +} + +function rectangle(x: number, y: number, width: number, height: number, options?: Parameters[1]) { + return shapePath( + [ + [x, y], + [x + width, y], + [x + width, y + height], + [x, y + height], + ], + options, + ); +} + +function geometryPositions(geometry: THREE.BufferGeometry) { + const nonIndexed = geometry.index ? geometry.toNonIndexed() : geometry; + const attribute = nonIndexed.getAttribute("position"); + const positions: number[] = []; + for (let index = 0; index < attribute.count; index += 1) { + positions.push(attribute.getX(index), attribute.getY(index), attribute.getZ(index)); + } + if (nonIndexed !== geometry) nonIndexed.dispose(); + geometry.dispose(); + return positions; +} + +describe("SVG source preflight", () => { + it("rejects XML entities and external references", () => { + expect(() => validateSvgSourcePreflight(']>')).toThrow(/document types and entities/i); + expect(() => validateSvgSourcePreflight('')).toThrow(/external references/i); + }); + + it("rejects excessive geometry before SVGLoader runs", () => { + const source = `${"".repeat(MAX_SVG_GEOMETRY_ELEMENTS + 1)}`; + expect(() => validateSvgSourcePreflight(source)).toThrow(/too many geometry elements/i); + }); + + it("normalizes modern local use href attributes for SVGLoader", () => { + const normalized = normalizeSvgUseReferences(''); + expect(normalized).toContain('xmlns:xlink="http://www.w3.org/1999/xlink"'); + expect(normalized).toContain('xlink:href="#p"'); + }); +}); + +describe("SVG path extrusion", () => { + it("creates a watertight solid with real, unclamped dimensions", () => { + const result = buildSvgExtrusionFromPaths([rectangle(0, 0, 0.25, 0.5)]); + expect(result.analysis.width).toBeCloseTo(0.25); + expect(result.analysis.height).toBeCloseTo(4); + expect(result.analysis.depth).toBeCloseTo(0.5); + expect(result.analysis.volume).toBeCloseTo(0.5); + expect(result.analysis.boundaryEdges).toBe(0); + expect(result.analysis.nonManifoldEdges).toBe(0); + }); + + it("treats a separately defined contained contour as a hole", () => { + const result = buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10), rectangle(3, 3, 4, 4)]); + expect(result.analysis.volume).toBeCloseTo((100 - 16) * 4, 5); + expect(result.analysis.boundaryEdges).toBe(0); + }); + + it("ignores non-filled and fully transparent paths", () => { + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "none" })])).toThrow(/no readable visible filled paths/i); + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { opacity: 0 })])).toThrow(/no readable visible filled paths/i); + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fillOpacity: 0 })])).toThrow(/no readable visible filled paths/i); + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "#00000000" })])).toThrow(/no readable visible filled paths/i); + }); + + it("imports open filled contours when they enclose usable area and skips lines", () => { + const result = buildSvgExtrusionFromPaths([shapePath([[0, 0], [10, 0], [5, 5]], { closed: false })]); + expect(result.analysis.volume).toBeCloseTo(100); + expect(() => buildSvgExtrusionFromPaths([shapePath([[0, 0], [10, 0]], { closed: false })])).toThrow(/no (?:readable )?filled (?:paths|contours)/i); + }); + + it("skips closed collinear paths", () => { + expect(() => buildSvgExtrusionFromPaths([shapePath([[0, 0], [5, 0], [10, 0]])])).toThrow(/no readable filled paths/i); + }); + + it("imports overlapping contours as separate valid components", () => { + const result = buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10), rectangle(5, 5, 10, 10)]); + expect(result.analysis.volume).toBeCloseTo(800); + }); +}); + +describe("triangle-soup solid validation", () => { + it("accepts a closed box", () => { + const positions = geometryPositions(new THREE.BoxGeometry(2, 3, 4)); + const analysis = validateClosedSolidTriangleSoup(positions); + expect(analysis.volume).toBeCloseTo(24); + expect(analysis.boundaryEdges).toBe(0); + expect(analysis.nonManifoldEdges).toBe(0); + }); + + it("rejects an open box shell", () => { + const positions = geometryPositions(new THREE.BoxGeometry(2, 3, 4)).slice(9); + expect(analyzeTriangleSoup(positions).boundaryEdges).toBeGreaterThan(0); + expect(() => validateClosedSolidTriangleSoup(positions)).toThrow(/not a watertight manifold/i); + }); + + it("rejects a topologically closed zero-volume shell", () => { + const positions = [ + 0, 0, 0, 1, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, 0, 1, 0, 0, + ]; + const analysis = analyzeTriangleSoup(positions); + expect(analysis.boundaryEdges).toBe(0); + expect(analysis.volume).toBe(0); + expect(() => validateClosedSolidTriangleSoup(positions)).toThrow(/non-zero volume/i); + }); +}); diff --git a/tests/unit/workplaneGrid.test.ts b/tests/unit/workplaneGrid.test.ts new file mode 100644 index 0000000..2afadde --- /dev/null +++ b/tests/unit/workplaneGrid.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { interiorWorkplaneGridCoordinates, workplaneGridPalette, WORKPLANE_LINE_ELEVATION } from "@/lib/workplaneGrid"; + +describe("workplane grid geometry", () => { + it("excludes both perimeter coordinates when spacing divides the workplane", () => { + const coordinates = interiorWorkplaneGridCoordinates(200, 5).map(({ coordinate }) => coordinate); + + expect(coordinates).not.toContain(-100); + expect(coordinates).not.toContain(100); + expect(coordinates).toContain(0); + expect(coordinates.at(0)).toBe(-95); + expect(coordinates.at(-1)).toBe(95); + }); + + it("keeps the final interior line for custom spacing", () => { + const coordinates = interiorWorkplaneGridCoordinates(200, 30).map(({ coordinate }) => coordinate); + + expect(coordinates).toEqual([-70, -40, -10, 20, 50, 80]); + }); + + it("uses one elevation for grid and border lines", () => { + expect(WORKPLANE_LINE_ELEVATION).toBe(0); + }); + + it("preserves the minor, major, and axis line hierarchy", () => { + const palette = workplaneGridPalette(); + + expect(palette.minor.opacity).toBeLessThan(palette.major.opacity); + expect(palette.major.opacity).toBeLessThan(palette.axis.opacity); + expect(palette.minor.color).not.toBe(palette.major.color); + }); +}); diff --git a/tests/unit/workplaneSettings.test.ts b/tests/unit/workplaneSettings.test.ts index a31e694..c753d24 100644 --- a/tests/unit/workplaneSettings.test.ts +++ b/tests/unit/workplaneSettings.test.ts @@ -80,9 +80,11 @@ describe("workplane settings helpers", () => { it("fingerprints workspace and snap settings together", () => { const base = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm"); + const equivalentNewReference = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE }, "1.0 mm"); const changedSnap = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "5.0 mm"); const changedWorkspace = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE, width: 300 }, "1.0 mm"); + expect(equivalentNewReference).toBe(base); expect(changedSnap).not.toBe(base); expect(changedWorkspace).not.toBe(base); }); diff --git a/tests/unit/workplaneShapes.test.ts b/tests/unit/workplaneShapes.test.ts index 2de9304..8fd46df 100644 --- a/tests/unit/workplaneShapes.test.ts +++ b/tests/unit/workplaneShapes.test.ts @@ -16,6 +16,7 @@ import { serializeShapesForSync, shapeDepth, shapeWidth, + withHoleMode, workplaneShapesEqual, } from "@/lib/workplaneShapes"; @@ -114,6 +115,29 @@ describe("workplane shape helpers", () => { expect(fallbackSolidColor(shape({ kind: "box" }))).toBe("#d41721"); }); + it("applies an explicitly selected group color to every nested child", () => { + const grouped = shape({ + kind: "mesh", + color: "#111111", + groupedShapes: [ + shape({ id: "child-box", color: "#222222" }), + shape({ + id: "child-group", + kind: "mesh", + color: "#333333", + groupedShapes: [shape({ id: "grandchild", kind: "sphere", color: "#444444" })], + }), + ], + }); + + const recolored = withHoleMode(grouped, false, "#12abef"); + + expect(recolored.color).toBe("#12abef"); + expect(recolored.groupedShapes?.map((child) => child.color)).toEqual(["#12abef", "#12abef"]); + expect(recolored.groupedShapes?.[1].groupedShapes?.[0].color).toBe("#12abef"); + expect(grouped.groupedShapes?.[0].color).toBe("#222222"); + }); + it("can resize the body while preserving fillet and chamfer boundary distances", () => { const modified = shape({ kind: "mesh",