From fd76c5bd965a8d4218ecfaae3b95d7e479190cf9 Mon Sep 17 00:00:00 2001 From: Francisco Rivero Date: Tue, 7 Jul 2026 23:59:36 +0900 Subject: [PATCH 1/7] Add SVG import extrusion --- .gitignore | 1 + apps/web/src/app/page.tsx | 33 ++++++++++--------- apps/web/src/components/SketchForgeEditor.tsx | 26 ++++++++++++--- apps/web/src/components/WorkplaneViewport.tsx | 2 +- apps/web/src/lib/stlImport.ts | 2 +- tests/unit/importExtensions.test.ts | 15 +++++++++ 6 files changed, 57 insertions(+), 22 deletions(-) create mode 100644 tests/unit/importExtensions.test.ts diff --git a/.gitignore b/.gitignore index c6b403a..406f134 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,7 @@ playwright-report/ # Local workspace state .codex/ +.codex-run/ .codex-remote-attachments/ # OS/editor noise diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 574c6aa..5f057fe 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -2,7 +2,7 @@ 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"; @@ -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,7 +255,7 @@ 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>>({}); @@ -513,15 +513,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 +611,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 +640,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 +691,7 @@ function Dashboard({ onDeleteProject, onDownloadFolderChange, onDownloadModeChange, - onImportStl, + onImportFile, onChallenges, onDashboardHome, onOpenProject, @@ -714,7 +717,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 +813,11 @@ function Dashboard({ Create new 3D design - diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 2e327ca..edb646d 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -4437,7 +4437,7 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, roughness: shape.hole ? 0.88 : 0.57, metalness: 0.02, - side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, + side: shape.importedMesh?.sourceFormat === "json" || shape.importedMesh?.sourceFormat === "svg" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, }); const width = shapeWidth(shape); 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/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); + }); +}); From d37a11964e346e7226b8096ebc48ed5519dae3c1 Mon Sep 17 00:00:00 2001 From: Formsmith Date: Tue, 7 Jul 2026 20:37:24 +0300 Subject: [PATCH 2/7] docs: add GitHub Sponsors badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 43c9cda..41b1140 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@

MIT license GitHub stars + GitHub Sponsors Local first Version 0.5.0

From 431538c541e3e8460d1d1726611250e1b1e8871e Mon Sep 17 00:00:00 2001 From: Formsmith <214276465+Formsmith746@users.noreply.github.com> Date: Fri, 10 Jul 2026 22:08:41 +0300 Subject: [PATCH 3/7] chore: adopt MIT license with Commons Clause --- .github/CONTRIBUTING.md | 4 ++++ LICENSE | 12 ++++++++++++ README.md | 6 ++++-- package-lock.json | 3 ++- package.json | 1 + 5 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d83c0f8..2508e80 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 same terms as SketchForge: the MIT License with the "Commons Clause" License Condition v1.0. See [LICENSE](../LICENSE). diff --git a/LICENSE b/LICENSE index 8135b1d..2fa5053 100644 --- a/LICENSE +++ b/LICENSE @@ -1,3 +1,15 @@ +"Commons Clause" License Condition v1.0 + +The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition. + +Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Software. + +For purposes of the foregoing, "Sell" means practicing any or all of the rights granted to you under the License to provide to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/ support services related to the Software), a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Clause License Condition notice. + +Software: SketchForge +License: MIT License +Licensor: Formsmith746 + MIT License Copyright (c) 2026 SketchForge contributors diff --git a/README.md b/README.md index 41b1140..85903c7 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@

- MIT license + MIT with Commons Clause license GitHub stars GitHub Sponsors Local first @@ -329,7 +329,9 @@ Please do not open public issues for security-sensitive reports. Read [.github/S ## License -MIT. See [LICENSE](LICENSE). +Future SketchForge releases are licensed under the [MIT License with the "Commons Clause" License Condition v1.0](LICENSE). The Commons Clause restricts selling the software, or a product or service whose value derives substantially from it. This is a source-available license, not an OSI-approved open-source license. + +Previously published releases remain under the license that accompanied them. ## SketchForge MCP Skill diff --git a/package-lock.json b/package-lock.json index fa1fbcc..1b782d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,7 +29,8 @@ "@types/react-dom": "^19.1.5", "typescript": "^5.8.3", "vitest": "^4.1.8" - } + }, + "license": "SEE LICENSE IN LICENSE" }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", diff --git a/package.json b/package.json index 181bbcd..8815d58 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "sketchforge", "version": "0.5.0", "private": true, + "license": "SEE LICENSE IN LICENSE", "scripts": { "copy:occt": "node scripts/copy-occt-wasm.mjs", "predev": "npm run copy:occt", From f91aa2fe9c4ee7ed68c4371a76f8a1bd0caef573 Mon Sep 17 00:00:00 2001 From: Formsmith <214276465+Formsmith746@users.noreply.github.com> Date: Fri, 10 Jul 2026 22:48:26 +0300 Subject: [PATCH 4/7] ci: prevent stalled multi-platform Docker builds --- .dockerignore | 18 ++++++++++++++++++ .github/workflows/docker.yml | 16 ++++++++++------ deploy/docker/Dockerfile | 4 +++- 3 files changed, 31 insertions(+), 7 deletions(-) create mode 100644 .dockerignore 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/workflows/docker.yml b/.github/workflows/docker.yml index 244c124..a0c0c4a 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 \ No newline at end of file diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 3961eaf..3cc64ac 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 From 0c53cf41e238656e9ff008cbeed546f38022e42c Mon Sep 17 00:00:00 2001 From: Formsmith <214276465+Formsmith746@users.noreply.github.com> Date: Fri, 10 Jul 2026 23:14:21 +0300 Subject: [PATCH 5/7] chore: restore standard MIT license --- .github/CONTRIBUTING.md | 2 +- LICENSE | 12 ------------ README.md | 6 ++---- package-lock.json | 2 +- package.json | 2 +- 5 files changed, 5 insertions(+), 19 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 2508e80..315c173 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -38,4 +38,4 @@ The app runs at `http://127.0.0.1:3000/` by default. ## Contribution Licensing -Unless explicitly agreed otherwise in writing, by submitting a contribution you license it under the same terms as SketchForge: the MIT License with the "Commons Clause" License Condition v1.0. See [LICENSE](../LICENSE). +Unless explicitly agreed otherwise in writing, by submitting a contribution you license it under the MIT License. See [LICENSE](../LICENSE). diff --git a/LICENSE b/LICENSE index 2fa5053..8135b1d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,15 +1,3 @@ -"Commons Clause" License Condition v1.0 - -The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition. - -Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Software. - -For purposes of the foregoing, "Sell" means practicing any or all of the rights granted to you under the License to provide to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/ support services related to the Software), a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Clause License Condition notice. - -Software: SketchForge -License: MIT License -Licensor: Formsmith746 - MIT License Copyright (c) 2026 SketchForge contributors diff --git a/README.md b/README.md index 85903c7..41b1140 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@

- MIT with Commons Clause license + MIT license GitHub stars GitHub Sponsors Local first @@ -329,9 +329,7 @@ Please do not open public issues for security-sensitive reports. Read [.github/S ## License -Future SketchForge releases are licensed under the [MIT License with the "Commons Clause" License Condition v1.0](LICENSE). The Commons Clause restricts selling the software, or a product or service whose value derives substantially from it. This is a source-available license, not an OSI-approved open-source license. - -Previously published releases remain under the license that accompanied them. +MIT. See [LICENSE](LICENSE). ## SketchForge MCP Skill diff --git a/package-lock.json b/package-lock.json index 1b782d4..1fb6648 100644 --- a/package-lock.json +++ b/package-lock.json @@ -30,7 +30,7 @@ "typescript": "^5.8.3", "vitest": "^4.1.8" }, - "license": "SEE LICENSE IN LICENSE" + "license": "MIT" }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", diff --git a/package.json b/package.json index 8815d58..2f7535c 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "sketchforge", "version": "0.5.0", "private": true, - "license": "SEE LICENSE IN LICENSE", + "license": "MIT", "scripts": { "copy:occt": "node scripts/copy-occt-wasm.mjs", "predev": "npm run copy:occt", From 458538d3d4848e36f630569ed6558424ace9865c Mon Sep 17 00:00:00 2001 From: Formsmith <214276465+Formsmith746@users.noreply.github.com> Date: Fri, 10 Jul 2026 23:19:21 +0300 Subject: [PATCH 6/7] docs: remove project layout and status sections --- README.md | 34 ---------------------------------- 1 file changed, 34 deletions(-) diff --git a/README.md b/README.md index 41b1140..0e6552a 100644 --- a/README.md +++ b/README.md @@ -276,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: From 20731043e45088d1d53f1328f100cf431065c72a Mon Sep 17 00:00:00 2001 From: Formsmith <214276465+Formsmith746@users.noreply.github.com> Date: Sat, 11 Jul 2026 20:34:13 +0300 Subject: [PATCH 7/7] release: publish v0.6.0 --- .github/workflows/docker.yml | 2 +- .gitignore | 1 + README.md | 4 +- apps/web/next.config.ts | 2 +- apps/web/src/app/globals.css | 132 ++++- apps/web/src/app/layout.tsx | 2 +- apps/web/src/app/page.tsx | 41 +- apps/web/src/components/SketchForgeEditor.tsx | 337 +++++------ apps/web/src/components/WorkplaneViewport.tsx | 225 ++++--- .../workplane/EdgeModifierPanel.tsx | 28 +- .../workplane/WorkspaceSettingsModal.tsx | 47 +- apps/web/src/lib/cadModifierGroups.ts | 14 + apps/web/src/lib/cadModifierRuntime.ts | 19 + apps/web/src/lib/edgeTreatmentHistory.ts | 19 + apps/web/src/lib/gridSnap.ts | 42 ++ apps/web/src/lib/svgImport.ts | 547 ++++++++++++++++++ apps/web/src/lib/workplaneGrid.ts | 45 ++ apps/web/src/lib/workplaneShapes.ts | 10 + apps/web/src/workers/cadModifier.worker.ts | 5 +- deploy/docker/Dockerfile | 4 +- ...r-v0.5.png => sketchforge-editor-v0.6.png} | Bin package-lock.json | 8 +- package.json | 5 +- scripts/verify-static-worker-assets.mjs | 47 ++ tests/unit/cadModifierGroups.test.ts | 14 + tests/unit/cadModifierRuntime.test.ts | 25 + tests/unit/edgeTreatmentHistory.test.ts | 119 ++++ tests/unit/gridSnap.test.ts | 90 +++ tests/unit/svgImport.test.ts | 135 +++++ tests/unit/workplaneGrid.test.ts | 32 + tests/unit/workplaneSettings.test.ts | 2 + tests/unit/workplaneShapes.test.ts | 24 + 32 files changed, 1707 insertions(+), 320 deletions(-) create mode 100644 apps/web/src/lib/cadModifierGroups.ts create mode 100644 apps/web/src/lib/cadModifierRuntime.ts create mode 100644 apps/web/src/lib/edgeTreatmentHistory.ts create mode 100644 apps/web/src/lib/gridSnap.ts create mode 100644 apps/web/src/lib/svgImport.ts create mode 100644 apps/web/src/lib/workplaneGrid.ts rename docs/media/{sketchforge-editor-v0.5.png => sketchforge-editor-v0.6.png} (100%) create mode 100644 scripts/verify-static-worker-assets.mjs create mode 100644 tests/unit/cadModifierGroups.test.ts create mode 100644 tests/unit/cadModifierRuntime.test.ts create mode 100644 tests/unit/edgeTreatmentHistory.test.ts create mode 100644 tests/unit/gridSnap.test.ts create mode 100644 tests/unit/svgImport.test.ts create mode 100644 tests/unit/workplaneGrid.test.ts diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index a0c0c4a..21f2f15 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -51,4 +51,4 @@ jobs: tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha,scope=sketchforge-docker - cache-to: type=gha,mode=max,scope=sketchforge-docker \ No newline at end of file + cache-to: type=gha,mode=max,scope=sketchforge-docker diff --git a/.gitignore b/.gitignore index 406f134..1f93e4f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ node_modules/ # Next.js .next/ +.next-export/ out/ build/ dist/ diff --git a/README.md b/README.md index 0e6552a..76022a2 100644 --- a/README.md +++ b/README.md @@ -19,11 +19,11 @@ 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 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 492aa81..da4d7fb 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -2686,36 +2686,111 @@ button { .camera-controls { position: absolute; top: 173px; - left: 8px; + left: 10px; z-index: 8; - display: grid; - gap: 4px; + display: flex; + flex-direction: column; + gap: 2px; + padding: 5px; + background: rgba(255, 255, 255, 0.86); + border: 1px solid rgba(194, 209, 219, 0.9); + border-radius: 17px; + box-shadow: 0 10px 30px rgba(32, 64, 84, 0.14), 0 2px 6px rgba(32, 64, 84, 0.08); + backdrop-filter: blur(14px) saturate(1.15); } .camera-controls button { + position: relative; display: grid; - width: 51px; - height: 51px; + width: 44px; + height: 43px; place-items: center; color: #173b5a; - background: rgba(255, 255, 255, 0.88); - border: 1px solid #dfe6eb; - border-radius: 999px; - box-shadow: 0 1px 2px rgba(30, 50, 70, 0.08); + background: transparent; + border: 1px solid transparent; + border-radius: 12px; + box-shadow: none; cursor: pointer; + transition: color 140ms ease, background-color 140ms ease, border-color 140ms ease, transform 140ms ease; } .camera-controls button:hover { - color: #000; - border-color: #c4d2dc; + color: #071f32; + background: rgba(223, 239, 247, 0.82); + border-color: rgba(155, 190, 207, 0.7); + transform: translateX(1px); +} + +.camera-controls button:focus-visible { + outline: 2px solid #28a9d2; + outline-offset: 1px; +} + +.camera-controls.collapsed { + border-radius: 17px; } .camera-controls button.active, .camera-controls button[aria-pressed="true"] { - color: #007eae; - background: #e8f8fd; - border-color: #63cbe8; - box-shadow: 0 0 0 3px rgba(0, 159, 207, 0.14), 0 1px 2px rgba(30, 50, 70, 0.08); + color: #006b94; + background: #def5fb; + border-color: #6fc8df; + box-shadow: inset 3px 0 0 #079bc6; +} + +.ruler-control-group { + position: relative; + margin-top: 6px; +} + +.ruler-control-group::before { + position: absolute; + top: -5px; + right: 8px; + left: 8px; + height: 1px; + content: ""; + background: rgba(117, 144, 160, 0.28); +} + +.ruler-tool-popover { + position: absolute; + top: 2px; + left: calc(100% + 10px); + display: flex; + gap: 3px; + padding: 4px; + background: rgba(255, 255, 255, 0.94); + border: 1px solid rgba(194, 209, 219, 0.94); + border-radius: 13px; + box-shadow: 0 8px 24px rgba(32, 64, 84, 0.18), 0 2px 6px rgba(32, 64, 84, 0.1); + backdrop-filter: blur(14px) saturate(1.15); + animation: ruler-tools-in 130ms ease-out; +} + +.camera-controls .ruler-tool-popover button { + width: 35px; + height: 35px; + border-radius: 9px; +} + +.camera-controls .ruler-tool-popover .ruler-delete-button.active { + color: #b42318; + background: #fff0ee; + border-color: #ee9b92; + box-shadow: inset 3px 0 0 #dc3f36; +} + +@keyframes ruler-tools-in { + from { + opacity: 0; + transform: translateX(-4px) scale(0.96); + } + + to { + opacity: 1; + transform: translateX(0) scale(1); + } } .workplane-wrap { @@ -2757,6 +2832,11 @@ button { cursor: crosshair; } +.workplane-wrap.ruler-delete-mode .three-workplane-host, +.workplane-wrap.ruler-delete-mode .three-workplane-host:active { + cursor: default; +} + .workplane-wrap.modifier-edge-pick .three-workplane-host, .workplane-wrap.modifier-edge-pick .three-workplane-host:active { cursor: crosshair; @@ -2796,6 +2876,7 @@ button { stroke-width: 2; vector-effect: non-scaling-stroke; pointer-events: none; + transition: stroke 120ms ease, stroke-width 120ms ease; } .ruler-segment-hit { @@ -2817,6 +2898,19 @@ button { .ruler-point { pointer-events: all; cursor: pointer; + transition: fill 120ms ease, stroke 120ms ease, filter 120ms ease; +} + +.ruler-overlay.delete-mode .ruler-segment-group:hover .ruler-segment { + stroke: #dc3f36; + stroke-width: 3; + filter: drop-shadow(0 0 2px rgba(220, 63, 54, 0.3)); +} + +.ruler-overlay.delete-mode .ruler-point:hover { + fill: #fff0ee; + stroke: #dc3f36; + filter: drop-shadow(0 0 3px rgba(220, 63, 54, 0.36)); } .ruler-point.pending { @@ -4142,6 +4236,14 @@ button { font-weight: 700; } +.workspace-global-note { + margin: -10px 0 0 153px; + color: #718697; + font-size: 12px; + font-weight: 650; + line-height: 1.45; +} + .workspace-dimensions { display: grid; grid-template-columns: 1fr 1fr; 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 5f057fe..76cbb41 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor"; import { createLocalId } from "@/lib/localIds"; import { importExtensionSupported } from "@/lib/stlImport"; -import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; +import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; type AppView = "dashboard" | "editor"; @@ -260,6 +260,13 @@ export default function Home() { const projectShapeSaveQueuesRef = useRef>>({}); 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) => { diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index 780025d..a4aa4c6 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -9,7 +9,6 @@ import * as THREE from "three"; import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js"; import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js"; import { FontLoader, type Font, type FontData } from "three/examples/jsm/loaders/FontLoader.js"; -import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js"; import droidMonoFontJson from "three/examples/fonts/droid/droid_sans_mono_regular.typeface.json"; import droidSansBoldFontJson from "three/examples/fonts/droid/droid_sans_bold.typeface.json"; import droidSerifBoldFontJson from "three/examples/fonts/droid/droid_serif_bold.typeface.json"; @@ -60,13 +59,24 @@ import { serializeShapesForSync, shapeDepth, shapeWidth, + withHoleMode, workplaneShapesEqual, } from "@/lib/workplaneShapes"; import { bakeCadMetadataForShapeTransform, cadBrepTransformForShape, cadModifierPrimitiveForAnalyticBox, cadModifierPrimitiveForBakedShape } from "@/lib/cadBakeMetadata"; +import { hasOneToOneCadComponentMapping } from "@/lib/cadModifierGroups"; +import { + CAD_MODIFIER_REQUEST_TIMEOUT_MS, + cadModifierTimeoutMessage, + cadModifierWorkerFailureMessage, + type CadModifierRequestPhase, +} from "@/lib/cadModifierRuntime"; +import { cloneWorkplaneShapeSnapshot, restoreShapeBeforeEdgeTreatment } from "@/lib/edgeTreatmentHistory"; +import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap"; import { createLocalId } from "@/lib/localIds"; import { projectExportFileName } from "@/lib/exportNames"; import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog"; import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"; +import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport"; import { normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; import { SKETCHFORGE_MCP_POLL_MS, @@ -179,7 +189,6 @@ const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02; const NORMAL_SELECTION_CAD_EDGE_MIN_ANGLE = 60; const MIN_EDGE_MODIFIER_AMOUNT = 0.001; const SEPARATE_PARTS_VERTEX_TOLERANCE = 0.0005; -const svgLoader = new SVGLoader(); const booleanFontLoader = new FontLoader(); const booleanTextFonts: Record = { Multilanguage: booleanFontLoader.parse(helvetikerBoldFontJson as FontData), @@ -1074,16 +1083,6 @@ function makeBlockPerfScene(count = 500): WorkplaneShape[] { }); } -function withHoleMode(shape: WorkplaneShape, hole: boolean, parentColor?: string): WorkplaneShape { - const color = hole ? "#b8c2cc" : (parentColor ?? fallbackSolidColor(shape)); - return { - ...shape, - hole, - color, - groupedShapes: shape.groupedShapes?.map((child) => withHoleMode(child, hole)), - }; -} - function sanitizeName(name: string) { return name.replace(/[^a-z0-9_-]+/gi, "_") || "shape"; } @@ -1275,10 +1274,6 @@ function cadModifierComponentPreviews(sourceParts: WorkplaneShape[], components: return previews; } -function cloneWorkplaneShapeSnapshot(shape: WorkplaneShape): WorkplaneShape { - return JSON.parse(JSON.stringify(canonicalizeShape(shape))) as WorkplaneShape; -} - function edgeTreatmentLabel(feature: NonNullable[number]) { const size = `${Number(feature.amount.toFixed(2))} mm`; return `${feature.kind === "fillet" ? "fillet" : "chamfer"} (${size}, ${feature.edgeCount} edge${feature.edgeCount === 1 ? "" : "s"})`; @@ -1357,7 +1352,10 @@ function groupedShapeWithComponentEdgeTreatment( feature: NonNullable[number], createdAt: number, ) { - if (!base.groupedShapes?.length || sourceParts.length < 2 || session.componentPreviews.length === 0) { + if ( + !base.groupedShapes?.length || + !hasOneToOneCadComponentMapping(sourceParts.length, session.componentPreviews.map((component) => component.owner)) + ) { return null; } @@ -1373,6 +1371,9 @@ function groupedShapeWithComponentEdgeTreatment( } const ownerToSourceIndex = matchCadComponentsToSources(sourceParts, session.componentPreviews); + if (ownerToSourceIndex.size !== sourceParts.length) { + return null; + } const componentByOwner = new Map(session.componentPreviews.map((component) => [component.owner, component])); const updatedSources = [...sourceParts]; let changed = false; @@ -1443,29 +1444,7 @@ function edgeTreatmentHistoryOptions(shape: WorkplaneShape, path: number[] = [], } function restoreOwnLastEdgeTreatment(shape: WorkplaneShape, entry: NonNullable[number]) { - const before = cloneWorkplaneShapeSnapshot(entry.before); - return canonicalizeShape({ - ...before, - id: shape.id, - name: shape.name, - color: shape.color, - hole: shape.hole || undefined, - x: shape.x, - z: shape.z, - elevation: shape.elevation, - width: shapeWidth(shape), - depth: shapeDepth(shape), - height: shape.height, - size: shape.size, - rotation: shape.rotation, - rotationX: shape.rotationX, - rotationZ: shape.rotationZ, - mirrorX: shape.mirrorX, - mirrorY: shape.mirrorY, - mirrorZ: shape.mirrorZ, - locked: shape.locked, - hidden: shape.hidden, - }); + return restoreShapeBeforeEdgeTreatment(shape, entry); } async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[], entryId: string): Promise<{ shape: WorkplaneShape; label: string } | null> { @@ -2099,98 +2078,6 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape { }; } -function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape { - const parsed = svgLoader.parse(source); - const rawPositions: number[] = []; - const rawNormals: number[] = []; - - parsed.paths.forEach((path) => { - SVGLoader.createShapes(path).forEach((svgShape) => { - const rawGeometry = new THREE.ExtrudeGeometry(svgShape, { - depth: 4, - bevelEnabled: false, - curveSegments: 16, - steps: 1, - }); - rawGeometry.rotateX(-Math.PI / 2); - const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry; - geometry.computeVertexNormals(); - const position = geometry.getAttribute("position"); - const normal = geometry.getAttribute("normal"); - for (let i = 0; i < position.count; i += 1) { - rawPositions.push(position.getX(i), position.getY(i), position.getZ(i)); - if (normal) { - rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i)); - } - } - if (geometry !== rawGeometry) geometry.dispose(); - rawGeometry.dispose(); - }); - }); - - if (rawPositions.length < 9) { - throw new Error("SVG has no readable filled paths"); - } - - let minX = Number.POSITIVE_INFINITY; - let minY = Number.POSITIVE_INFINITY; - let minZ = Number.POSITIVE_INFINITY; - let maxX = Number.NEGATIVE_INFINITY; - let maxY = Number.NEGATIVE_INFINITY; - let maxZ = Number.NEGATIVE_INFINITY; - - for (let i = 0; i < rawPositions.length; i += 3) { - minX = Math.min(minX, rawPositions[i]); - minY = Math.min(minY, rawPositions[i + 1]); - minZ = Math.min(minZ, rawPositions[i + 2]); - maxX = Math.max(maxX, rawPositions[i]); - maxY = Math.max(maxY, rawPositions[i + 1]); - maxZ = Math.max(maxZ, rawPositions[i + 2]); - } - - const centerX = (minX + maxX) / 2; - const centerZ = (minZ + maxZ) / 2; - const width = Math.max(1, maxX - minX); - const height = Math.max(1, maxY - minY); - const depth = Math.max(1, maxZ - minZ); - const positions: number[] = []; - const normals: number[] = []; - - for (let i = 0; i < rawPositions.length; i += 3) { - positions.push(rawPositions[i] - centerX, rawPositions[i + 1] - minY, rawPositions[i + 2] - centerZ); - if (rawNormals.length === rawPositions.length) { - normals.push(rawNormals[i], rawNormals[i + 1], rawNormals[i + 2]); - } - } - - return { - id: createLocalId("uploaded-svg"), - name: fileName.replace(/\.[^.]+$/, "") || "Imported SVG", - kind: "mesh", - color: "#0098c7", - x: 10, - z: -10, - size: Math.max(width, depth), - width, - depth, - height, - rotation: 0, - rotationX: 0, - rotationZ: 0, - importedMesh: { - positions, - normals: normals.length ? normals : undefined, - baseWidth: width, - baseDepth: depth, - baseHeight: height, - triangleCount: Math.floor(positions.length / 9), - sourceFormat: "svg", - }, - locked: false, - hidden: false, - }; -} - function readFileAsDataUrl(file: File) { return new Promise((resolve, reject) => { const reader = new FileReader(); @@ -5193,14 +5080,86 @@ export function SketchForgeEditor({ const cadModifierBaseShapeRef = useRef(null); const cadModifierBaseFingerprintRef = useRef(""); const cadModifierSourcePartsRef = useRef([]); + const cadModifierWatchdogRef = useRef<{ requestId: number; phase: CadModifierRequestPhase; timer: number } | null>(null); + const cadModifierWorkerRestartRef = useRef<() => Worker | null>(() => null); const lastMcpErrorRef = useRef(null); const executeMcpCommandRef = useRef<((command: SketchForgeMcpCommand) => Promise) | null>(null); + const clearCadModifierWatchdog = useCallback((requestId?: number) => { + const active = cadModifierWatchdogRef.current; + if (!active || (requestId !== undefined && active.requestId !== requestId)) return; + window.clearTimeout(active.timer); + cadModifierWatchdogRef.current = null; + }, []); + + const armCadModifierWatchdog = useCallback((requestId: number, phase: CadModifierRequestPhase) => { + clearCadModifierWatchdog(); + const timer = window.setTimeout(() => { + const active = cadModifierWatchdogRef.current; + if (!active || active.requestId !== requestId) return; + cadModifierWatchdogRef.current = null; + cadModifierWorkerRef.current?.terminate(); + cadModifierWorkerRef.current = null; + cadModifierWorkerRestartRef.current(); + const message = cadModifierTimeoutMessage(phase); + setEdgeModifier((current) => current ? { + ...current, + busy: false, + prepared: false, + preview: null, + error: message, + } : current); + setNotice(message); + }, CAD_MODIFIER_REQUEST_TIMEOUT_MS); + cadModifierWatchdogRef.current = { requestId, phase, timer }; + }, [clearCadModifierWatchdog]); + useEffect(() => { - const worker = new Worker(new URL("../workers/cadModifier.worker.ts", import.meta.url), { type: "module" }); - cadModifierWorkerRef.current = worker; - worker.onmessage = (event: MessageEvent) => { + let disposed = false; + const rejectPendingRequests = (message: string) => { + cadModifierPendingRef.current.forEach((pending) => { + window.clearTimeout(pending.timer); + pending.reject(new Error(message)); + }); + cadModifierPendingRef.current.clear(); + }; + const reportWorkerFailure = (worker: Worker | null) => { + if (worker && cadModifierWorkerRef.current !== worker) return; + clearCadModifierWatchdog(); + worker?.terminate(); + cadModifierWorkerRef.current = null; + rejectPendingRequests("The CAD worker could not start"); + const requestId = cadModifierRequestRef.current + 1; + cadModifierRequestRef.current = requestId; + cadModifierPrepareRef.current = requestId; + cadModifierLatestPreviewRef.current = requestId; + if (cadModifierBaseShapeRef.current) { + const message = cadModifierWorkerFailureMessage(); + setEdgeModifier((current) => current ? { ...current, busy: false, prepared: false, preview: null, error: message } : current); + setNotice(message); + } + }; + const createWorker = () => { + if (disposed) return null; + cadModifierWorkerRef.current?.terminate(); + try { + const worker = new Worker(new URL("../workers/cadModifier.worker.ts", import.meta.url), { type: "module" }); + cadModifierWorkerRef.current = worker; + worker.onmessage = handleWorkerMessage; + worker.onerror = (event) => { + event.preventDefault(); + reportWorkerFailure(worker); + }; + worker.onmessageerror = () => reportWorkerFailure(worker); + return worker; + } catch { + reportWorkerFailure(null); + return null; + } + }; + function handleWorkerMessage(event: MessageEvent) { const message = event.data; + clearCadModifierWatchdog(message.requestId); const pending = cadModifierPendingRef.current.get(message.requestId); if (pending) { window.clearTimeout(pending.timer); @@ -5263,24 +5222,23 @@ export function SketchForgeEditor({ setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: message.message } : current); setNotice("Edge treatment needs adjustment"); } - }; - worker.onerror = () => { - setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: "The CAD worker could not start" } : current); - }; + } + cadModifierWorkerRestartRef.current = createWorker; + createWorker(); return () => { - cadModifierPendingRef.current.forEach((pending) => { - window.clearTimeout(pending.timer); - pending.reject(new Error("The CAD worker was closed")); - }); - cadModifierPendingRef.current.clear(); - worker.terminate(); + disposed = true; + clearCadModifierWatchdog(); + cadModifierWorkerRestartRef.current = () => null; + rejectPendingRequests("The CAD worker was closed"); + cadModifierWorkerRef.current?.terminate(); cadModifierWorkerRef.current = null; }; - }, []); + }, [clearCadModifierWatchdog]); const invalidateCadModifierSession = useCallback(() => { const wasActive = cadModifierBaseShapeRef.current !== null; if (!wasActive) return false; + clearCadModifierWatchdog(); const requestId = cadModifierRequestRef.current + 1; cadModifierRequestRef.current = requestId; cadModifierLatestPreviewRef.current = requestId; @@ -5291,7 +5249,7 @@ export function SketchForgeEditor({ cadModifierSourcePartsRef.current = []; setEdgeModifier(null); return true; - }, []); + }, [clearCadModifierWatchdog]); useEffect(() => { const warmBooleanRuntime = () => { @@ -6344,14 +6302,22 @@ export function SketchForgeEditor({ }, []); const postCadModifierRequest = useCallback((request: CadModifierWorkerPayload, transfer: Transferable[] = []) => { + const worker = cadModifierWorkerRef.current ?? cadModifierWorkerRestartRef.current(); + if (!worker) return null; const requestId = cadModifierRequestRef.current + 1; cadModifierRequestRef.current = requestId; - cadModifierWorkerRef.current?.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer); + try { + worker.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer); + } catch { + worker.terminate(); + if (cadModifierWorkerRef.current === worker) cadModifierWorkerRef.current = null; + return null; + } return requestId; }, []); const postCadModifierRequestAsync = useCallback((request: CadModifierWorkerPayload, transfer: Transferable[] = [], timeoutMs = 20000) => { - const worker = cadModifierWorkerRef.current; + const worker = cadModifierWorkerRef.current ?? cadModifierWorkerRestartRef.current(); if (!worker) { return Promise.reject(new Error("The CAD worker is not ready")); } @@ -6363,7 +6329,13 @@ export function SketchForgeEditor({ reject(new Error("Timed out waiting for the CAD worker")); }, timeoutMs); cadModifierPendingRef.current.set(requestId, { resolve, reject, timer }); - worker.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer); + try { + worker.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer); + } catch (error) { + window.clearTimeout(timer); + cadModifierPendingRef.current.delete(requestId); + reject(error instanceof Error ? error : new Error("The CAD worker rejected the request")); + } }); }, []); @@ -6430,13 +6402,21 @@ export function SketchForgeEditor({ if (part.primitive) return { primitive: part.primitive, hole: Boolean(part.shape.hole) }; return { ...meshDataToCadTransfer(part.mesh as MeshData), hole: Boolean(part.shape.hole) }; }); - cadModifierPrepareRef.current = postCadModifierRequest({ + const prepareRequestId = postCadModifierRequest({ type: "prepare", parts, sharpAngle: 25, suppressTreatmentDetailEdges: appliedEdgeTreatmentCount > 0, }, parts.flatMap((part) => part.positions && part.indices ? [part.positions.buffer, part.indices.buffer] : [])); - }, [postCadModifierRequest, selectedShape, selectedShapes.length]); + if (prepareRequestId === null) { + const message = cadModifierWorkerFailureMessage(); + setEdgeModifier((current) => current ? { ...current, busy: false, prepared: false, error: message } : current); + setNotice(message); + return; + } + cadModifierPrepareRef.current = prepareRequestId; + armCadModifierWatchdog(prepareRequestId, "prepare"); + }, [armCadModifierWatchdog, postCadModifierRequest, selectedShape, selectedShapes.length]); const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => { if (shape.locked || shape.hole) { @@ -6632,8 +6612,6 @@ export function SketchForgeEditor({ useEffect(() => { if (!edgeModifier?.prepared || edgeModifier.selectedEdgeIds.length === 0) return; - const worker = cadModifierWorkerRef.current; - if (!worker) return; const timer = window.setTimeout(() => { const requestId = postCadModifierRequest({ type: "preview", @@ -6643,11 +6621,18 @@ export function SketchForgeEditor({ quality: edgeModifier.quality, chamferAngle: edgeModifier.chamferAngle, }); + if (requestId === null) { + const message = cadModifierWorkerFailureMessage(); + setEdgeModifier((current) => current ? { ...current, busy: false, prepared: false, preview: null, error: message } : current); + setNotice(message); + return; + } cadModifierLatestPreviewRef.current = requestId; + armCadModifierWatchdog(requestId, "preview"); setEdgeModifier((current) => current ? { ...current, busy: true, error: null } : current); }, 120); return () => window.clearTimeout(timer); - }, [edgeModifier?.amount, edgeModifier?.chamferAngle, edgeModifier?.kind, edgeModifier?.prepared, edgeModifier?.quality, edgeModifier?.selectedEdgeIds, postCadModifierRequest]); + }, [armCadModifierWatchdog, edgeModifier?.amount, edgeModifier?.chamferAngle, edgeModifier?.kind, edgeModifier?.prepared, edgeModifier?.quality, edgeModifier?.selectedEdgeIds, postCadModifierRequest]); const snapSelected = useCallback(() => { if (!hasSelection) { @@ -6655,27 +6640,17 @@ export function SketchForgeEditor({ return; } const selected = new Set(selectedIds); - const grid = 1; - const snapValue = (value: number) => Math.round(value / grid) * grid; + const grid = visibleGridStep(workspaceSettings); commitShapes( shapes.map((shape) => selected.has(shape.id) && !shape.locked - ? { - ...shape, - x: snapValue(shape.x), - z: snapValue(shape.z), - elevation: snapValue(shape.elevation ?? 0), - width: Math.max(grid, snapValue(shape.width)), - depth: Math.max(grid, snapValue(shape.depth)), - height: Math.max(grid, snapValue(shape.height)), - size: Math.max(grid, snapValue(shape.size)), - } + ? snapShapeFootprintToVisibleGrid(shape, meshAabb(shape), workspaceSettings) : shape, ), selectedIds, - `Snapped ${selectedShapes.length} shape${selectedShapes.length === 1 ? "" : "s"} to 1 mm grid`, + `Snapped ${selectedShapes.length} shape${selectedShapes.length === 1 ? "" : "s"} to ${grid} mm visible grid`, ); - }, [commitShapes, hasSelection, selectedIds, selectedShapes.length, shapes]); + }, [commitShapes, hasSelection, selectedIds, selectedShapes.length, shapes, workspaceSettings]); const toggleHidden = useCallback(() => { if (!hasSelection) { @@ -7460,6 +7435,11 @@ export function SketchForgeEditor({ setNotice(hasSelection ? "Select at least one solid shape before exporting" : "Add a solid shape before exporting"); return; } + const invalidSvg = exportable.map(invalidSvgMeshReason).find((reason): reason is string => Boolean(reason)); + if (invalidSvg) { + setNotice(`${invalidSvg}. Re-import the source SVG after fixing its contours`); + return; + } const meshes = exportable.map(meshForShape); const selectedNotice = `Exported ${exportable.length} selected shape${exportable.length === 1 ? "" : "s"}`; const finishNotice = (label: string, result: DownloadResult) => { @@ -8002,12 +7982,13 @@ export function SketchForgeEditor({ selectedCount={edgeModifier.selectedEdgeIds.length} availableCount={modifierAvailableEdgeIds.length} busy={edgeModifier.busy} + prepared={edgeModifier.prepared} error={edgeModifier.error} - onAmountChange={(value) => setEdgeModifier((current) => current ? { ...current, amount: Math.max(MIN_EDGE_MODIFIER_AMOUNT, Math.min(edgeModifierMaxAmount, value)), preview: null, busy: true, error: null } : current)} - onChamferAngleChange={(value) => setEdgeModifier((current) => current ? { ...current, chamferAngle: Math.max(5, Math.min(85, value)), preview: null, busy: true, error: null } : current)} - onQualityChange={(quality) => setEdgeModifier((current) => current ? { ...current, quality, preview: null, busy: true, error: null } : current)} + onAmountChange={(value) => setEdgeModifier((current) => current?.prepared ? { ...current, amount: Math.max(MIN_EDGE_MODIFIER_AMOUNT, Math.min(edgeModifierMaxAmount, value)), preview: null, busy: true, error: null } : current)} + onChamferAngleChange={(value) => setEdgeModifier((current) => current?.prepared ? { ...current, chamferAngle: Math.max(5, Math.min(85, value)), preview: null, busy: true, error: null } : current)} + onQualityChange={(quality) => setEdgeModifier((current) => current?.prepared ? { ...current, quality, preview: null, busy: true, error: null } : current)} onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => { - if (!current) return current; + if (!current?.prepared) return current; const nextAngle = Math.max(1, Math.min(120, sharpAngle)); const availableIds = new Set(current.edges .filter((edge) => selectableCadModifierEdge(edge, nextAngle)) @@ -8022,10 +8003,10 @@ export function SketchForgeEditor({ error: availableIds.size === 0 ? "No sharp edges match this threshold" : selectedEdgeIds.length ? null : "Select at least one highlighted edge", }; })} - onTangentChainChange={(tangentChain) => setEdgeModifier((current) => current ? { ...current, tangentChain } : current)} - onPreserveEdgeSizeChange={(preserveEdgeSize) => setEdgeModifier((current) => current ? { ...current, preserveEdgeSize } : current)} - onSelectAll={() => setEdgeModifier((current) => current ? { ...current, selectedEdgeIds: modifierAvailableEdgeIds, preview: null, busy: modifierAvailableEdgeIds.length > 0, error: modifierAvailableEdgeIds.length ? null : current.error } : current)} - onClear={() => setEdgeModifier((current) => current ? { ...current, selectedEdgeIds: [], preview: null, busy: false, error: "Select at least one highlighted edge" } : current)} + onTangentChainChange={(tangentChain) => setEdgeModifier((current) => current?.prepared ? { ...current, tangentChain } : current)} + onPreserveEdgeSizeChange={(preserveEdgeSize) => setEdgeModifier((current) => current?.prepared ? { ...current, preserveEdgeSize } : current)} + onSelectAll={() => setEdgeModifier((current) => current?.prepared ? { ...current, selectedEdgeIds: modifierAvailableEdgeIds, preview: null, busy: modifierAvailableEdgeIds.length > 0, error: modifierAvailableEdgeIds.length ? null : current.error } : current)} + onClear={() => setEdgeModifier((current) => current?.prepared ? { ...current, selectedEdgeIds: [], preview: null, busy: false, error: "Select at least one highlighted edge" } : current)} onRemoveFeature={removeEdgeTreatment} onApply={applyEdgeModifier} onCancel={cancelEdgeModifier} @@ -8390,7 +8371,7 @@ function SecondaryToolbar({
-
Output
+
Manage
- - - +
+ {cameraControlsCollapsed ? ( + + ) : ( + <> + + + + +
+ + {rulerToolsOpen ? ( +
+ + +
+ ) : null} +
+ + )}
-
+
@@ -3221,6 +3299,9 @@ function rebuildWorkplane(state: ThreeState | null, workspace: WorkspaceSettings opacity: 0.68, roughness: 0.92, side: THREE.FrontSide, + polygonOffset: true, + polygonOffsetFactor: 1, + polygonOffsetUnits: 1, }), ); base.name = "WorkplaneBase"; @@ -3235,9 +3316,10 @@ function rebuildWorkplane(state: ThreeState | null, workspace: WorkspaceSettings function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, blockSize = DEFAULT_WORKSPACE.gridBlockSize) { const group = new THREE.Group(); - const minor = new THREE.LineBasicMaterial({ color: "#91dff0", transparent: true, opacity: 0.55 }); - const major = new THREE.LineBasicMaterial({ color: "#4bbddf", transparent: true, opacity: 0.7 }); - const axis = new THREE.LineBasicMaterial({ color: "#34aad2", transparent: true, opacity: 0.88 }); + const palette = workplaneGridPalette(); + const minor = new THREE.LineBasicMaterial({ ...palette.minor, transparent: true, depthWrite: false }); + const major = new THREE.LineBasicMaterial({ ...palette.major, transparent: true, depthWrite: false }); + const axis = new THREE.LineBasicMaterial({ ...palette.axis, transparent: true, depthWrite: false }); const minorPoints: number[] = []; const majorPoints: number[] = []; const axisPoints: number[] = []; @@ -3247,28 +3329,21 @@ function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, block }; const step = clamp(blockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE); const majorEvery = 4; - const xCount = Math.floor(width / step); - const zCount = Math.floor(depth / step); - - for (let index = 0; index <= xCount; index += 1) { - const x = -width / 2 + index * step; - const centeredX = Math.abs(x) < 0.0001 ? 0 : x; + for (const { coordinate: centeredX, index } of interiorWorkplaneGridCoordinates(width, step)) { const points = centeredX === 0 ? axisPoints : index % majorEvery === 0 ? majorPoints : minorPoints; - pushLine(points, [centeredX, 0.04, -depth / 2], [centeredX, 0.04, depth / 2]); + pushLine(points, [centeredX, WORKPLANE_LINE_ELEVATION, -depth / 2], [centeredX, WORKPLANE_LINE_ELEVATION, depth / 2]); } - for (let index = 0; index <= zCount; index += 1) { - const z = -depth / 2 + index * step; - const centeredZ = Math.abs(z) < 0.0001 ? 0 : z; + for (const { coordinate: centeredZ, index } of interiorWorkplaneGridCoordinates(depth, step)) { const points = centeredZ === 0 ? axisPoints : index % majorEvery === 0 ? majorPoints : minorPoints; - pushLine(points, [-width / 2, 0.04, centeredZ], [width / 2, 0.04, centeredZ]); + pushLine(points, [-width / 2, WORKPLANE_LINE_ELEVATION, centeredZ], [width / 2, WORKPLANE_LINE_ELEVATION, centeredZ]); } - const border = new THREE.LineBasicMaterial({ color: "#58c5e6", transparent: true, opacity: 0.9 }); - pushLine(borderPoints, [-width / 2, 0.08, -depth / 2], [width / 2, 0.08, -depth / 2]); - pushLine(borderPoints, [width / 2, 0.08, -depth / 2], [width / 2, 0.08, depth / 2]); - pushLine(borderPoints, [width / 2, 0.08, depth / 2], [-width / 2, 0.08, depth / 2]); - pushLine(borderPoints, [-width / 2, 0.08, depth / 2], [-width / 2, 0.08, -depth / 2]); + const border = new THREE.LineBasicMaterial({ ...palette.border, transparent: true, depthWrite: false }); + pushLine(borderPoints, [-width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2], [width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2]); + pushLine(borderPoints, [width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2], [width / 2, WORKPLANE_LINE_ELEVATION, depth / 2]); + pushLine(borderPoints, [width / 2, WORKPLANE_LINE_ELEVATION, depth / 2], [-width / 2, WORKPLANE_LINE_ELEVATION, depth / 2]); + pushLine(borderPoints, [-width / 2, WORKPLANE_LINE_ELEVATION, depth / 2], [-width / 2, WORKPLANE_LINE_ELEVATION, -depth / 2]); group.add(linesFromPoints(minorPoints, minor)); group.add(linesFromPoints(majorPoints, major)); @@ -3281,7 +3356,9 @@ function createGridLines(width = WORKPLANE_WIDTH, depth = WORKPLANE_DEPTH, block function linesFromPoints(points: number[], material: THREE.LineBasicMaterial) { const geometry = new THREE.BufferGeometry(); geometry.setAttribute("position", new THREE.Float32BufferAttribute(points, 3)); - return new THREE.LineSegments(geometry, material); + const lines = new THREE.LineSegments(geometry, material); + lines.renderOrder = 1; + return lines; } type CutPreviewShapeFrame = { @@ -4437,7 +4514,7 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1, roughness: shape.hole ? 0.88 : 0.57, metalness: 0.02, - side: shape.importedMesh?.sourceFormat === "json" || shape.importedMesh?.sourceFormat === "svg" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, + side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide, }); const width = shapeWidth(shape); 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/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 815f811..05369f9 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 3cc64ac..f167b6b 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -13,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 1fb6648..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", @@ -29,8 +30,7 @@ "@types/react-dom": "^19.1.5", "typescript": "^5.8.3", "vitest": "^4.1.8" - }, - "license": "MIT" + } }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", diff --git a/package.json b/package.json index 2f7535c..e593d15 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sketchforge", - "version": "0.5.0", + "version": "0.6.0", "private": true, "license": "MIT", "scripts": { @@ -9,7 +9,8 @@ "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/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",