diff --git a/README.md b/README.md index 68aeb08..e57e460 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,11 @@ MIT license GitHub stars Local first - Version 0.2.0 + Version 0.5.0

-![SketchForge v0.2 editor showing a selected box on the workplane](docs/media/sketchforge-editor-v0.2.png) +![SketchForge editor showing a selected box on the workplane](docs/media/sketchforge-editor-v0.5.png) ## Why SketchForge @@ -39,8 +39,10 @@ No login. No server project storage. No heavyweight CAD install just to make a u - **Primitive shape library** - boxes, cylinders, spheres, cones, pyramids, wedges, text, roofs, half spheres, torus shapes, tubes, and more. - **Solid and hole workflow** - turn shapes into cutters and group them into final geometry. - **Boolean Intersection** - keep only the geometry where selected solid and hole shapes overlap. +- **Reversible edge tools** - chamfer and fillet selected CAD edges, with history controls for removing applied edge features. +- **Rotated solid edge treatment** - chamfer and fillet preserve analytic box topology after one-, two-, or three-axis rotations. - **STL import** - bring outside models into the same workspace as primitives. -- **STL and OBJ export** - export selected objects or the whole scene. +- **STL, OBJ, and STEP workflows** - export selected objects or the whole scene, and round-trip exact STEP/B-Rep geometry. - **Fast browser stack** - Next.js, React, TypeScript, Three.js, and Manifold/CSG geometry tooling. ## Demo @@ -238,6 +240,12 @@ Run tests: npm run test ``` +Start the local SketchForge MCP bridge for editor automation: + +```bash +npm run mcp:sketchforge +``` + Create a production build: ```bash @@ -309,6 +317,7 @@ 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 deploy/docker/ Docker, Compose, and Nginx deployment files .github/ Issue templates and community files @@ -322,7 +331,9 @@ SketchForge is alpha, but the core editor loop is usable today: - 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 diff --git a/apps/web/public/assets/sketchforge/sketch-tool-add-image.png b/apps/web/public/assets/sketchforge/sketch-tool-add-image.png new file mode 100644 index 0000000..9a1b2fc Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-add-image.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-add-or-remove-points.png b/apps/web/public/assets/sketchforge/sketch-tool-add-or-remove-points.png new file mode 100644 index 0000000..15cdd79 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-add-or-remove-points.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-bezier-curve.png b/apps/web/public/assets/sketchforge/sketch-tool-bezier-curve.png new file mode 100644 index 0000000..70150b9 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-bezier-curve.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-edit-sketch-to-3d.png b/apps/web/public/assets/sketchforge/sketch-tool-edit-sketch-to-3d.png new file mode 100644 index 0000000..03d7b81 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-edit-sketch-to-3d.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-erase.png b/apps/web/public/assets/sketchforge/sketch-tool-erase.png new file mode 100644 index 0000000..1f7f2ac Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-erase.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-line.png b/apps/web/public/assets/sketchforge/sketch-tool-line.png new file mode 100644 index 0000000..0d12a2b Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-line.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-measure.png b/apps/web/public/assets/sketchforge/sketch-tool-measure.png new file mode 100644 index 0000000..72b6319 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-measure.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-select.png b/apps/web/public/assets/sketchforge/sketch-tool-select.png new file mode 100644 index 0000000..f72f448 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-select.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-sketch-to-3d.png b/apps/web/public/assets/sketchforge/sketch-tool-sketch-to-3d.png new file mode 100644 index 0000000..62c905b Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-sketch-to-3d.png differ diff --git a/apps/web/public/assets/sketchforge/sketch-tool-smooth-curve.png b/apps/web/public/assets/sketchforge/sketch-tool-smooth-curve.png new file mode 100644 index 0000000..672d4b0 Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketch-tool-smooth-curve.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-chamfer.png b/apps/web/public/assets/sketchforge/toolbar-chamfer.png new file mode 100644 index 0000000..8fdc68a Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-chamfer.png differ diff --git a/apps/web/public/assets/sketchforge/toolbar-fillet.png b/apps/web/public/assets/sketchforge/toolbar-fillet.png new file mode 100644 index 0000000..d3fa562 Binary files /dev/null and b/apps/web/public/assets/sketchforge/toolbar-fillet.png differ diff --git a/apps/web/src/app/api/sketchforge-mcp/route.ts b/apps/web/src/app/api/sketchforge-mcp/route.ts new file mode 100644 index 0000000..b7ae34e --- /dev/null +++ b/apps/web/src/app/api/sketchforge-mcp/route.ts @@ -0,0 +1,110 @@ +import { NextResponse } from "next/server"; +import type { SketchForgeMcpApiPayload } from "@/lib/sketchforgeMcpProtocol"; +import { + completeSketchForgeMcpCommand, + dispatchSketchForgeMcpCommand, + listSketchForgeMcpEditors, + pollSketchForgeMcpCommand, + registerSketchForgeMcpEditor, +} from "@/lib/sketchforgeMcpStore"; + +export const dynamic = "force-dynamic"; +export const revalidate = false; + +const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]); + +function isLocalRequest(request: Request) { + const requestUrl = new URL(request.url); + if (!LOCAL_HOSTS.has(requestUrl.hostname)) { + return false; + } + + const origin = request.headers.get("origin"); + if (origin) { + try { + const originUrl = new URL(origin); + if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) { + return false; + } + } catch { + return false; + } + } + + const fetchSite = request.headers.get("sec-fetch-site"); + return !fetchSite || fetchSite === "same-origin" || fetchSite === "none"; +} + +function localOnly(request: Request) { + if (process.env.NODE_ENV === "production") { + return NextResponse.json({ error: "SketchForge MCP is only available in local development." }, { status: 404 }); + } + if (!isLocalRequest(request)) { + return NextResponse.json({ error: "SketchForge MCP only accepts localhost requests." }, { status: 403 }); + } + return null; +} + +function isObject(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +export async function GET(request: Request) { + const blocked = localOnly(request); + if (blocked) return blocked; + return NextResponse.json({ editors: listSketchForgeMcpEditors() }); +} + +export async function POST(request: Request) { + const blocked = localOnly(request); + if (blocked) return blocked; + + let body: SketchForgeMcpApiPayload; + try { + body = (await request.json()) as SketchForgeMcpApiPayload; + } catch { + return NextResponse.json({ error: "Invalid SketchForge MCP request." }, { status: 400 }); + } + + if (!isObject(body) || typeof body.type !== "string") { + return NextResponse.json({ error: "Invalid SketchForge MCP request." }, { status: 400 }); + } + + if (body.type === "heartbeat") { + if (!isObject(body.editor)) { + return NextResponse.json({ error: "Invalid editor heartbeat." }, { status: 400 }); + } + registerSketchForgeMcpEditor(body.editor); + return NextResponse.json({ ok: true, editors: listSketchForgeMcpEditors() }); + } + + if (body.type === "poll") { + if (typeof body.editorId !== "string") { + return NextResponse.json({ error: "Invalid editor poll." }, { status: 400 }); + } + return NextResponse.json({ command: pollSketchForgeMcpCommand(body.editorId) }); + } + + if (body.type === "result") { + if (typeof body.editorId !== "string" || !isObject(body.result) || typeof body.result.commandId !== "string" || typeof body.result.ok !== "boolean") { + return NextResponse.json({ error: "Invalid command result." }, { status: 400 }); + } + return NextResponse.json({ ok: completeSketchForgeMcpCommand(body.editorId, body.result) }); + } + + if (body.type === "command") { + if (typeof body.action !== "string") { + return NextResponse.json({ error: "Invalid command action." }, { status: 400 }); + } + const result = await dispatchSketchForgeMcpCommand({ + editorId: typeof body.editorId === "string" ? body.editorId : undefined, + editorNumber: typeof body.editorNumber === "number" ? body.editorNumber : undefined, + action: body.action, + params: isObject(body.params) ? body.params : {}, + timeoutMs: typeof body.timeoutMs === "number" ? body.timeoutMs : undefined, + }); + return NextResponse.json(result, { status: result.ok ? 200 : 504 }); + } + + return NextResponse.json({ error: "Unknown SketchForge MCP request." }, { status: 400 }); +} diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index e84b4fc..492aa81 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -182,10 +182,11 @@ button { .dashboard-nav-item { display: flex; width: 100%; + min-width: 0; height: 42px; align-items: center; - gap: 10px; - padding: 0 12px; + gap: 8px; + padding: 0 8px; color: #40586f; background: transparent; border-radius: 6px; @@ -208,6 +209,14 @@ button { background: #e8f6fc; } +.dashboard-nav-item:focus { + outline: 0; +} + +.dashboard-nav-item:focus-visible { + box-shadow: inset 0 0 0 2px #52bfe9; +} + .dashboard-settings-button { color: #536a80; } @@ -231,6 +240,20 @@ button { font-weight: 800; } +.dashboard-coming-soon { + display: grid; + min-height: calc(100vh - 64px - 44px); + place-items: center; + color: #173a56; +} + +.dashboard-coming-soon strong { + font-size: clamp(42px, 7vw, 96px); + font-weight: 900; + line-height: 1; + text-align: center; +} + .dashboard-action-tile { display: flex; min-width: 0; @@ -989,7 +1012,6 @@ button { } .edge-modifier-header, -.edge-modifier-value-row, .edge-modifier-quick-actions, .edge-modifier-footer, .edge-modifier-check { @@ -1110,6 +1132,18 @@ button { cursor: pointer; } +.edge-modifier-history-toggle, +.edge-modifier-history-item { + display: flex; + align-items: center; + gap: 7px; + text-align: left; +} + +.edge-modifier-history-toggle { + justify-content: center; +} + .edge-modifier-history-actions button:disabled { color: #9aa8b3; background: #f4f6f8; @@ -1123,6 +1157,43 @@ button { line-height: 1.35; } +.edge-modifier-history-list { + display: grid; + gap: 5px; + max-height: 170px; + overflow: auto; +} + +.edge-modifier-history-item { + justify-content: flex-start; + min-height: 42px; + padding: 6px 8px; +} + +.edge-modifier-history-item > span { + display: grid; + min-width: 0; + gap: 2px; +} + +.edge-modifier-history-item strong, +.edge-modifier-history-item small { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.edge-modifier-history-item strong { + color: #6d4310; + font-size: 11px; +} + +.edge-modifier-history-item small { + color: #7a6851; + font-size: 10px; + font-weight: 700; +} + .edge-modifier-field { display: block; margin-top: 11px; @@ -1131,18 +1202,6 @@ button { font-weight: 700; } -.edge-modifier-value-row { - gap: 7px; - margin-top: 5px; -} - -.edge-modifier-value-row input[type="range"] { - min-width: 0; - flex: 1; - accent-color: #139ed0; -} - -.edge-modifier-value-row input[type="number"], .edge-modifier-field select { height: 31px; color: #263f53; @@ -1151,11 +1210,6 @@ button { border-radius: 6px; } -.edge-modifier-value-row input[type="number"] { - width: 72px; - padding: 0 6px; -} - .edge-modifier-field select { width: 100%; margin-top: 5px; @@ -1273,6 +1327,57 @@ button { stroke-width: 1.8; } +.sketch-tool-icon .sketch-reference-icon { + width: 32px; + height: 32px; +} + +.sketch-reference-icon { + --sketch-icon-offset-y: 0; + --sketch-icon-scale: 1; + display: block; + object-fit: contain; + pointer-events: none; + user-select: none; + opacity: 0.96; + transform: + translateY(var(--sketch-icon-offset-y)) + scale(var(--sketch-icon-scale)); + transition: filter 120ms ease, opacity 120ms ease; +} + +.sketch-reference-icon[data-sketch-icon="line"], +.sketch-reference-icon[data-sketch-icon="erase"], +.sketch-reference-icon[data-sketch-icon="measure"], +.sketch-reference-icon[data-sketch-icon="select"] { + --sketch-icon-scale: 0.94; +} + +.sketch-reference-icon[data-sketch-icon="bezier"] { + --sketch-icon-scale: 1.12; +} + +.sketch-reference-icon[data-sketch-icon="smooth"] { + --sketch-icon-scale: 1.16; +} + +.sketch-reference-icon[data-sketch-icon="image"] { + --sketch-icon-scale: 1.06; +} + +.sketch-reference-icon[data-sketch-icon="refine"] { + --sketch-icon-scale: 1.12; +} + +.sketch-reference-icon[data-sketch-icon="sketchTo3d"], +.sketch-reference-icon[data-sketch-icon="editSketchTo3d"] { + --sketch-icon-scale: 1.08; +} + +.sketch-reference-icon[data-sketch-icon="sketchTo3d"] { + --sketch-icon-scale: 1.08; +} + .sketch-command-button { display: inline-flex; height: 43px; @@ -1297,6 +1402,11 @@ button { stroke-width: 1.8; } +.sketch-command-button .sketch-reference-icon { + width: 27px; + height: 27px; +} + .sketch-command-button:hover:not(:disabled) { color: #17405d; background: #e7f5fb; @@ -1317,6 +1427,25 @@ button { cursor: default; } +.toolbar-icon.disabled .sketch-reference-icon, +.toolbar-icon:disabled .sketch-reference-icon, +.sketch-command-button.disabled .sketch-reference-icon, +.sketch-command-button:disabled .sketch-reference-icon { + filter: grayscale(1) brightness(1.25); + opacity: 0.34; +} + +.toolbar-icon:not(.disabled):hover .sketch-reference-icon, +.sketch-command-button:hover:not(:disabled) .sketch-reference-icon { + filter: contrast(1.08) brightness(0.95); + opacity: 1; +} + +.toolbar-icon.active .sketch-reference-icon { + filter: contrast(1.12) brightness(0.9) drop-shadow(0 0 5px rgba(0, 156, 222, 0.28)); + opacity: 1; +} + .toolbar-workspace-tabs { position: absolute; top: 0; @@ -1509,6 +1638,12 @@ button { height: 43px; } +.toolbar-icon .toolbar-art-toolbar-chamfer, +.toolbar-icon .toolbar-art-toolbar-fillet { + width: 34px; + height: 34px; +} + .toolbar-icon.disabled .toolbar-command-icon { filter: grayscale(1) brightness(1.25); opacity: 0.22; @@ -2052,6 +2187,18 @@ button { vector-effect: non-scaling-stroke; } +.sketch-reference-shapes .sketch-reference-mesh-face { + fill: rgba(207, 142, 42, 0.22); + stroke: none; +} + +.sketch-reference-shapes .sketch-reference-mesh-outline { + fill: none; + stroke: rgba(188, 113, 18, 0.7); + stroke-width: 1.25; + vector-effect: non-scaling-stroke; +} + .sketch-reference-images image { cursor: move; image-rendering: auto; @@ -2217,6 +2364,26 @@ button { pointer-events: none; } +.sketch-measurement.pending > line { + stroke: #169fce; +} + +.sketch-measurement-point { + fill: #ffffff; + stroke: #d56100; + stroke-width: 2; + vector-effect: non-scaling-stroke; +} + +.sketch-measurement-point.pending { + stroke: #169fce; +} + +.sketch-measurement-point.hover { + fill: #169fce; + stroke: #ffffff; +} + .sketch-measurement-pill { cursor: pointer; } @@ -2590,6 +2757,11 @@ button { cursor: crosshair; } +.workplane-wrap.modifier-edge-pick .three-workplane-host, +.workplane-wrap.modifier-edge-pick .three-workplane-host:active { + cursor: crosshair; +} + .three-workplane-host canvas { display: block; width: 100%; @@ -3312,8 +3484,12 @@ button { opacity: 0.55; } -.shape-inspector .edit-sketch-button { - display: block; +.shape-inspector .edit-sketch-button, +.shape-inspector .inspector-action-button { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; width: calc(100% - 20px); height: 38px; margin: 0 10px 12px; @@ -3326,13 +3502,15 @@ button { font-weight: 900; } -.shape-inspector .edit-sketch-button:hover:not(:disabled) { +.shape-inspector .edit-sketch-button:hover:not(:disabled), +.shape-inspector .inspector-action-button:hover:not(:disabled) { color: #0d7198; background: #eaf7fb; border-color: #8ecbdf; } -.shape-inspector .edit-sketch-button:disabled { +.shape-inspector .edit-sketch-button:disabled, +.shape-inspector .inspector-action-button:disabled { opacity: 0.45; cursor: default; } @@ -3378,12 +3556,109 @@ button { .range-property { display: grid; - gap: 9px; + gap: 7px; color: #637286; font-size: 15px; font-weight: 650; } +.range-property-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-width: 0; +} + +.range-property-name { + min-width: 0; + overflow: hidden; + color: #586a7d; + text-overflow: ellipsis; + white-space: nowrap; +} + +.range-value-control { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 5px; + min-width: 88px; + min-height: 31px; + padding: 0 7px; + color: #51657a; + background: #fff; + border: 1px solid #c7d4df; + border-radius: 6px; + box-shadow: inset 0 1px 1px rgba(25, 45, 65, 0.04); +} + +.range-value-control:focus-within { + border-color: #55add8; + box-shadow: 0 0 0 3px rgba(0, 156, 222, 0.14); +} + +.range-value-control input { + width: 58px; + min-width: 0; + height: 29px; + padding: 0; + appearance: textfield; + color: #2f4457; + background: transparent; + border: 0; + outline: 0; + font: 750 14px/1 var(--font-ui); + letter-spacing: 0; + text-align: right; +} + +.range-value-control input:disabled { + cursor: default; +} + +.range-value-control input::-webkit-outer-spin-button, +.range-value-control input::-webkit-inner-spin-button { + appearance: none; + margin: 0; +} + +.range-value-unit { + color: #7b8da0; + font-size: 11px; + font-weight: 850; + line-height: 1; +} + +.edge-modifier-slider.range-property { + margin-top: 12px; + color: #415a6e; + font-size: 12px; + font-weight: 700; +} + +.edge-modifier-slider .range-property-header { + gap: 10px; +} + +.edge-modifier-slider .range-property-name { + color: #415a6e; +} + +.edge-modifier-slider .range-value-control { + min-width: 84px; + border-color: #bdcdda; +} + +.edge-modifier-slider .range-value-control input { + width: 50px; + font-size: 13px; +} + +.edge-modifier-slider .range-value-unit { + font-size: 10px; +} + .text-property { display: grid; gap: 8px; @@ -3435,42 +3710,15 @@ button { .range-control { position: relative; - height: 22px; - padding: 0 21px; -} - -.range-control output, -.range-value-input { - position: absolute; - z-index: 2; - top: -3px; - left: clamp(22px, calc(var(--slider-pos) + 7px), calc(100% - 22px)); - min-width: 31px; - height: 31px; - padding: 0 8px; - color: #617287; - font-size: 15px; - line-height: 29px; - text-align: center; - background: white; - border: 1px solid #cbd6e1; - border-radius: 999px; - transform: translateX(-50%); -} - -.range-control output { - cursor: text; -} - -.range-value-input { - width: 70px; - outline: 0; - font: 700 15px/29px var(--font-ui); + display: flex; + align-items: center; + height: 24px; + padding: 0 3px; } .range-control input[type="range"] { width: 100%; - height: 22px; + height: 24px; margin: 0; appearance: none; background: transparent; @@ -3478,30 +3726,44 @@ button { } .range-control input[type="range"]::-webkit-slider-runnable-track { - height: 4px; + height: 5px; background: linear-gradient(to right, #00a6db 0 var(--slider-pos), #dbe1e7 var(--slider-pos) 100%); border-radius: 999px; } .range-control input[type="range"]::-webkit-slider-thumb { - width: 1px; - height: 1px; + width: 17px; + height: 17px; + margin-top: -6px; appearance: none; + background: #ffffff; + border: 2px solid #00a6db; + border-radius: 999px; + box-shadow: 0 1px 4px rgba(24, 48, 68, 0.2); } .range-control input[type="range"]::-moz-range-track { - height: 4px; + height: 5px; background: #dbe1e7; border-radius: 999px; } .range-control input[type="range"]::-moz-range-progress { - height: 4px; + height: 5px; background: #00a6db; border-radius: 999px; } +.range-control input[type="range"]::-moz-range-thumb { + width: 15px; + height: 15px; + background: #ffffff; + border: 2px solid #00a6db; + border-radius: 999px; + box-shadow: 0 1px 4px rgba(24, 48, 68, 0.2); +} + .inspector-header-icon:hover, .shape-state-card button:not(:disabled):hover { background: #eef8fc; diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 6005ece..574c6aa 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -10,6 +10,7 @@ import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/typ type AppView = "dashboard" | "editor"; type ViewMode = "grid" | "list"; +type DashboardSection = "home" | "challenges"; type DownloadMode = "browser" | "folder"; type DashboardProject = { @@ -244,6 +245,7 @@ export default function Home() { const [editorStarted, setEditorStarted] = useState(false); const [activeProjectId, setActiveProjectId] = useState(null); const [projects, setProjects] = useState([]); + const [dashboardSection, setDashboardSection] = useState("home"); const [query, setQuery] = useState(""); const [viewMode, setViewMode] = useState("grid"); const [sortMode, setSortMode] = useState("recent"); @@ -550,6 +552,7 @@ export default function Home() { if (activeProjectId) { setProjects((current) => current.map((project) => (project.id === activeProjectId ? { ...project, updatedAt: Date.now() } : project))); } + setDashboardSection("home"); setView("dashboard"); if (typeof window !== "undefined") { window.history.replaceState(null, "", "/"); @@ -619,6 +622,7 @@ export default function Home() { /> {view === "dashboard" ? ( dashboardStlInputRef.current?.click()} + onChallenges={() => { + setDashboardSection("challenges"); + setDashboardNotice(""); + }} + onDashboardHome={() => setDashboardSection("home")} onOpenProject={openEditor} onOpenSettings={() => setSettingsOpen(true)} onQueryChange={setQuery} @@ -664,6 +673,7 @@ export default function Home() { } function Dashboard({ + dashboardSection, dashboardNotice, downloadFolder, downloadMode, @@ -679,6 +689,8 @@ function Dashboard({ onDownloadFolderChange, onDownloadModeChange, onImportStl, + onChallenges, + onDashboardHome, onOpenProject, onOpenSettings, onQueryChange, @@ -687,6 +699,7 @@ function Dashboard({ onViewModeChange, onWorkspace, }: { + dashboardSection: DashboardSection; dashboardNotice: string; downloadFolder: string; downloadMode: DownloadMode; @@ -702,6 +715,8 @@ function Dashboard({ onDownloadFolderChange: (value: string) => void; onDownloadModeChange: (value: DownloadMode) => void; onImportStl: () => void; + onChallenges: () => void; + onDashboardHome: () => void; onOpenProject: (projectId: string) => void; onOpenSettings: () => void; onQueryChange: (value: string) => void; @@ -766,10 +781,14 @@ function Dashboard({
-
-
- - - -
- {dashboardNotice ? ( -
- {dashboardNotice} -
- ) : null} - -
-
-

Projects

- {projects.length} visible -
-
- -
- - -
-
-
- - {projects.length > 0 ? ( -
- {projects.map((project) => ( -
- - - {openProjectMenuId === project.id ? ( -
- - -
- ) : null} -
- ))} +
+ {dashboardSection === "challenges" ? ( +
+ Coming soon
) : ( -
- No projects yet - Create a 3D design and it will appear here. -
+ <> +
+ + + +
+ {dashboardNotice ? ( +
+ {dashboardNotice} +
+ ) : null} + +
+
+

Projects

+ {projects.length} visible +
+
+ +
+ + +
+
+
+ + {projects.length > 0 ? ( +
+ {projects.map((project) => ( +
+ + + {openProjectMenuId === project.id ? ( +
+ + +
+ ) : null} +
+ ))} +
+ ) : ( +
+ No projects yet + Create a 3D design and it will appear here. +
+ )} + )}
diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index ccee6d2..bb757c5 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -1,6 +1,6 @@ "use client"; -import { Box, Check, Download, Eraser, ImagePlus, ListPlus, MousePointer2, PencilLine, Ruler, Spline, Waves, X } from "lucide-react"; +import { Check, Download, X } from "lucide-react"; import type manifoldModule from "manifold-3d"; import type { ManifoldToplevel } from "manifold-3d"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -62,11 +62,21 @@ import { shapeWidth, workplaneShapesEqual, } from "@/lib/workplaneShapes"; +import { bakeCadMetadataForShapeTransform, cadBrepTransformForShape, cadModifierPrimitiveForAnalyticBox, cadModifierPrimitiveForBakedShape } from "@/lib/cadBakeMetadata"; 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 type { CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes"; +import { normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; +import { + SKETCHFORGE_MCP_POLL_MS, + SKETCHFORGE_MCP_ROUTE, + type SketchForgeMcpCommand, + type SketchForgeMcpSceneSummary, + type SketchForgeMcpShapeSummary, + type SketchForgeMcpViewFace, +} from "@/lib/sketchforgeMcpProtocol"; +import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes"; import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; export { importedShapeFromStl }; @@ -94,6 +104,21 @@ type EdgeModifierSession = { prepared: boolean; error: string | null; preview: WorkplaneShape | null; + componentPreviews: EdgeModifierComponentPreview[]; +}; + +type EdgeModifierComponentPreview = { + owner: number; + shape: WorkplaneShape; +}; +type EdgeFeatureRevertOption = { + id: string; + entryId: string; + path: number[]; + label: string; + targetName: string; + createdAt: number; + removesNewerCount: number; }; type ManifoldSolid = ReturnType; type DownloadResult = { mode: "browser" } | { mode: "folder"; path: string }; @@ -139,6 +164,8 @@ declare global { interface Window { __sketchforgeBooleanTest?: BooleanAutomationResult; __sketchforgeBooleanTestImage?: string; + sketchforgeCaptureCanvas?: () => string; + sketchforgeCaptureView?: (face?: SketchForgeMcpViewFace) => Promise | string; } } @@ -150,6 +177,8 @@ const MODEL_DIMENSION_PRECISION = 3; const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000; 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 = { @@ -1067,35 +1096,6 @@ function meshDataToCadTransfer(mesh: MeshData) { return { positions, indices }; } -function cadBrepTransformForShape(shape: WorkplaneShape) { - const frame = shape.cadBrepFrame; - if (!frame) return undefined; - const oldCenter = new THREE.Vector3(frame.x, frame.elevation + frame.height / 2, frame.z); - const currentCenter = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); - const rotation = new THREE.Quaternion().setFromEuler(new THREE.Euler( - THREE.MathUtils.degToRad(shape.rotationX ?? 0), - THREE.MathUtils.degToRad(shape.rotation ?? 0), - THREE.MathUtils.degToRad(shape.rotationZ ?? 0), - "XYZ", - )); - const scale = new THREE.Vector3( - shapeWidth(shape) / Math.max(0.001, frame.width) * mirrorSign(shape.mirrorX), - shape.height / Math.max(0.001, frame.height) * mirrorSign(shape.mirrorY), - shapeDepth(shape) / Math.max(0.001, frame.depth) * mirrorSign(shape.mirrorZ), - ); - const matrix = new THREE.Matrix4() - .compose(currentCenter, rotation, scale) - .multiply(new THREE.Matrix4().makeTranslation(-oldCenter.x, -oldCenter.y, -oldCenter.z)); - const elements = matrix.elements; - const result = [ - elements[0], elements[4], elements[8], elements[12], - elements[1], elements[5], elements[9], elements[13], - elements[2], elements[6], elements[10], elements[14], - ]; - const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]; - return result.every((value, index) => Math.abs(value - identity[index]) < 1e-9) ? undefined : result; -} - function shapeFromCadMesh( source: WorkplaneShape, positions: Float32Array, @@ -1170,6 +1170,7 @@ function shapeFromCadMesh( depth, height, }, + cadPrimitiveFrame: undefined, }); } @@ -1217,6 +1218,10 @@ function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedI return [...selected]; } +function selectableCadModifierEdge(edge: CadModifierEdge, sharpAngle: number) { + return edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle; +} + function cadDisplayEdgesAfterTreatment(shape: WorkplaneShape, session: EdgeModifierSession) { const removed = new Set(session.selectedEdgeIds); const elevation = shape.elevation ?? 0; @@ -1250,6 +1255,26 @@ function cadDisplayEdgesForShape(shape: WorkplaneShape, edges: CadModifierDispla })); } +function cadModifierComponentPreviews(sourceParts: WorkplaneShape[], components: CadModifierComponentMesh[] | undefined): EdgeModifierComponentPreview[] { + if (!components?.length) return []; + const previews: EdgeModifierComponentPreview[] = []; + components.forEach((component) => { + const source = sourceParts[component.owner] ?? sourceParts[0]; + if (!source) return; + const shape = shapeFromCadMesh(source, component.positions, component.normals, component.indices, component.brep); + if (!shape) return; + previews.push({ + owner: component.owner, + shape: canonicalizeShape({ + ...shape, + cadDisplayEdges: cadDisplayEdgesForShape(shape, component.displayEdges), + cadDisplayEdgesVersion: 2 as const, + }), + }); + }); + return previews; +} + function cloneWorkplaneShapeSnapshot(shape: WorkplaneShape): WorkplaneShape { return JSON.parse(JSON.stringify(canonicalizeShape(shape))) as WorkplaneShape; } @@ -1259,6 +1284,139 @@ function edgeTreatmentLabel(feature: NonNullable[number], + preserveEdgeSize: boolean, + createdAt: number, +) { + return canonicalizeShape({ + ...shape, + edgeResizeMode: preserveEdgeSize ? "preserve" : "scale", + edgeTreatments: [ + ...(before.edgeTreatments ?? []), + { + ...feature, + }, + ], + edgeTreatmentHistory: [ + ...(before.edgeTreatmentHistory ?? []), + { + id: createLocalId("edge-history"), + createdAt, + feature, + before: cloneWorkplaneShapeSnapshot(before), + }, + ], + }); +} + +function shapeCenterDistance(a: WorkplaneShape, b: WorkplaneShape) { + const ax = a.x; + const ay = (a.elevation ?? 0) + a.height / 2; + const az = a.z; + const bx = b.x; + const by = (b.elevation ?? 0) + b.height / 2; + const bz = b.z; + return Math.hypot(ax - bx, ay - by, az - bz); +} + +function shapeDimensionDistance(a: WorkplaneShape, b: WorkplaneShape) { + return Math.hypot(shapeWidth(a) - shapeWidth(b), a.height - b.height, shapeDepth(a) - shapeDepth(b)); +} + +function matchCadComponentsToSources(sourceParts: WorkplaneShape[], componentPreviews: EdgeModifierComponentPreview[]) { + const candidates = componentPreviews.flatMap((component, componentIndex) => + sourceParts.map((source, sourceIndex) => ({ + component, + componentIndex, + sourceIndex, + score: shapeCenterDistance(component.shape, source) + shapeDimensionDistance(component.shape, source) * 0.25, + })), + ); + candidates.sort((a, b) => a.score - b.score); + + const usedComponents = new Set(); + const usedSources = new Set(); + const ownerToSourceIndex = new Map(); + candidates.forEach((candidate) => { + if (usedComponents.has(candidate.componentIndex) || usedSources.has(candidate.sourceIndex)) return; + usedComponents.add(candidate.componentIndex); + usedSources.add(candidate.sourceIndex); + ownerToSourceIndex.set(candidate.component.owner, candidate.sourceIndex); + }); + return ownerToSourceIndex; +} + +function groupedShapeWithComponentEdgeTreatment( + base: WorkplaneShape, + preview: WorkplaneShape, + sourceParts: WorkplaneShape[], + session: EdgeModifierSession, + feature: NonNullable[number], + createdAt: number, +) { + if (!base.groupedShapes?.length || sourceParts.length < 2 || session.componentPreviews.length === 0) { + return null; + } + + const edgeById = new Map(session.edges.map((edge) => [edge.id, edge])); + const ownerEdgeCounts = new Map(); + session.selectedEdgeIds.forEach((edgeId) => { + const owner = edgeById.get(edgeId)?.owner; + if (typeof owner !== "number") return; + ownerEdgeCounts.set(owner, (ownerEdgeCounts.get(owner) ?? 0) + 1); + }); + if (ownerEdgeCounts.size === 0) { + return null; + } + + const ownerToSourceIndex = matchCadComponentsToSources(sourceParts, session.componentPreviews); + const componentByOwner = new Map(session.componentPreviews.map((component) => [component.owner, component])); + const updatedSources = [...sourceParts]; + let changed = false; + + ownerEdgeCounts.forEach((edgeCount, owner) => { + const sourceIndex = ownerToSourceIndex.get(owner); + const component = componentByOwner.get(owner); + if (sourceIndex === undefined || !component) return; + const source = sourceParts[sourceIndex]; + const ownerFeature = { ...feature, edgeCount }; + const retargeted = canonicalizeShape({ + ...component.shape, + id: source.id, + name: source.name, + color: source.color, + hole: source.hole || undefined, + locked: source.locked, + hidden: source.hidden, + groupedShapes: source.groupedShapes, + groupedBaseWidth: source.groupedBaseWidth, + groupedBaseDepth: source.groupedBaseDepth, + groupedBaseHeight: source.groupedBaseHeight, + }); + updatedSources[sourceIndex] = shapeWithEdgeTreatmentRecord(retargeted, source, ownerFeature, session.preserveEdgeSize, createdAt); + changed = true; + }); + + if (!changed) { + return null; + } + + const elevation = preview.elevation ?? 0; + return canonicalizeShape({ + ...preview, + edgeResizeMode: session.preserveEdgeSize ? "preserve" : "scale", + edgeTreatments: base.edgeTreatments, + edgeTreatmentHistory: base.edgeTreatmentHistory, + groupedBaseWidth: shapeWidth(preview), + groupedBaseDepth: shapeDepth(preview), + groupedBaseHeight: preview.height, + groupedShapes: updatedSources.map((shape) => cloneAsGroupChild(shape, preview.x, preview.z, elevation)), + }); +} + function edgeTreatmentFeatureCount(shape: WorkplaneShape): number { return (shape.edgeTreatments?.length ?? 0) + (shape.groupedShapes?.reduce((total, child) => total + edgeTreatmentFeatureCount(child), 0) ?? 0); } @@ -1267,17 +1425,21 @@ function reversibleEdgeTreatmentCount(shape: WorkplaneShape): number { return (shape.edgeTreatmentHistory?.length ?? 0) + (shape.groupedShapes?.reduce((total, child) => total + reversibleEdgeTreatmentCount(child), 0) ?? 0); } -function latestEdgeTreatmentTimestamp(shape: WorkplaneShape): number { - const own = shape.edgeTreatmentHistory?.reduce((latest, entry) => Math.max(latest, entry.createdAt), Number.NEGATIVE_INFINITY) ?? Number.NEGATIVE_INFINITY; - const child = shape.groupedShapes?.reduce((latest, entry) => Math.max(latest, latestEdgeTreatmentTimestamp(entry)), Number.NEGATIVE_INFINITY) ?? Number.NEGATIVE_INFINITY; - return Math.max(own, child); -} - -function latestOwnEdgeTreatmentEntry(shape: WorkplaneShape) { - return (shape.edgeTreatmentHistory ?? []).reduce[number] | null>( - (latest, entry) => (!latest || entry.createdAt >= latest.createdAt ? entry : latest), - null, +function edgeTreatmentHistoryOptions(shape: WorkplaneShape, path: number[] = [], targetName = shape.name): EdgeFeatureRevertOption[] { + const ownHistory = shape.edgeTreatmentHistory ?? []; + const ownOptions = ownHistory.map((entry, index) => ({ + id: `${path.length ? path.join(".") : "root"}:${entry.id}`, + entryId: entry.id, + path, + label: edgeTreatmentLabel(entry.feature), + targetName, + createdAt: entry.createdAt, + removesNewerCount: Math.max(0, ownHistory.length - index - 1), + })); + const childOptions = (shape.groupedShapes ?? []).flatMap((child, index) => + edgeTreatmentHistoryOptions(child, [...path, index], `${targetName} / ${child.name}`), ); + return [...ownOptions, ...childOptions].sort((a, b) => b.createdAt - a.createdAt); } function restoreOwnLastEdgeTreatment(shape: WorkplaneShape, entry: NonNullable[number]) { @@ -1306,38 +1468,28 @@ function restoreOwnLastEdgeTreatment(shape: WorkplaneShape, entry: NonNullable { - const ownEntry = latestOwnEdgeTreatmentEntry(shape); - const childCandidates = (shape.groupedShapes ?? []) - .map((child, index) => ({ index, createdAt: latestEdgeTreatmentTimestamp(child) })) - .filter((entry) => Number.isFinite(entry.createdAt)); - const latestChild = childCandidates.reduce<{ index: number; createdAt: number } | null>( - (latest, entry) => (!latest || entry.createdAt > latest.createdAt ? entry : latest), - null, - ); - - if (ownEntry && (!latestChild || ownEntry.createdAt >= latestChild.createdAt)) { - return { - shape: restoreOwnLastEdgeTreatment(shape, ownEntry), - label: edgeTreatmentLabel(ownEntry.feature), - }; +async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[], entryId: string): Promise<{ shape: WorkplaneShape; label: string } | null> { + if (path.length === 0) { + const entry = (shape.edgeTreatmentHistory ?? []).find((candidate) => candidate.id === entryId); + return entry ? { shape: restoreOwnLastEdgeTreatment(shape, entry), label: edgeTreatmentLabel(entry.feature) } : null; } - if (!latestChild || !shape.groupedShapes?.length) { + if (!shape.groupedShapes?.length) { return null; } + const [childIndex, ...restPath] = path; const restoredChildren = restoreGroupedChildren(shape); - const child = restoredChildren[latestChild.index]; + const child = restoredChildren[childIndex]; if (!child) { return null; } - const restoredChild = await restoreLastEdgeTreatmentInShape(child); + const restoredChild = await restoreEdgeTreatmentInShape(child, restPath, entryId); if (!restoredChild) { return null; } - restoredChildren[latestChild.index] = restoredChild.shape; + restoredChildren[childIndex] = restoredChild.shape; const rebuilt = await buildGroupedShapeFromSelection(restoredChildren); if (!rebuilt.group) { return null; @@ -1862,6 +2014,11 @@ function shapeHasTransformToBake(shape: WorkplaneShape) { ); } +function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimitivePart | null { + return cadModifierPrimitiveForBakedShape(shape) + ?? (shapeHasTransformToBake(shape) ? cadModifierPrimitiveForAnalyticBox(shape) : null); +} + function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape { if (!shapeHasTransformToBake(shape)) { return shape; @@ -1901,6 +2058,7 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape { const height = cleanModelDimension(rawHeight); const depth = cleanModelDimension(rawDepth); const positions: number[] = []; + const bakedCadMetadata = bakeCadMetadataForShapeTransform(shape, { centerX, minY, centerZ, width, depth, height, yawDegrees: meshYawDegrees(shape) }); mesh.faces.forEach(([ai, bi, ci]) => { [mesh.vertices[ai], mesh.vertices[bi], mesh.vertices[ci]].forEach(([x, y, z]) => { @@ -1932,6 +2090,7 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape { triangleCount: mesh.faces.length, sourceFormat: "json", }, + ...bakedCadMetadata, imagePlate: undefined, groupedShapes: undefined, groupedBaseWidth: undefined, @@ -2634,6 +2793,128 @@ function meshDataPositions(mesh: MeshData) { return positions; } +function meshFaceComponents(mesh: MeshData, tolerance = SEPARATE_PARTS_VERTEX_TOLERANCE) { + if (mesh.faces.length === 0) return []; + const keysByFace = mesh.faces.map((face) => face.map((vertexIndex) => quantizedPointKey(mesh.vertices[vertexIndex], tolerance))); + const facesByVertex = new Map(); + keysByFace.forEach((keys, faceIndex) => { + keys.forEach((key) => { + const current = facesByVertex.get(key); + if (current) { + current.push(faceIndex); + } else { + facesByVertex.set(key, [faceIndex]); + } + }); + }); + + const visited = new Uint8Array(mesh.faces.length); + const components: number[][] = []; + for (let faceIndex = 0; faceIndex < mesh.faces.length; faceIndex += 1) { + if (visited[faceIndex]) continue; + const component: number[] = []; + const queue = [faceIndex]; + visited[faceIndex] = 1; + while (queue.length > 0) { + const current = queue.pop() as number; + component.push(current); + keysByFace[current].forEach((key) => { + const neighbors = facesByVertex.get(key); + if (!neighbors) return; + facesByVertex.delete(key); + neighbors.forEach((neighbor) => { + if (visited[neighbor]) return; + visited[neighbor] = 1; + queue.push(neighbor); + }); + }); + } + components.push(component); + } + return components; +} + +function meshComponentShape(source: WorkplaneShape, mesh: MeshData, faceIndices: number[], partIndex: number, totalParts: number): WorkplaneShape | null { + const worldPositions: number[] = []; + faceIndices.forEach((faceIndex) => { + const face = mesh.faces[faceIndex]; + if (!face) return; + face.forEach((vertexIndex) => { + const vertex = mesh.vertices[vertexIndex]; + if (vertex) worldPositions.push(vertex[0], vertex[1], vertex[2]); + }); + }); + + const bounds = boundsForPositions(worldPositions); + if (!bounds) return null; + const centerX = (bounds.minX + bounds.maxX) / 2; + const centerZ = (bounds.minZ + bounds.maxZ) / 2; + const rawWidth = Math.max(MIN_SHAPE_DIMENSION, bounds.maxX - bounds.minX); + const rawHeight = Math.max(MIN_SHAPE_DIMENSION, bounds.maxY - bounds.minY); + const rawDepth = Math.max(MIN_SHAPE_DIMENSION, bounds.maxZ - bounds.minZ); + const width = cleanModelDimension(rawWidth); + const height = cleanModelDimension(rawHeight); + const depth = cleanModelDimension(rawDepth); + const positions = worldPositions.map((value, index) => { + if (index % 3 === 0) return value - centerX; + if (index % 3 === 1) return value - bounds.minY; + return value - centerZ; + }); + + return canonicalizeShape({ + id: createLocalId(`${source.id}-part`), + name: totalParts > 1 ? `${source.name} Part ${partIndex + 1}` : source.name, + kind: "mesh", + color: source.color, + hole: source.hole || undefined, + x: cleanNearZero(centerX, 0.0005), + z: cleanNearZero(centerZ, 0.0005), + elevation: cleanNearZero(bounds.minY, 0.0005), + size: Math.max(width, depth), + width, + depth, + height, + rotation: 0, + rotationX: 0, + rotationZ: 0, + importedMesh: { + positions, + baseWidth: rawWidth, + baseDepth: rawDepth, + baseHeight: rawHeight, + triangleCount: Math.floor(positions.length / 9), + sourceFormat: "json", + }, + locked: false, + hidden: source.hidden, + }); +} + +function separateMeshParts(shape: WorkplaneShape) { + const mesh = meshForShape(shape); + const components = meshFaceComponents(mesh).filter((component) => component.length > 0); + if (components.length <= 1) return []; + return components + .map((component, index) => meshComponentShape(shape, mesh, component, index, components.length)) + .filter((part): part is WorkplaneShape => Boolean(part)); +} + +function separablePartCount(shape: WorkplaneShape) { + if (shape.locked || shape.hole) return 0; + if (shape.groupedShapes?.length && !shape.importedMesh) return shape.groupedShapes.length; + const mesh = meshForShape(shape); + return meshFaceComponents(mesh).length; +} + +function separateShapeParts(shape: WorkplaneShape) { + if (shape.locked || shape.hole) return []; + if (shape.groupedShapes?.length && !shape.importedMesh) { + const restored = restoreGroupedChildren(shape); + return restored.length > 1 ? restored : []; + } + return separateMeshParts(shape); +} + function cutBoundaryEdgeCount(positions: number[], cutters: WorkplaneShape[]) { if (cutters.length === 0) { return 0; @@ -4622,6 +4903,7 @@ function debugShapeSummary(shape: WorkplaneShape): Record { cadDisplayEdgesVersion: shape.cadDisplayEdgesVersion ?? null, edgeResizeMode: shape.edgeResizeMode ?? "scale", cadBrepLength: shape.cadBrep?.length ?? 0, + cadPrimitiveKind: shape.cadPrimitiveFrame?.kind ?? null, groupedCount: shape.groupedShapes?.length ?? 0, children: shape.groupedShapes?.map(debugShapeSummary) ?? [], }; @@ -4639,6 +4921,7 @@ function compactShapeSummary(shape: WorkplaneShape, index: number) { `viewEdges${shape.cadDisplayEdges?.length ?? "auto"}v${shape.cadDisplayEdgesVersion ?? 0}`, `edgeResize${shape.edgeResizeMode ?? "scale"}`, `brep${shape.cadBrep?.length ?? 0}`, + `prim${shape.cadPrimitiveFrame ? `${shape.cadPrimitiveFrame.kind}:${shape.cadPrimitiveFrame.width}:${shape.cadPrimitiveFrame.depth}:${shape.cadPrimitiveFrame.height}` : ""}`, `p${Number(shape.x.toFixed(2))},${Number(shape.z.toFixed(2))},${Number((shape.elevation ?? 0).toFixed(2))}`, `d${Number(shapeWidth(shape).toFixed(2))}x${Number(shapeDepth(shape).toFixed(2))}x${Number(shape.height.toFixed(2))}`, `r${Number((shape.rotationX ?? 0).toFixed(1))},${Number(shape.rotation.toFixed(1))},${Number((shape.rotationZ ?? 0).toFixed(1))}`, @@ -4647,6 +4930,114 @@ function compactShapeSummary(shape: WorkplaneShape, index: number) { ].join(","); } +function mcpShapeSummary(shape: WorkplaneShape): SketchForgeMcpShapeSummary { + return { + id: shape.id, + name: shape.name, + kind: shape.kind, + color: shape.color, + hole: Boolean(shape.hole), + locked: Boolean(shape.locked), + hidden: Boolean(shape.hidden), + position: { + x: shape.x, + z: shape.z, + elevation: shape.elevation ?? 0, + }, + dimensions: { + width: shapeWidth(shape), + depth: shapeDepth(shape), + height: shape.height, + size: shape.size, + }, + rotation: { + x: shape.rotationX ?? 0, + y: shape.rotation, + z: shape.rotationZ ?? 0, + }, + mirror: { + x: Boolean(shape.mirrorX), + y: Boolean(shape.mirrorY), + z: Boolean(shape.mirrorZ), + }, + edgeTreatments: shape.edgeTreatments ?? [], + groupedCount: shape.groupedShapes?.length ?? 0, + importedTriangles: shape.importedMesh?.triangleCount ?? 0, + cadDisplayEdgeCount: shape.cadDisplayEdges?.length ?? null, + sketchPointCount: shape.sketchProfile?.points.length ?? 0, + sketchSegmentCount: shape.sketchProfile?.segments.length ?? 0, + children: shape.groupedShapes?.map(mcpShapeSummary), + }; +} + +function defaultMcpSketchProfile(width: number, depth: number): SketchProfile { + const halfWidth = Math.max(0.01, width) / 2; + const halfDepth = Math.max(0.01, depth) / 2; + const pointIds = ["mcp-sketch-a", "mcp-sketch-b", "mcp-sketch-c", "mcp-sketch-d"].map((prefix) => createLocalId(prefix)); + return { + points: [ + { id: pointIds[0], x: -halfWidth, z: -halfDepth, mode: "corner" }, + { id: pointIds[1], x: halfWidth, z: -halfDepth, mode: "corner" }, + { id: pointIds[2], x: halfWidth, z: halfDepth, mode: "corner" }, + { id: pointIds[3], x: -halfWidth, z: halfDepth, mode: "corner" }, + ], + segments: [ + { id: createLocalId("mcp-sketch-segment"), startId: pointIds[0], endId: pointIds[1], kind: "line" }, + { id: createLocalId("mcp-sketch-segment"), startId: pointIds[1], endId: pointIds[2], kind: "line" }, + { id: createLocalId("mcp-sketch-segment"), startId: pointIds[2], endId: pointIds[3], kind: "line" }, + { id: createLocalId("mcp-sketch-segment"), startId: pointIds[3], endId: pointIds[0], kind: "line" }, + ], + images: [], + }; +} + +function mcpNumber(value: unknown, fallback: number) { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} + +function mcpString(value: unknown, fallback: string) { + return typeof value === "string" && value.trim() ? value : fallback; +} + +function mcpStringArray(value: unknown): string[] { + if (Array.isArray(value)) { + return value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0); + } + return typeof value === "string" && value.length > 0 ? [value] : []; +} + +function mcpNumberArray(value: unknown): number[] { + return Array.isArray(value) ? value.filter((entry): entry is number => typeof entry === "number" && Number.isInteger(entry)) : []; +} + +function mcpFiniteNumberArray(value: unknown): number[] { + return Array.isArray(value) ? value.filter((entry): entry is number => typeof entry === "number" && Number.isFinite(entry)) : []; +} + +function readMcpEditorIdentity() { + const storageKey = "sketchforge.mcp.editorIdentity"; + try { + const existing = JSON.parse(window.sessionStorage.getItem(storageKey) ?? "null") as { editorId?: unknown; editorNumber?: unknown } | null; + if (typeof existing?.editorId === "string" && typeof existing.editorNumber === "number") { + return { editorId: existing.editorId, editorNumber: existing.editorNumber }; + } + } catch { + // Session identity is best-effort; fall through and create a new one. + } + + const randomValues = new Uint32Array(1); + window.crypto?.getRandomValues?.(randomValues); + const editorNumber = 10000 + ((randomValues[0] || Math.floor(Math.random() * 90000)) % 90000); + const editorId = window.crypto?.randomUUID?.() ?? `sketchforge-editor-${Date.now()}-${Math.random().toString(36).slice(2)}`; + const identity = { editorId, editorNumber }; + try { + window.sessionStorage.setItem(storageKey, JSON.stringify(identity)); + } catch { + // Private browsing can block sessionStorage; the in-memory identity is enough for this tab. + } + return identity; +} + function projectShapesFingerprint(shapes: WorkplaneShape[]) { return shapes .map((shape, index) => @@ -4657,6 +5048,30 @@ function projectShapesFingerprint(shapes: WorkplaneShape[]) { `clr${shape.color}`, `txt${shape.text ?? ""}`, `mesh${shape.importedMesh?.positions.length ?? 0}:${shape.importedMesh?.normals?.length ?? 0}`, + `cadFrame${shape.cadBrepFrame ? JSON.stringify({ + x: Number(shape.cadBrepFrame.x.toFixed(6)), + z: Number(shape.cadBrepFrame.z.toFixed(6)), + elevation: Number(shape.cadBrepFrame.elevation.toFixed(6)), + width: Number(shape.cadBrepFrame.width.toFixed(6)), + depth: Number(shape.cadBrepFrame.depth.toFixed(6)), + height: Number(shape.cadBrepFrame.height.toFixed(6)), + sourceTransform: shape.cadBrepFrame.sourceTransform?.map((value) => Number(value.toFixed(9))) ?? null, + }) : ""}`, + `primitiveFrame${shape.cadPrimitiveFrame ? JSON.stringify({ + kind: shape.cadPrimitiveFrame.kind, + width: Number(shape.cadPrimitiveFrame.width.toFixed(6)), + depth: Number(shape.cadPrimitiveFrame.depth.toFixed(6)), + height: Number(shape.cadPrimitiveFrame.height.toFixed(6)), + frame: { + x: Number(shape.cadPrimitiveFrame.frame.x.toFixed(6)), + z: Number(shape.cadPrimitiveFrame.frame.z.toFixed(6)), + elevation: Number(shape.cadPrimitiveFrame.frame.elevation.toFixed(6)), + width: Number(shape.cadPrimitiveFrame.frame.width.toFixed(6)), + depth: Number(shape.cadPrimitiveFrame.frame.depth.toFixed(6)), + height: Number(shape.cadPrimitiveFrame.frame.height.toFixed(6)), + sourceTransform: shape.cadPrimitiveFrame.frame.sourceTransform?.map((value) => Number(value.toFixed(9))) ?? null, + }, + }) : ""}`, `sketch${shape.sketchProfile ? JSON.stringify({ points: shape.sketchProfile.points, segments: shape.sketchProfile.segments, @@ -4707,6 +5122,7 @@ export function SketchForgeEditor({ const [history, setHistory] = useState([[]]); const [historyIndex, setHistoryIndex] = useState(0); const [placementElevation, setPlacementElevation] = useState(0); + const [workspaceSettings, setWorkspaceSettings] = useState(() => normalizeWorkspaceSettings(initialWorkspace)); const [workplaneMode, setWorkplaneMode] = useState(false); const [menuOpen, setMenuOpen] = useState(false); const [topPanel, setTopPanel] = useState(null); @@ -4730,6 +5146,10 @@ export function SketchForgeEditor({ const lastProjectIdRef = useRef(null); const projectSnapshotRunRef = useRef(0); const shapesRef = useRef(shapes); + const selectedIdsRef = useRef(selectedIds); + const workspaceSettingsRef = useRef(workspaceSettings); + const noticeRef = useRef(notice); + const projectInfoRef = useRef({ projectId: projectId ?? null, projectName }); const historyIndexRef = useRef(historyIndex); const interactionHistoryStartRef = useRef(""); const interactionHistoryChangedRef = useRef(false); @@ -4747,18 +5167,38 @@ export function SketchForgeEditor({ const [sketchMeasurement, setSketchMeasurement] = useState(null); const [editingSketchShapeId, setEditingSketchShapeId] = useState(null); const [edgeModifier, setEdgeModifier] = useState(null); + const edgeModifierRef = useRef(null); const cadModifierWorkerRef = useRef(null); + const cadModifierPendingRef = useRef(new Map void; + reject: (error: Error) => void; + timer: number; + }>()); const cadModifierRequestRef = useRef(0); const cadModifierPrepareRef = useRef(0); const cadModifierLatestPreviewRef = useRef(0); const cadModifierBaseShapeRef = useRef(null); const cadModifierBaseFingerprintRef = useRef(""); + const cadModifierSourcePartsRef = useRef([]); + const lastMcpErrorRef = useRef(null); + const executeMcpCommandRef = useRef<((command: SketchForgeMcpCommand) => Promise) | null>(null); useEffect(() => { const worker = new Worker(new URL("../workers/cadModifier.worker.ts", import.meta.url), { type: "module" }); cadModifierWorkerRef.current = worker; worker.onmessage = (event: MessageEvent) => { const message = event.data; + const pending = cadModifierPendingRef.current.get(message.requestId); + if (pending) { + window.clearTimeout(pending.timer); + cadModifierPendingRef.current.delete(message.requestId); + if (message.type === "error") { + pending.reject(new Error(message.message)); + } else { + pending.resolve(message); + } + return; + } if (message.type === "ready") { if (message.requestId !== cadModifierPrepareRef.current) return; setEdgeModifier((current) => current ? { @@ -4775,15 +5215,18 @@ export function SketchForgeEditor({ if (message.type === "preview") { if (message.requestId !== cadModifierLatestPreviewRef.current) return; const base = cadModifierBaseShapeRef.current; + const sourceParts = cadModifierSourcePartsRef.current.length ? cadModifierSourcePartsRef.current : (base ? [base] : []); const rawPreview = base ? shapeFromCadMesh(base, message.positions, message.normals, message.indices, message.brep) : null; const preview = rawPreview ? { ...rawPreview, cadDisplayEdges: cadDisplayEdgesForShape(rawPreview, message.displayEdges), cadDisplayEdgesVersion: 2 as const, } : null; + const componentPreviews = cadModifierComponentPreviews(sourceParts, message.components); setEdgeModifier((current) => current ? { ...current, preview, + componentPreviews, busy: false, error: preview ? null : "The CAD kernel returned an empty edge treatment", } : current); @@ -4792,6 +5235,18 @@ export function SketchForgeEditor({ } if (message.type === "error") { if (message.requestId < cadModifierLatestPreviewRef.current) return; + if (message.resetSession) { + const requestId = cadModifierRequestRef.current + 1; + cadModifierRequestRef.current = requestId; + cadModifierLatestPreviewRef.current = requestId; + cadModifierPrepareRef.current = requestId; + cadModifierBaseShapeRef.current = null; + cadModifierBaseFingerprintRef.current = ""; + cadModifierSourcePartsRef.current = []; + setEdgeModifier(null); + setNotice(message.message); + return; + } setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: message.message } : current); setNotice("Edge treatment needs adjustment"); } @@ -4800,6 +5255,11 @@ export function SketchForgeEditor({ setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: "The CAD worker could not start" } : current); }; return () => { + cadModifierPendingRef.current.forEach((pending) => { + window.clearTimeout(pending.timer); + pending.reject(new Error("The CAD worker was closed")); + }); + cadModifierPendingRef.current.clear(); worker.terminate(); cadModifierWorkerRef.current = null; }; @@ -4815,6 +5275,7 @@ export function SketchForgeEditor({ cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest); cadModifierBaseShapeRef.current = null; cadModifierBaseFingerprintRef.current = ""; + cadModifierSourcePartsRef.current = []; setEdgeModifier(null); return true; }, []); @@ -4869,29 +5330,58 @@ export function SketchForgeEditor({ shapesRef.current = shapes; }, [shapes]); + useEffect(() => { + selectedIdsRef.current = selectedIds; + }, [selectedIds]); + + useEffect(() => { + workspaceSettingsRef.current = workspaceSettings; + }, [workspaceSettings]); + + useEffect(() => { + noticeRef.current = notice; + }, [notice]); + + useEffect(() => { + projectInfoRef.current = { projectId: projectId ?? null, projectName }; + }, [projectId, projectName]); + useEffect(() => { historyIndexRef.current = historyIndex; }, [historyIndex]); + useEffect(() => { + edgeModifierRef.current = edgeModifier; + }, [edgeModifier]); + + useEffect(() => { + setWorkspaceSettings(normalizeWorkspaceSettings(initialWorkspace)); + }, [initialWorkspace]); + const selectedShapes = useMemo(() => shapes.filter((shape) => selectedIds.includes(shape.id)), [selectedIds, shapes]); const selectedShape = selectedShapes.at(-1) ?? null; const hasSelection = selectedShapes.length > 0; const modifierAvailableEdgeIds = useMemo( - () => edgeModifier ? edgeModifier.edges.filter((edge) => edge.manifold && !edge.boundary && edge.angle + 1e-3 >= edgeModifier.sharpAngle).map((edge) => edge.id) : [], + () => edgeModifier ? edgeModifier.edges.filter((edge) => selectableCadModifierEdge(edge, edgeModifier.sharpAngle)).map((edge) => edge.id) : [], [edgeModifier?.edges, edgeModifier?.sharpAngle], ); const edgeModifierMaxAmount = useMemo(() => { const source = cadModifierBaseShapeRef.current ?? selectedShape; if (!source) return 10; const smallestDimension = Math.min(shapeWidth(source), shapeDepth(source), source.height); - return Math.max(0.05, smallestDimension * (edgeModifier?.kind === "chamfer" ? 0.99 : 0.5)); + return Math.max(MIN_EDGE_MODIFIER_AMOUNT, smallestDimension * 0.99); }, [edgeModifier, selectedShape]); const selectedEdgeFeatureCount = useMemo(() => selectedShape ? edgeTreatmentFeatureCount(selectedShape) : 0, [selectedShape]); const selectedReversibleEdgeFeatureCount = useMemo(() => selectedShape ? reversibleEdgeTreatmentCount(selectedShape) : 0, [selectedShape]); + const selectedEdgeHistoryOptions = useMemo(() => selectedShape ? edgeTreatmentHistoryOptions(selectedShape) : [], [selectedShape]); + const canSeparateSelectedParts = useMemo( + () => selectedShapes.length === 1 && Boolean(selectedShape && separablePartCount(selectedShape) > 1), + [selectedShape, selectedShapes.length], + ); const toggleModifierEdge = useCallback((id: number, singleEdge = false) => { setEdgeModifier((current) => { if (!current) return current; - const allowed = new Set(current.edges.filter((edge) => edge.boundary || edge.angle + 1e-3 >= current.sharpAngle).map((edge) => edge.id)); + const allowed = new Set(current.edges.filter((edge) => selectableCadModifierEdge(edge, current.sharpAngle)).map((edge) => edge.id)); if (!allowed.has(id)) return current; const ids = current.tangentChain && !singleEdge ? tangentCadEdgeChain(current.edges, id, allowed) : [id]; const next = new Set(current.selectedEdgeIds); @@ -5081,6 +5571,7 @@ export function SketchForgeEditor({ const updateProjectWorkspaceSettings = useCallback( (settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => { + setWorkspaceSettings(settings.workspace); if (!projectId || !onProjectWorkspaceChange) { return; } @@ -5111,7 +5602,7 @@ export function SketchForgeEditor({ [historyIndex, selectedIds, syncProjectShapes], ); - const removeLastEdgeTreatment = useCallback(async () => { + const removeEdgeTreatment = useCallback(async (optionId: string) => { if (!selectedShape) { setNotice("Select a shape with an edge feature first"); return; @@ -5120,7 +5611,12 @@ export function SketchForgeEditor({ setNotice("Unlock the shape before removing an edge feature"); return; } - const restored = await restoreLastEdgeTreatmentInShape(selectedShape); + const option = selectedEdgeHistoryOptions.find((candidate) => candidate.id === optionId); + if (!option) { + setNotice("Choose an edge feature to remove"); + return; + } + const restored = await restoreEdgeTreatmentInShape(selectedShape, option.path, option.entryId); if (!restored) { setNotice(selectedEdgeFeatureCount > 0 ? "This edge feature has no stored undo history" : "No edge feature to remove"); return; @@ -5132,7 +5628,7 @@ export function SketchForgeEditor({ `Removed ${restored.label}`, ); setNotice(`Removed ${restored.label}`); - }, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedShape, shapes]); + }, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedEdgeHistoryOptions, selectedShape, shapes]); const commitSketchProfile = useCallback( (next: SketchProfile, message?: string) => { @@ -5841,6 +6337,23 @@ export function SketchForgeEditor({ return requestId; }, []); + const postCadModifierRequestAsync = useCallback((request: CadModifierWorkerPayload, transfer: Transferable[] = [], timeoutMs = 20000) => { + const worker = cadModifierWorkerRef.current; + if (!worker) { + return Promise.reject(new Error("The CAD worker is not ready")); + } + const requestId = cadModifierRequestRef.current + 1; + cadModifierRequestRef.current = requestId; + return new Promise((resolve, reject) => { + const timer = window.setTimeout(() => { + cadModifierPendingRef.current.delete(requestId); + 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); + }); + }, []); + const cancelEdgeModifier = useCallback(() => { invalidateCadModifierSession(); setNotice("Edge modifier cancelled"); @@ -5851,21 +6364,24 @@ export function SketchForgeEditor({ setNotice(`Select one unlocked solid to ${kind}`); return; } + const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape); const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length); const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape]; - const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[] }> = sourceParts.map((shape) => { + const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => { const frame = shape.cadBrepFrame; const preserveNeedsRetessellation = preservesEdgeTreatmentSize(shape) && Boolean(frame) && ( Math.abs(shapeWidth(shape) - (frame?.width ?? shapeWidth(shape))) > 1e-6 || Math.abs(shapeDepth(shape) - (frame?.depth ?? shapeDepth(shape))) > 1e-6 || Math.abs(shape.height - (frame?.height ?? shape.height)) > 1e-6 ); + const primitive = cadModifierPrimitiveForShape(shape); + if (primitive) return { shape, primitive }; return shape.cadBrep && frame && !preserveNeedsRetessellation ? { shape, brep: shape.cadBrep, brepTransform: cadBrepTransformForShape(shape) } : { shape, mesh: meshForShape(shape) }; }); const triangleCount = partInputs.reduce((total, part) => total + (part.mesh?.faces.length ?? 0), 0); - if (triangleCount === 0 && partInputs.every((part) => !part.brep)) { + if (triangleCount === 0 && partInputs.every((part) => !part.brep && !part.primitive)) { setNotice("The selected object has no printable surface"); return; } @@ -5873,9 +6389,10 @@ export function SketchForgeEditor({ setNotice("This mesh is too dense for interactive edge treatment. Simplify it below 180,000 triangles first."); return; } - const amount = Math.max(0.05, Math.min(1, shapeWidth(selectedShape) / 6, shapeDepth(selectedShape) / 6, selectedShape.height / 6)); + const amount = Math.max(MIN_EDGE_MODIFIER_AMOUNT, Math.min(1, shapeWidth(selectedShape) / 6, shapeDepth(selectedShape) / 6, selectedShape.height / 6)); cadModifierBaseShapeRef.current = selectedShape; cadModifierBaseFingerprintRef.current = projectShapesFingerprint([selectedShape]); + cadModifierSourcePartsRef.current = sourceParts; setAlignMode(false); setMirrorMode(false); setEdgeModifier({ @@ -5892,18 +6409,146 @@ export function SketchForgeEditor({ prepared: false, error: null, preview: null, + componentPreviews: [], }); setNotice(`Preparing ${kind} edges in the CAD worker`); - const parts: CadModifierMeshPart[] = partInputs.map((part) => part.brep - ? { brep: part.brep, brepTransform: part.brepTransform, hole: Boolean(part.shape.hole) } - : { ...meshDataToCadTransfer(part.mesh as MeshData), hole: Boolean(part.shape.hole) }); + const parts: CadModifierMeshPart[] = partInputs.map((part) => { + if (part.brep) return { brep: part.brep, brepTransform: part.brepTransform, hole: Boolean(part.shape.hole) }; + 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({ 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]); + const prepareCadModifierForMcp = useCallback(async (shape: WorkplaneShape, sharpAngle: number) => { + if (shape.locked || shape.hole) { + throw new Error("Select one unlocked solid object for edge treatment"); + } + const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape); + const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length); + const sourceParts = shape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(shape) : [shape]; + const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => { + const frame = partShape.cadBrepFrame; + const preserveNeedsRetessellation = preservesEdgeTreatmentSize(partShape) && Boolean(frame) && ( + Math.abs(shapeWidth(partShape) - (frame?.width ?? shapeWidth(partShape))) > 1e-6 || + Math.abs(shapeDepth(partShape) - (frame?.depth ?? shapeDepth(partShape))) > 1e-6 || + Math.abs(partShape.height - (frame?.height ?? partShape.height)) > 1e-6 + ); + const primitive = cadModifierPrimitiveForShape(partShape); + if (primitive) return { shape: partShape, primitive }; + return partShape.cadBrep && frame && !preserveNeedsRetessellation + ? { shape: partShape, brep: partShape.cadBrep, brepTransform: cadBrepTransformForShape(partShape) } + : { shape: partShape, mesh: meshForShape(partShape) }; + }); + const triangleCount = partInputs.reduce((total, part) => total + (part.mesh?.faces.length ?? 0), 0); + if (triangleCount === 0 && partInputs.every((part) => !part.brep && !part.primitive)) { + throw new Error("The selected object has no printable surface"); + } + if (triangleCount > 180_000) { + throw new Error("This mesh is too dense for interactive edge treatment. Simplify it below 180,000 triangles first."); + } + const parts: CadModifierMeshPart[] = partInputs.map((part) => { + if (part.brep) return { brep: part.brep, brepTransform: part.brepTransform, hole: Boolean(part.shape.hole) }; + if (part.primitive) return { primitive: part.primitive, hole: Boolean(part.shape.hole) }; + return { ...meshDataToCadTransfer(part.mesh as MeshData), hole: Boolean(part.shape.hole) }; + }); + const transfer = parts.flatMap((part) => part.positions && part.indices ? [part.positions.buffer as Transferable, part.indices.buffer as Transferable] : []); + const response = await postCadModifierRequestAsync({ + type: "prepare", + parts, + sharpAngle, + suppressTreatmentDetailEdges: appliedEdgeTreatmentCount > 0, + }, transfer); + if (response.type !== "ready") { + throw new Error("The CAD worker did not return an edge list"); + } + return { response, sourceParts }; + }, [postCadModifierRequestAsync]); + + const applyCadModifierForMcp = useCallback(async ( + shape: WorkplaneShape, + params: Record, + ) => { + invalidateCadModifierSession(); + const kind: CadModifierKind = params.kind === "fillet" ? "fillet" : "chamfer"; + const sharpAngle = Math.max(1, Math.min(120, mcpNumber(params.sharpAngle, 25))); + const amount = Math.max(MIN_EDGE_MODIFIER_AMOUNT, mcpNumber(params.amount, 1)); + const chamferAngle = Math.max(5, Math.min(85, mcpNumber(params.chamferAngle, 45))); + const quality: CadModifierQuality = params.quality === "draft" || params.quality === "fine" ? params.quality : "standard"; + const preserveEdgeSize = typeof params.preserveEdgeSize === "boolean" ? params.preserveEdgeSize : shape.edgeResizeMode === "preserve"; + const { response, sourceParts } = await prepareCadModifierForMcp(shape, sharpAngle); + const selectableIds = response.edges.filter((edge) => selectableCadModifierEdge(edge, sharpAngle)).map((edge) => edge.id); + const requestedIds = mcpNumberArray(params.edgeIds); + const selectedEdgeIds = params.edgeIds === "all" || params.allEdges === true ? selectableIds : requestedIds.filter((edgeId) => selectableIds.includes(edgeId)); + const missingIds = requestedIds.filter((edgeId) => !selectableIds.includes(edgeId)); + if (selectedEdgeIds.length === 0) { + throw new Error("Select at least one valid highlighted edge ID"); + } + if (missingIds.length > 0) { + throw new Error(`These edge IDs are not selectable at the current threshold: ${missingIds.join(", ")}`); + } + const previewResponse = await postCadModifierRequestAsync({ + type: "preview", + kind, + edgeIds: selectedEdgeIds, + amount, + quality, + chamferAngle, + }, [], 30000); + if (previewResponse.type !== "preview") { + throw new Error("The CAD worker did not return an edge preview"); + } + const rawPreview = shapeFromCadMesh(shape, previewResponse.positions, previewResponse.normals, previewResponse.indices, previewResponse.brep); + if (!rawPreview) { + throw new Error("The CAD kernel returned an empty edge treatment"); + } + const preview = canonicalizeShape({ + ...rawPreview, + cadDisplayEdges: cadDisplayEdgesForShape(rawPreview, previewResponse.displayEdges), + cadDisplayEdgesVersion: 2 as const, + }); + const feature = { + kind, + amount, + edgeCount: selectedEdgeIds.length, + ...(kind === "chamfer" ? { chamferAngle } : {}), + } satisfies NonNullable[number]; + const session: EdgeModifierSession = { + kind, + edges: response.edges, + selectedEdgeIds, + amount, + sharpAngle, + chamferAngle, + quality, + tangentChain: false, + preserveEdgeSize, + busy: false, + prepared: true, + error: null, + preview, + componentPreviews: cadModifierComponentPreviews(sourceParts, previewResponse.components), + }; + const createdAt = Date.now(); + const groupedModifiedShape = groupedShapeWithComponentEdgeTreatment(shape, preview, sourceParts, session, feature, createdAt); + const modifiedShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord(preview, shape, feature, preserveEdgeSize, createdAt); + commitShapes( + shapesRef.current.map((candidate) => candidate.id === shape.id ? modifiedShape : candidate), + modifiedShape.id, + `${kind === "fillet" ? "Filleted" : "Chamfered"} ${selectedEdgeIds.length} edge${selectedEdgeIds.length === 1 ? "" : "s"} by MCP`, + ); + return { + object: mcpShapeSummary(modifiedShape), + selectedEdgeIds, + selectableEdgeIds: selectableIds, + }; + }, [commitShapes, invalidateCadModifierSession, prepareCadModifierForMcp, postCadModifierRequestAsync]); + useEffect(() => { const base = cadModifierBaseShapeRef.current; if (!edgeModifier || !base) return; @@ -5926,29 +6571,29 @@ export function SketchForgeEditor({ edgeCount: edgeModifier.selectedEdgeIds.length, ...(edgeModifier.kind === "chamfer" ? { chamferAngle: edgeModifier.chamferAngle } : {}), } satisfies NonNullable[number]; - const modifiedShape: WorkplaneShape = { + const createdAt = Date.now(); + const previewShape = canonicalizeShape({ ...edgeModifier.preview, - edgeResizeMode: edgeModifier.preserveEdgeSize ? "preserve" : "scale", cadDisplayEdges: edgeModifier.preview.cadDisplayEdges?.length ? edgeModifier.preview.cadDisplayEdges : cadDisplayEdgesAfterTreatment(edgeModifier.preview, edgeModifier), cadDisplayEdgesVersion: 2, - edgeTreatments: [ - ...(base.edgeTreatments ?? []), - { - ...feature, - }, - ], - edgeTreatmentHistory: [ - ...(base.edgeTreatmentHistory ?? []), - { - id: createLocalId("edge-history"), - createdAt: Date.now(), - feature, - before: cloneWorkplaneShapeSnapshot(base), - }, - ], - }; + }); + const groupedModifiedShape = groupedShapeWithComponentEdgeTreatment( + base, + previewShape, + cadModifierSourcePartsRef.current, + edgeModifier, + feature, + createdAt, + ); + const modifiedShape: WorkplaneShape = groupedModifiedShape ?? shapeWithEdgeTreatmentRecord( + previewShape, + base, + feature, + edgeModifier.preserveEdgeSize, + createdAt, + ); commitShapes( shapes.map((shape) => shape.id === base.id ? modifiedShape : shape), base.id, @@ -6209,6 +6854,438 @@ export function SketchForgeEditor({ commitShapes([...shapes.filter((shape) => !groupIds.has(shape.id)), ...restored], restored.map((shape) => shape.id), `Ungrouped ${groups.length} group${groups.length === 1 ? "" : "s"}`); }, [commitShapes, selectedShapes, shapes]); + const separateSelectedParts = useCallback(() => { + if (selectedShapes.length !== 1 || !selectedShape) { + setNotice("Select one object to separate"); + return; + } + if (selectedShape.locked) { + setNotice("Unlock the object before separating parts"); + return; + } + const parts = separateShapeParts(selectedShape); + if (parts.length <= 1) { + setNotice("The selected object has only one connected part"); + return; + } + commitShapes( + [...shapes.filter((shape) => shape.id !== selectedShape.id), ...parts], + parts.map((shape) => shape.id), + `Separated ${parts.length} parts`, + ); + }, [commitShapes, selectedShape, selectedShapes.length, shapes]); + + const mcpSceneSnapshot = useCallback((includeRawShapes = false): SketchForgeMcpSceneSummary & { rawShapes?: WorkplaneShape[] } => { + const projectInfo = projectInfoRef.current; + const currentShapes = shapesRef.current; + return { + projectId: projectInfo.projectId, + projectName: projectInfo.projectName, + notice: noticeRef.current, + selectedIds: selectedIdsRef.current, + shapeCount: currentShapes.length, + workspace: workspaceSettingsRef.current, + snap: initialSnap ?? null, + shapes: currentShapes.map(mcpShapeSummary), + ...(includeRawShapes ? { rawShapes: currentShapes.map((shape) => canonicalizeShape(shape)) } : {}), + }; + }, [initialSnap]); + + const executeMcpCommand = useCallback(async (command: SketchForgeMcpCommand): Promise => { + const params = command.params ?? {}; + const currentShapes = () => shapesRef.current; + const findShape = (id: unknown) => (typeof id === "string" ? currentShapes().find((shape) => shape.id === id) ?? null : null); + + try { + lastMcpErrorRef.current = null; + if (command.action === "get_scene") { + return mcpSceneSnapshot(params.includeRawShapes === true); + } + + if (command.action === "list_objects") { + return { objects: currentShapes().map(mcpShapeSummary) }; + } + + if (command.action === "select_objects") { + const requestedIds = mcpStringArray(params.ids ?? params.id); + const validIds = requestedIds.filter((id) => currentShapes().some((shape) => shape.id === id)); + setSelectedIds(validIds); + selectedIdsRef.current = validIds; + setNotice(validIds.length ? `MCP selected ${validIds.length} object${validIds.length === 1 ? "" : "s"}` : "MCP cleared selection"); + return { selectedIds: validIds, objects: currentShapes().filter((shape) => validIds.includes(shape.id)).map(mcpShapeSummary) }; + } + + if (command.action === "delete_objects") { + const requestedIds = mcpStringArray(params.ids ?? params.id); + const ids = requestedIds.length ? new Set(requestedIds) : new Set(selectedIdsRef.current); + const deleted = currentShapes().filter((shape) => ids.has(shape.id)); + if (deleted.length === 0) throw new Error("No matching objects to delete"); + commitShapes(currentShapes().filter((shape) => !ids.has(shape.id)), [], `MCP deleted ${deleted.length} object${deleted.length === 1 ? "" : "s"}`); + selectedIdsRef.current = []; + return { deletedIds: deleted.map((shape) => shape.id), deletedCount: deleted.length }; + } + + if (command.action === "create_shape") { + const rawKind = mcpString(params.kind, "box"); + const kind = rawKind === "cube" ? "box" : rawKind; + const width = Math.max(MIN_SHAPE_DIMENSION, mcpNumber(params.width ?? params.size, 20)); + const depth = Math.max(MIN_SHAPE_DIMENSION, mcpNumber(params.depth ?? params.size, rawKind === "cube" ? width : 20)); + const height = Math.max(MIN_SHAPE_DIMENSION, mcpNumber(params.height ?? params.size, rawKind === "cube" ? width : 20)); + const x = mcpNumber(params.x, 0); + const z = mcpNumber(params.z, 0); + const elevation = mcpNumber(params.elevation, placementElevation); + const color = mcpString(params.color, kind === "cylinder" ? "#d97813" : "#d41721"); + const name = mcpString(params.name, kind === "cylinder" ? "Cylinder" : kind === "sketch" ? "Sketch extrusion" : rawKind === "cube" ? "Cube" : "Box"); + let shape: WorkplaneShape; + if (kind === "sketch") { + const profile = defaultMcpSketchProfile(width, depth); + const extruded = shapeFromSketchProfile(profile, height); + if (!extruded) throw new Error("Could not create the sketch profile"); + shape = canonicalizeShape({ ...extruded, name, color, x, z, elevation, rotation: mcpNumber(params.rotation, 0) }); + } else if (kind === "box" || kind === "cylinder") { + shape = sceneShape({ + name, + kind, + color, + x, + z, + elevation, + width, + depth, + height, + size: Math.max(width, depth), + rotation: mcpNumber(params.rotation, 0), + rotationX: mcpNumber(params.rotationX, 0), + rotationZ: mcpNumber(params.rotationZ, 0), + sides: kind === "cylinder" ? Math.max(3, Math.floor(mcpNumber(params.sides, 96))) : undefined, + }); + } else { + throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch"); + } + commitShapes([...currentShapes(), shape], shape.id, `${shape.name} added by MCP`); + return { object: mcpShapeSummary(shape) }; + } + + if (command.action === "import_mesh") { + const positions = mcpFiniteNumberArray(params.positions); + const normals = mcpFiniteNumberArray(params.normals); + if (positions.length < 9 || positions.length % 9 !== 0) { + throw new Error("import_mesh requires positions as triangle xyz values"); + } + let minX = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + let minZ = Number.POSITIVE_INFINITY; + let maxZ = Number.NEGATIVE_INFINITY; + for (let index = 0; index < positions.length; index += 3) { + const x = positions[index]; + const y = positions[index + 1]; + const z = positions[index + 2]; + minX = Math.min(minX, x); + maxX = Math.max(maxX, x); + minY = Math.min(minY, y); + maxY = Math.max(maxY, y); + minZ = Math.min(minZ, z); + maxZ = Math.max(maxZ, z); + } + const width = Math.max(MIN_SHAPE_DIMENSION, mcpNumber(params.width, maxX - minX)); + const depth = Math.max(MIN_SHAPE_DIMENSION, mcpNumber(params.depth, maxZ - minZ)); + const height = Math.max(MIN_SHAPE_DIMENSION, mcpNumber(params.height, maxY - minY)); + const shape = canonicalizeShape({ + id: createLocalId("mcp-imported-mesh"), + name: mcpString(params.name, "Imported mesh"), + kind: "mesh", + color: mcpString(params.color, "#9bd7f0"), + x: mcpNumber(params.x, 0), + z: mcpNumber(params.z, 0), + elevation: mcpNumber(params.elevation, 0), + size: Math.max(width, depth), + width, + depth, + height, + rotation: mcpNumber(params.rotation, 0), + rotationX: mcpNumber(params.rotationX, 0), + rotationZ: mcpNumber(params.rotationZ, 0), + importedMesh: { + positions, + normals: normals.length === positions.length ? normals : undefined, + baseWidth: width, + baseDepth: depth, + baseHeight: height, + triangleCount: Math.floor(positions.length / 9), + sourceFormat: "json", + }, + locked: false, + hidden: false, + } satisfies WorkplaneShape); + commitShapes([...currentShapes(), shape], shape.id, `${shape.name} imported by MCP`); + return { object: mcpShapeSummary(shape) }; + } + + if (command.action === "update_object") { + const target = findShape(params.id); + if (!target) throw new Error("Object not found"); + if (target.locked) throw new Error("Unlock the object before updating it"); + const patch: ShapeUpdatePatch = {}; + (["x", "z", "elevation", "width", "depth", "height", "size", "rotation", "rotationX", "rotationZ"] as const).forEach((key) => { + if (typeof params[key] === "number" && Number.isFinite(params[key])) { + patch[key] = params[key]; + } + }); + if (typeof params.color === "string") patch.color = params.color; + if (typeof params.name === "string") patch.name = params.name; + if (typeof params.hole === "boolean") patch.hole = params.hole; + const nextShapes = currentShapes().map((shape) => { + if (shape.id !== target.id) return shape; + const patched = { ...shape, ...cleanShapePatch(patch) }; + const width = shapeWidth(patched); + const depth = shapeDepth(patched); + return canonicalizeShape({ ...patched, size: Math.max(width, depth) }); + }); + const updated = nextShapes.find((shape) => shape.id === target.id) as WorkplaneShape; + commitShapes(nextShapes, target.id, `${updated.name} updated by MCP`); + return { object: mcpShapeSummary(updated) }; + } + + if (command.action === "align_objects") { + const axis = params.axis === "x" || params.axis === "y" || params.axis === "z" ? params.axis : null; + const target = params.target === "min" || params.target === "center" || params.target === "max" ? params.target : null; + if (!axis || !target) throw new Error("align_objects requires axis x/y/z and target min/center/max"); + const requestedIds = mcpStringArray(params.ids); + const ids = requestedIds.length ? requestedIds : selectedIdsRef.current; + const selectedForAlign = currentShapes().filter((shape) => ids.includes(shape.id)); + if (selectedForAlign.length < 2) throw new Error("Select at least two objects to align"); + const validIds = selectedForAlign.map((shape) => shape.id); + const requestedAnchorId = typeof params.anchorId === "string" ? params.anchorId : null; + const anchorId = effectiveAlignmentAnchorId(selectedForAlign, requestedAnchorId); + const { nextShapes, moved } = alignedShapesForSelection(currentShapes(), validIds, selectedForAlign, anchorId, axis, target); + if (moved === 0) { + setSelectedIds(validIds); + selectedIdsRef.current = validIds; + setNotice(`MCP alignment already ${alignmentLabel(axis, target)}`); + return { + moved, + selectedIds: validIds, + anchorId, + objects: selectedForAlign.map(mcpShapeSummary), + }; + } + commitShapes(nextShapes, validIds, `MCP aligned ${moved} object${moved === 1 ? "" : "s"} ${alignmentLabel(axis, target)}`); + return { + moved, + selectedIds: validIds, + anchorId, + objects: nextShapes.filter((shape) => validIds.includes(shape.id)).map(mcpShapeSummary), + }; + } + + if (command.action === "group_objects") { + const ids = new Set(mcpStringArray(params.ids)); + const groupable = currentShapes().filter((shape) => ids.has(shape.id)); + if (groupable.length < 2) throw new Error("Select at least two objects to group"); + if (groupable.some((shape) => shape.locked)) throw new Error("Unlock every selected object before grouping"); + const result = await buildGroupedShapeFromSelection(groupable); + if (!result.group) { + if (result.consumed) { + commitShapes(currentShapes().filter((shape) => !ids.has(shape.id)), null, "MCP group consumed solid"); + return { consumed: true, objects: currentShapes().filter((shape) => !ids.has(shape.id)).map(mcpShapeSummary) }; + } + throw new Error(result.failureNotice); + } + commitShapes([...currentShapes().filter((shape) => !ids.has(shape.id)), result.group], result.group.id, `MCP grouped ${groupable.length} objects`); + return { object: mcpShapeSummary(result.group) }; + } + + if (command.action === "ungroup_objects") { + const requestedIds = mcpStringArray(params.ids ?? params.id); + const ids = requestedIds.length ? new Set(requestedIds) : new Set(selectedIdsRef.current); + const groups = currentShapes().filter((shape) => ids.has(shape.id) && shape.groupedShapes?.length); + if (groups.length === 0) throw new Error("Select at least one group to ungroup"); + const groupIds = new Set(groups.map((shape) => shape.id)); + const restored = groups.flatMap(restoreGroupedChildren); + commitShapes([...currentShapes().filter((shape) => !groupIds.has(shape.id)), ...restored], restored.map((shape) => shape.id), `MCP ungrouped ${groups.length} group${groups.length === 1 ? "" : "s"}`); + return { objects: restored.map(mcpShapeSummary) }; + } + + if (command.action === "boolean_cut") { + const solidIds = new Set(mcpStringArray(params.solidIds ?? params.solids)); + const holeIds = new Set(mcpStringArray(params.holeIds ?? params.holes)); + const operandIds = new Set([...solidIds, ...holeIds]); + const operands = currentShapes() + .filter((shape) => operandIds.has(shape.id)) + .map((shape) => holeIds.has(shape.id) ? withHoleMode(shape, true) : withHoleMode(shape, false)); + if (!operands.some((shape) => !shape.hole) || !operands.some((shape) => shape.hole)) { + throw new Error("Provide at least one solidId and one holeId for boolean_cut"); + } + if (operands.some((shape) => shape.locked)) { + throw new Error("Unlock every boolean operand before cutting"); + } + const result = await buildGroupedShapeFromSelection(operands); + const remainingShapes = currentShapes().filter((shape) => !operandIds.has(shape.id)); + if (result.consumed) { + commitShapes(remainingShapes, null, "MCP cut consumed solid"); + return { consumed: true }; + } + if (!result.group) { + throw new Error(result.failureNotice); + } + commitShapes([...remainingShapes, result.group], result.group.id, "MCP boolean cut complete"); + return { object: mcpShapeSummary(result.group) }; + } + + if (command.action === "separate_parts") { + const target = findShape(params.id) ?? (selectedIdsRef.current.length === 1 ? findShape(selectedIdsRef.current[0]) : null); + if (!target) throw new Error("Select one object to separate"); + if (target.locked) throw new Error("Unlock the object before separating parts"); + const parts = separateShapeParts(target); + if (parts.length <= 1) throw new Error("The selected object has only one connected part"); + commitShapes([...currentShapes().filter((shape) => shape.id !== target.id), ...parts], parts.map((shape) => shape.id), `MCP separated ${parts.length} parts`); + return { objects: parts.map(mcpShapeSummary) }; + } + + if (command.action === "list_edges") { + const target = findShape(params.id); + if (!target) throw new Error("Object not found"); + invalidateCadModifierSession(); + const sharpAngle = Math.max(1, Math.min(120, mcpNumber(params.sharpAngle, 25))); + const { response } = await prepareCadModifierForMcp(target, sharpAngle); + const selectableEdgeIds = response.edges.filter((edge) => selectableCadModifierEdge(edge, sharpAngle)).map((edge) => edge.id); + return { object: mcpShapeSummary(target), sharpAngle, selectableEdgeIds, edges: response.edges }; + } + + if (command.action === "apply_edge_treatment") { + const target = findShape(params.id); + if (!target) throw new Error("Object not found"); + return applyCadModifierForMcp(target, params); + } + + if (command.action === "inspect_errors") { + return { + notice: noticeRef.current, + edgeModifierError: edgeModifierRef.current?.error ?? null, + lastMcpError: lastMcpErrorRef.current, + }; + } + + if (command.action === "capture_image") { + const face = mcpString(params.face, "current") as SketchForgeMcpViewFace; + const image = await (window.sketchforgeCaptureView?.(face) ?? window.sketchforgeCaptureCanvas?.() ?? ""); + if (!image || image.length < 100) { + throw new Error("The SketchForge viewport did not return an image"); + } + return { face, dataUrl: image, bytesApprox: Math.floor(image.length * 0.75) }; + } + + throw new Error(`Unknown MCP command: ${command.action}`); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + lastMcpErrorRef.current = message; + setNotice(message); + throw error; + } + }, [ + applyCadModifierForMcp, + commitShapes, + initialSnap, + invalidateCadModifierSession, + mcpSceneSnapshot, + placementElevation, + prepareCadModifierForMcp, + ]); + + useEffect(() => { + executeMcpCommandRef.current = executeMcpCommand; + }, [executeMcpCommand]); + + useEffect(() => { + if (process.env.NODE_ENV === "production" || typeof window === "undefined") { + return; + } + if (!["localhost", "127.0.0.1", "::1"].includes(window.location.hostname)) { + return; + } + + const identity = readMcpEditorIdentity(); + let stopped = false; + let polling = false; + + const heartbeat = () => { + const projectInfo = projectInfoRef.current; + const currentShapes = shapesRef.current; + void fetch(SKETCHFORGE_MCP_ROUTE, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + type: "heartbeat", + editor: { + ...identity, + projectId: projectInfo.projectId, + projectName: projectInfo.projectName, + url: window.location.href, + focused: document.visibilityState === "visible" && document.hasFocus(), + shapeCount: currentShapes.length, + selectedCount: selectedIdsRef.current.length, + notice: noticeRef.current, + lastError: edgeModifierRef.current?.error ?? lastMcpErrorRef.current, + }, + }), + }).catch(() => undefined); + }; + + const submitResult = (commandId: string, ok: boolean, data?: unknown, error?: string) => { + void fetch(SKETCHFORGE_MCP_ROUTE, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + type: "result", + editorId: identity.editorId, + result: { commandId, ok, data, error, completedAt: Date.now() }, + }), + }).catch(() => undefined); + }; + + const poll = async () => { + if (polling || stopped) return; + polling = true; + try { + const response = await fetch(SKETCHFORGE_MCP_ROUTE, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ type: "poll", editorId: identity.editorId }), + }); + const payload = (await response.json().catch(() => null)) as { command?: SketchForgeMcpCommand | null } | null; + const command = payload?.command; + if (command) { + try { + const data = await executeMcpCommandRef.current?.(command); + submitResult(command.id, true, data); + } catch (error) { + submitResult(command.id, false, undefined, error instanceof Error ? error.message : String(error)); + } + } + } catch { + // The local bridge may not exist while static builds or tests render the editor. + } finally { + polling = false; + } + }; + + heartbeat(); + void poll(); + const heartbeatTimer = window.setInterval(heartbeat, 1000); + const pollTimer = window.setInterval(() => void poll(), SKETCHFORGE_MCP_POLL_MS); + window.addEventListener("focus", heartbeat); + document.addEventListener("visibilitychange", heartbeat); + return () => { + stopped = true; + window.clearInterval(heartbeatTimer); + window.clearInterval(pollTimer); + window.removeEventListener("focus", heartbeat); + document.removeEventListener("visibilitychange", heartbeat); + }; + }, []); + useEffect(() => { if (process.env.NODE_ENV === "production" || typeof window === "undefined") { return; @@ -6820,6 +7897,7 @@ export function SketchForgeEditor({ activePointId={sketchActivePointId} selected={sketchSelection} measurement={sketchMeasurement} + pendingMeasurementStart={sketchMeasureStart} initialSnap={initialSnap} initialWorkspace={initialWorkspace} onPlanePoint={addSketchPlanePoint} @@ -6876,6 +7954,8 @@ export function SketchForgeEditor({ onSetPlacementElevation={setPlacementWorkplane} onInteractionActiveChange={updateProjectInteractionActive} onEditSketch={beginSketchEdit} + canSeparateParts={canSeparateSelectedParts} + onSeparateParts={separateSelectedParts} onUpdateShape={updateShape} onWorkspaceSettingsChange={updateProjectWorkspaceSettings} onWorkplaneModeChange={setWorkplaneMode} @@ -6895,24 +7975,26 @@ export function SketchForgeEditor({ chamferAngle={edgeModifier.chamferAngle} quality={edgeModifier.quality} sharpAngle={edgeModifier.sharpAngle} + workspace={workspaceSettings} tangentChain={edgeModifier.tangentChain} preserveEdgeSize={edgeModifier.preserveEdgeSize} targetName={selectedShape?.name ?? "Object"} groupedCount={selectedShape?.groupedShapes?.length ?? 0} appliedFeatureCount={selectedEdgeFeatureCount} reversibleFeatureCount={selectedReversibleEdgeFeatureCount} + historyOptions={selectedEdgeHistoryOptions} selectedCount={edgeModifier.selectedEdgeIds.length} availableCount={modifierAvailableEdgeIds.length} busy={edgeModifier.busy} error={edgeModifier.error} - onAmountChange={(value) => setEdgeModifier((current) => current ? { ...current, amount: Math.max(0.05, Math.min(edgeModifierMaxAmount, value)), preview: null, busy: true, error: null } : current)} + 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)} onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => { if (!current) return current; const nextAngle = Math.max(1, Math.min(120, sharpAngle)); const availableIds = new Set(current.edges - .filter((edge) => edge.manifold && !edge.boundary && edge.angle + 1e-3 >= nextAngle) + .filter((edge) => selectableCadModifierEdge(edge, nextAngle)) .map((edge) => edge.id)); const selectedEdgeIds = current.selectedEdgeIds.filter((edgeId) => availableIds.has(edgeId)); return { @@ -6928,7 +8010,7 @@ export function SketchForgeEditor({ 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)} - onRemoveLastFeature={removeLastEdgeTreatment} + onRemoveFeature={removeEdgeTreatment} onApply={applyEdgeModifier} onCancel={cancelEdgeModifier} /> @@ -6983,6 +8065,34 @@ export function SketchForgeEditor({ ); } +const sketchReferenceIcons = { + line: "sketch-tool-line.png", + bezier: "sketch-tool-bezier-curve.png", + smooth: "sketch-tool-smooth-curve.png", + select: "sketch-tool-select.png", + image: "sketch-tool-add-image.png", + refine: "sketch-tool-add-or-remove-points.png", + erase: "sketch-tool-erase.png", + measure: "sketch-tool-measure.png", + sketchTo3d: "sketch-tool-sketch-to-3d.png", + editSketchTo3d: "sketch-tool-edit-sketch-to-3d.png", +} as const; + +type SketchReferenceIconName = keyof typeof sketchReferenceIcons; + +function SketchReferenceIcon({ name }: { name: SketchReferenceIconName }) { + return ( + + ); +} + function SecondaryToolbar({ toolbarMode, onToolbarModeChange, @@ -7104,21 +8214,27 @@ function SecondaryToolbar({ { label: "Undo", icon: ToolbarUndoIcon, action: onUndo, enabled: canUndo }, { label: "Redo", icon: ToolbarRedoIcon, action: onRedo, enabled: canRedo }, ]; - const rightTools = [ + const visibilityTools = [ { label: "Hide selected", icon: ToolbarHideSelectedIcon, action: onToggleHidden, enabled: hasSelection }, { label: "Visibility options", icon: ToolbarCaretDownIcon, action: onTips, enabled: hasSelection }, + ]; + const combineTools = [ { label: "Group", icon: ToolbarGroupIcon, action: onGroup, enabled: canGroup }, { label: "Ungroup", icon: ToolbarUngroupIcon, action: onUngroup, enabled: canUngroup }, { label: "Boolean Intersection", icon: ToolbarIntersectionIcon, action: onIntersect, enabled: canIntersect }, + ]; + const modifyTools = [ { label: "Align", icon: ToolbarAlignIcon, action: onAlign, enabled: canAlign, active: alignMode }, { label: "Mirror", icon: ToolbarMirrorIcon, action: onMirror, enabled: hasSelection, active: mirrorMode }, { label: "Snap to grid", icon: ToolbarSnapGridIcon, action: onSnap, enabled: hasSelection }, { label: "Chamfer", icon: ToolbarChamferIcon, action: onChamfer, enabled: canEdgeModify, active: edgeModifierKind === "chamfer" }, { label: "Fillet", icon: ToolbarFilletIcon, action: onFillet, enabled: canEdgeModify, active: edgeModifierKind === "fillet" }, + ]; + const arrangeTools = [ { label: "Workplane", icon: ToolbarWorkplaneIcon, action: onWorkplaneTool, enabled: true, active: workplaneMode }, { label: "Drop to workplane", icon: ToolbarDropToWorkplaneIcon, action: onDropToWorkplane, enabled: hasSelection }, ]; - const renderToolButton = (tool: (typeof leftTools)[number] | (typeof rightTools)[number]) => { + const renderToolButton = (tool: (typeof leftTools)[number] | (typeof visibilityTools)[number] | (typeof combineTools)[number] | (typeof modifyTools)[number] | (typeof arrangeTools)[number]) => { const { icon: Icon, action, enabled, label } = tool; const active = "active" in tool && Boolean(tool.active); return ( @@ -7242,19 +8358,19 @@ function SecondaryToolbar({
Visibility
-
{rightTools.slice(0, 2).map(renderToolButton)}
+
{visibilityTools.map(renderToolButton)}
Combine
-
{rightTools.slice(2, 5).map(renderToolButton)}
+
{combineTools.map(renderToolButton)}
Modify
-
{rightTools.slice(5, 10).map(renderToolButton)}
+
{modifyTools.map(renderToolButton)}
Arrange
-
{rightTools.slice(10).map(renderToolButton)}
+
{arrangeTools.map(renderToolButton)}
@@ -7280,13 +8396,13 @@ function SecondaryToolbar({
Draw
- -
@@ -7294,23 +8410,23 @@ function SecondaryToolbar({
Select
-
@@ -7329,7 +8445,7 @@ function SecondaryToolbar({
Inspect
@@ -7353,11 +8469,11 @@ function SecondaryToolbar({
Create
-
diff --git a/apps/web/src/components/SketchWorkspace.tsx b/apps/web/src/components/SketchWorkspace.tsx index be06064..0e8fbd6 100644 --- a/apps/web/src/components/SketchWorkspace.tsx +++ b/apps/web/src/components/SketchWorkspace.tsx @@ -3,6 +3,7 @@ import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react"; import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react"; import { SnapGridControl } from "@/components/workplane/ShapeInspector"; +import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; import type { GridSize, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; @@ -22,6 +23,7 @@ type SketchWorkspaceProps = { activePointId: string | null; selected: SketchSelection; measurement: SketchMeasurement; + pendingMeasurementStart: SketchPoint | null; initialSnap?: GridSize; initialWorkspace?: WorkplaneWorkspaceSettings; onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void; @@ -42,6 +44,7 @@ type SketchWorkspaceProps = { type PathStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint }; type DisplayPath = { id: string; points: SketchPoint[]; steps: PathStep[]; closed: boolean }; +type SketchReferenceFootprint = { fillD: string | null; outlineD: string | null }; type PointerAction = | { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } } | { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } } @@ -123,6 +126,14 @@ function formatDimension(value: number, accuracy: 1 | 2 | 3) { return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy); } +function dimensionPillSize(label: string, screenUnit: number, extra = 24) { + return { + width: Math.max(48, label.length * 7.5 + extra) * screenUnit, + height: 26 * screenUnit, + radius: 5 * screenUnit, + }; +} + function cubicPoint(start: SketchPoint, first: { x: number; z: number }, second: { x: number; z: number }, end: SketchPoint, amount: number) { const inverse = 1 - amount; return { @@ -239,6 +250,152 @@ function isRoundReference(shape: WorkplaneShape) { return ["cylinder", "sphere", "cone", "torus", "tube", "ring", "halfSphere"].includes(shape.kind); } +function sketchReferencePoint(shape: WorkplaneShape, x: number, z: number) { + return { + x: shape.x + x * mirrorSign(shape.mirrorX), + z: shape.z + z * mirrorSign(shape.mirrorZ), + }; +} + +function pointKey(point: { x: number; z: number }, tolerance: number) { + return `${Math.round(point.x / tolerance)},${Math.round(point.z / tolerance)}`; +} + +function triangleArea2d(a: { x: number; z: number }, b: { x: number; z: number }, c: { x: number; z: number }) { + return Math.abs((b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z)) / 2; +} + +function trianglePath(points: Array<{ x: number; z: number }>) { + return `M ${points[0].x} ${points[0].z} L ${points[1].x} ${points[1].z} L ${points[2].x} ${points[2].z} Z`; +} + +function convexHull(points: Array<{ x: number; z: number }>) { + const unique = new Map(); + points.forEach((point) => unique.set(pointKey(point, 0.001), point)); + const sorted = [...unique.values()].sort((a, b) => a.x === b.x ? a.z - b.z : a.x - b.x); + if (sorted.length <= 2) return sorted; + const cross = (origin: { x: number; z: number }, a: { x: number; z: number }, b: { x: number; z: number }) => + (a.x - origin.x) * (b.z - origin.z) - (a.z - origin.z) * (b.x - origin.x); + const lower: Array<{ x: number; z: number }> = []; + sorted.forEach((point) => { + while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], point) <= 0) lower.pop(); + lower.push(point); + }); + const upper: Array<{ x: number; z: number }> = []; + [...sorted].reverse().forEach((point) => { + while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], point) <= 0) upper.pop(); + upper.push(point); + }); + lower.pop(); + upper.pop(); + return [...lower, ...upper]; +} + +function boundaryPath(points: Array<{ x: number; z: number }>, triangles: number[][], tolerance: number) { + const pointByKey = new Map(); + const edgeCounts = new Map(); + const addEdge = (aIndex: number, bIndex: number) => { + const a = points[aIndex]; + const b = points[bIndex]; + const aKey = pointKey(a, tolerance); + const bKey = pointKey(b, tolerance); + pointByKey.set(aKey, a); + pointByKey.set(bKey, b); + const key = aKey < bKey ? `${aKey}|${bKey}` : `${bKey}|${aKey}`; + const current = edgeCounts.get(key); + edgeCounts.set(key, current ? { ...current, count: current.count + 1 } : { count: 1, a: aKey, b: bKey }); + }; + triangles.forEach(([a, b, c]) => { + addEdge(a, b); + addEdge(b, c); + addEdge(c, a); + }); + + const boundaryEdges = [...edgeCounts.values()].filter((edge) => edge.count === 1); + if (boundaryEdges.length === 0) return null; + const adjacency = new Map(); + boundaryEdges.forEach(({ a, b }) => { + adjacency.set(a, [...(adjacency.get(a) ?? []), b]); + adjacency.set(b, [...(adjacency.get(b) ?? []), a]); + }); + const unused = new Set(boundaryEdges.map(({ a, b }) => (a < b ? `${a}|${b}` : `${b}|${a}`))); + const takeEdge = (a: string, b: string) => unused.delete(a < b ? `${a}|${b}` : `${b}|${a}`); + const hasEdge = (a: string, b: string) => unused.has(a < b ? `${a}|${b}` : `${b}|${a}`); + const commands: string[] = []; + + while (unused.size > 0) { + const firstKey = unused.values().next().value as string; + const [start, firstNext] = firstKey.split("|"); + const chain = [start, firstNext]; + takeEdge(start, firstNext); + while (chain.length <= boundaryEdges.length + 1) { + const current = chain[chain.length - 1]; + const previous = chain[chain.length - 2]; + const next = (adjacency.get(current) ?? []).find((candidate) => candidate !== previous && hasEdge(current, candidate)) + ?? (adjacency.get(current) ?? []).find((candidate) => hasEdge(current, candidate)); + if (!next) break; + takeEdge(current, next); + chain.push(next); + if (next === start) break; + } + const startPoint = pointByKey.get(chain[0]); + if (!startPoint) continue; + const pointsD = chain + .slice(1) + .map((key) => pointByKey.get(key)) + .filter((point): point is { x: number; z: number } => Boolean(point)) + .map((point) => `L ${point.x} ${point.z}`); + commands.push(`M ${startPoint.x} ${startPoint.z} ${pointsD.join(" ")}${chain[chain.length - 1] === chain[0] ? " Z" : ""}`); + } + + return commands.join(" "); +} + +function importedMeshFootprint(shape: WorkplaneShape): SketchReferenceFootprint | null { + if (!shape.importedMesh) return null; + const positions = resizedImportedMeshPositions(shape); + if (positions.length < 9) return null; + let minY = Number.POSITIVE_INFINITY; + for (let index = 1; index < positions.length; index += 3) { + minY = Math.min(minY, positions[index]); + } + if (!Number.isFinite(minY)) return null; + + const tolerance = Math.max(0.001, Math.max(shape.width, shape.depth, shape.height) / 100000); + const bottomTolerance = Math.max(0.025, shape.height * 0.003); + const points: Array<{ x: number; z: number }> = []; + const triangles: number[][] = []; + const allProjected: Array<{ x: number; z: number }> = []; + + for (let index = 0; index + 8 < positions.length; index += 9) { + const ys = [positions[index + 1], positions[index + 4], positions[index + 7]]; + const projected = [ + sketchReferencePoint(shape, positions[index], positions[index + 2]), + sketchReferencePoint(shape, positions[index + 3], positions[index + 5]), + sketchReferencePoint(shape, positions[index + 6], positions[index + 8]), + ]; + allProjected.push(...projected); + if (!ys.every((value) => value <= minY + bottomTolerance) || triangleArea2d(projected[0], projected[1], projected[2]) <= tolerance) { + continue; + } + const offset = points.length; + points.push(...projected); + triangles.push([offset, offset + 1, offset + 2]); + } + + if (triangles.length > 0) { + return { + fillD: triangles.length <= 5000 ? triangles.map((triangle) => trianglePath(triangle.map((index) => points[index]))).join(" ") : null, + outlineD: boundaryPath(points, triangles, tolerance), + }; + } + + const hull = convexHull(allProjected); + if (hull.length < 3) return null; + const d = `M ${hull[0].x} ${hull[0].z} ${hull.slice(1).map((point) => `L ${point.x} ${point.z}`).join(" ")} Z`; + return { fillD: d, outlineD: d }; +} + export function SketchWorkspace({ profile, referenceShapes, @@ -246,6 +403,7 @@ export function SketchWorkspace({ activePointId, selected, measurement, + pendingMeasurementStart, initialSnap, initialWorkspace, onPlanePoint, @@ -270,9 +428,17 @@ export function SketchWorkspace({ const [pan, setPan] = useState({ x: 0, z: 0 }); const [hover, setHover] = useState<{ x: number; z: number } | null>(null); const [pointerAction, setPointerAction] = useState(null); + const [svgSize, setSvgSize] = useState({ width: 0, height: 0 }); const svgRef = useRef(null); const width = workspace.width / zoom; const depth = workspace.depth / zoom; + const screenUnit = useMemo(() => { + const fittedScale = Math.min( + svgSize.width > 0 ? svgSize.width / width : 0, + svgSize.height > 0 ? svgSize.height / depth : 0, + ); + return fittedScale > 0 ? 1 / fittedScale : Math.max(width, depth) / 720; + }, [depth, svgSize.height, svgSize.width, width]); const displayProfile = useMemo(() => { if (pointerAction?.kind === "move-point") { const source = profile.points.find((point) => point.id === pointerAction.pointId); @@ -356,6 +522,19 @@ export function SketchWorkspace({ }; }; + useEffect(() => { + const svg = svgRef.current; + if (!svg) return; + const updateSize = () => { + const bounds = svg.getBoundingClientRect(); + setSvgSize({ width: bounds.width, height: bounds.height }); + }; + updateSize(); + const observer = new ResizeObserver(updateSize); + observer.observe(svg); + return () => observer.disconnect(); + }, []); + const beginPan = (event: ReactPointerEvent) => { event.preventDefault(); event.stopPropagation(); @@ -472,7 +651,12 @@ export function SketchWorkspace({ const measurementLabel = formatDimension(measurementLength, workspace.accuracy); const previewLength = activePoint && hover ? Math.hypot(hover.x - activePoint.x, hover.z - activePoint.z) : 0; const previewLabel = formatDimension(previewLength, workspace.accuracy); - const pillScale = 1 / zoom; + const labelOffset = 22 * screenUnit; + const pointRadius = 5 * screenUnit; + const controlPointRadius = 6 * screenUnit; + const hoverPointRadius = 5 * screenUnit; + const handleSize = 12 * screenUnit; + const handleRadius = 2 * screenUnit; const selectedImageBounds = selectedImage ? { minX: selectedImage.x - selectedImage.width / 2, maxX: selectedImage.x + selectedImage.width / 2, @@ -489,6 +673,10 @@ export function SketchWorkspace({ { id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ }, { id: "w", x: selectedImageBounds.minX, z: selectedImage.z }, ] : []; + const referenceFootprints = useMemo( + () => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])), + [referenceShapes], + ); return (
@@ -556,15 +744,23 @@ export function SketchWorkspace({ ))} - {referenceShapes.filter((shape) => !shape.hidden).map((shape) => ( - - {isRoundReference(shape) ? ( - - ) : ( - - )} - - ))} + {referenceShapes.filter((shape) => !shape.hidden).map((shape) => { + const footprint = referenceFootprints.get(shape.id); + return ( + + {footprint?.fillD || footprint?.outlineD ? ( + <> + {footprint.fillD ? : null} + {footprint.outlineD ? : null} + + ) : isRoundReference(shape) ? ( + + ) : ( + + )} + + ); + })} {pointerAction?.kind === "marquee" ? ( @@ -604,53 +800,68 @@ export function SketchWorkspace({ const dimension = segmentDimension(segment, pointById); if (!dimension) return null; const label = formatDimension(dimension.length, workspace.accuracy); - const pillWidth = Math.max(7.2, label.length * 1.2 + 2.4) * pillScale; - const pillHeight = 4.2 * pillScale; + const pill = dimensionPillSize(label, screenUnit, 18); return ( - - - {label} + + + {label} ); })} {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? : null} {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? ( - - - {previewLabel} + + {(() => { + const pill = dimensionPillSize(previewLabel, screenUnit, 18); + return ( + <> + + {previewLabel} + + ); + })()} ) : null} {pointerAction?.kind === "bezier" ? ( - + ) : null} {measurement ? ( + + { event.preventDefault(); event.stopPropagation(); onClearMeasurement(); }} > - - {measurementLabel} - × + + {measurementLabel} + x ) : null} + {pendingMeasurementStart ? ( + + {hover ? : null} + + {hover ? : null} + + ) : null} {selectedPoint && tool === "select" ? ( - {selectedPoint.handleIn ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /> : null} - {selectedPoint.handleOut ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /> : null} + {selectedPoint.handleIn ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /> : null} + {selectedPoint.handleOut ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /> : null} ) : null} @@ -661,7 +872,7 @@ export function SketchWorkspace({ key={point.id} cx={point.x} cy={point.z} - r={0.82 / Math.sqrt(zoom)} + r={pointRadius} onPointerDown={(event) => { event.preventDefault(); event.stopPropagation(); @@ -689,24 +900,40 @@ export function SketchWorkspace({ height={selectedImage.depth} pointerEvents="none" /> - - - {formatDimension(selectedImage.width, workspace.accuracy)} + + {(() => { + const label = formatDimension(selectedImage.width, workspace.accuracy); + const pill = dimensionPillSize(label, screenUnit, 18); + return ( + <> + + {label} + + ); + })()} - - - {formatDimension(selectedImage.depth, workspace.accuracy)} + + {(() => { + const label = formatDimension(selectedImage.depth, workspace.accuracy); + const pill = dimensionPillSize(label, screenUnit, 18); + return ( + <> + + {label} + + ); + })()} {imageResizeHandles.map((handle) => ( { if (event.button === 1) { beginPan(event); @@ -728,7 +955,7 @@ export function SketchWorkspace({ ))} ) : null} - {hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? : null} + {hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? : null} {selectedImage && tool === "select" ? ( diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 639ed5d..2e327ca 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -19,6 +19,7 @@ import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } fro import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; +import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol"; import { TransformOverlay, getElevationMeasureKey, @@ -89,6 +90,7 @@ const preservedImportedGeometryCache = new WeakMap void; onInteractionActiveChange?: (active: boolean) => void; onEditSketch?: () => void; + canSeparateParts?: boolean; + onSeparateParts?: () => void; onUpdateShape: (id: string, patch: ShapeUpdatePatch) => void; onWorkspaceSettingsChange?: (settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void; onWorkplaneModeChange: (active: boolean) => void; @@ -219,6 +223,7 @@ declare global { get: () => ViewportPerfStats; }; sketchforgeCaptureCanvas?: () => string; + sketchforgeCaptureView?: (face?: SketchForgeMcpViewFace) => Promise | string; } } @@ -523,6 +528,51 @@ function projectToScreen(point: THREE.Vector3, state: ThreeState) { }; } +function distanceToScreenSegment(x: number, y: number, ax: number, ay: number, bx: number, by: number) { + const dx = bx - ax; + const dy = by - ay; + const lengthSq = dx * dx + dy * dy; + const amount = lengthSq > 0.0001 ? clamp(((x - ax) * dx + (y - ay) * dy) / lengthSq, 0, 1) : 0; + return Math.hypot(x - (ax + dx * amount), y - (ay + dy * amount)); +} + +function projectCadPointToCanvas(point: THREE.Vector3, state: ThreeState, rect: DOMRect) { + const projected = point.clone().project(state.camera); + if (!Number.isFinite(projected.x) || !Number.isFinite(projected.y) || projected.z < -1 || projected.z > 1) { + return null; + } + return { + x: ((projected.x + 1) / 2) * rect.width, + y: ((1 - projected.y) / 2) * rect.height, + }; +} + +function pickModifierEdgeFromScreen(state: ThreeState, edges: CadModifierEdge[], clientX: number, clientY: number) { + const rect = state.renderer.domElement.getBoundingClientRect(); + const pointerX = clientX - rect.left; + const pointerY = clientY - rect.top; + const pointA = new THREE.Vector3(); + const pointB = new THREE.Vector3(); + let nearestId: number | null = null; + let nearestDistance = MODIFIER_EDGE_PICK_RADIUS_PX; + state.camera.updateMatrixWorld(); + edges.forEach((edge) => { + for (let index = 0; index + 5 < edge.points.length; index += 3) { + pointA.set(edge.points[index], edge.points[index + 1], edge.points[index + 2]); + pointB.set(edge.points[index + 3], edge.points[index + 4], edge.points[index + 5]); + const a = projectCadPointToCanvas(pointA, state, rect); + const b = projectCadPointToCanvas(pointB, state, rect); + if (!a || !b) continue; + const distance = distanceToScreenSegment(pointerX, pointerY, a.x, a.y, b.x, b.y); + if (distance < nearestDistance) { + nearestDistance = distance; + nearestId = edge.id; + } + } + }); + return nearestId; +} + function syncRulerOverlay( state: ThreeState, model: RulerModel, @@ -1112,6 +1162,8 @@ export function WorkplaneViewport({ onSetPlacementElevation, onInteractionActiveChange, onEditSketch, + canSeparateParts = false, + onSeparateParts, onUpdateShape, onWorkspaceSettingsChange, onWorkplaneModeChange, @@ -1170,6 +1222,8 @@ export function WorkplaneViewport({ const mirrorModeRef = useRef(mirrorMode); const modifierActiveRef = useRef(modifierActive); const modifierPreviewActiveRef = useRef(modifierPreviewActive); + const modifierEdgesRef = useRef(modifierEdges); + const [hoverModifierEdgeId, setHoverModifierEdgeId] = useState(null); const selectedIdsKeyRef = useRef(selectedIds.join("|")); const perfRef = useRef({ fps: 0, @@ -1186,8 +1240,9 @@ export function WorkplaneViewport({ ); useEffect(() => { - rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive); - }, [modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]); + modifierEdgesRef.current = modifierEdges; + rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive, hoverModifierEdgeId); + }, [hoverModifierEdgeId, modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]); const placementElevationRef = useRef(placementElevation); const workplaneModeRef = useRef(workplaneMode); @@ -1259,10 +1314,11 @@ export function WorkplaneViewport({ useEffect(() => { shapesRef.current = shapes; rebuildShapes(threeRef.current, shapes, renderSelectionIds(), !transformRef.current && !dragRef.current); + refreshDragPreviewObjects(threeRef.current, dragRef.current); if (threeRef.current) { syncTransformOverlay( threeRef.current, - shapes, + previewShapesForDrag(shapes, dragRef.current), selectedIdsRef.current, transformOverlayRef, setTransformOverlay, @@ -1306,10 +1362,11 @@ export function WorkplaneViewport({ } selectedIdsRef.current = selectedIds; rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(selectedIds), !transformRef.current && !dragRef.current); + refreshDragPreviewObjects(threeRef.current, dragRef.current); if (threeRef.current) { syncTransformOverlay( threeRef.current, - shapesRef.current, + previewShapesForDrag(shapesRef.current, dragRef.current), selectedIds, transformOverlayRef, setTransformOverlay, @@ -1324,6 +1381,7 @@ export function WorkplaneViewport({ useEffect(() => { modifierActiveRef.current = modifierActive; + if (!modifierActive) setHoverModifierEdgeId(null); rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current); if (threeRef.current) threeRef.current.needsRender = true; }, [modifierActive, renderSelectionIds]); @@ -1334,6 +1392,12 @@ export function WorkplaneViewport({ if (threeRef.current) threeRef.current.needsRender = true; }, [modifierPreviewActive, renderSelectionIds]); + useEffect(() => { + if (hoverModifierEdgeId !== null && !modifierEdges.some((edge) => edge.id === hoverModifierEdgeId)) { + setHoverModifierEdgeId(null); + } + }, [hoverModifierEdgeId, modifierEdges]); + useEffect(() => { alignModeRef.current = alignMode; alignAnchorIdRef.current = alignAnchorId; @@ -1411,6 +1475,17 @@ export function WorkplaneViewport({ state.renderer.render(state.scene, state.camera); return state.renderer.domElement.toDataURL("image/png"); }; + window.sketchforgeCaptureView = (face = "current") => { + if (face === "home") { + resetCamera(state); + } else if (face !== "current") { + setCameraToViewFace(state, face); + } + syncViewCube(state, viewCubeRef.current); + state.camera.updateMatrixWorld(); + state.renderer.render(state.scene, state.camera); + return state.renderer.domElement.toDataURL("image/png"); + }; perfRef.current.lastSample = performance.now(); resetCamera(state); rebuildShapes(state, shapesRef.current, renderSelectionIds()); @@ -1483,6 +1558,9 @@ export function WorkplaneViewport({ if (window.sketchforgeCaptureCanvas) { delete window.sketchforgeCaptureCanvas; } + if (window.sketchforgeCaptureView) { + delete window.sketchforgeCaptureView; + } threeRef.current = null; }; }, []); @@ -2199,14 +2277,16 @@ export function WorkplaneViewport({ const pickModifierEdge = useCallback((clientX: number, clientY: number) => { const state = threeRef.current; if (!state) return null; - const rect = state.renderer.domElement.getBoundingClientRect(); - state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1; - state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1; - state.raycaster.setFromCamera(state.pointer, state.camera); - const hit = state.raycaster - .intersectObjects(state.modifierLayer.children, true) - .find((entry) => typeof entry.object.userData.modifierEdgeId === "number"); - return hit ? hit.object.userData.modifierEdgeId as number : null; + return pickModifierEdgeFromScreen(state, modifierEdgesRef.current, clientX, clientY); + }, []); + + const updateModifierEdgeHover = useCallback((clientX: number, clientY: number) => { + const edgeId = pickModifierEdge(clientX, clientY); + setHoverModifierEdgeId((current) => (current === edgeId ? current : edgeId)); + }, [pickModifierEdge]); + + const clearModifierEdgeHover = useCallback(() => { + setHoverModifierEdgeId((current) => (current === null ? current : null)); }, []); const pickTransformHandle = useCallback((clientX: number, clientY: number) => { @@ -2497,6 +2577,10 @@ export function WorkplaneViewport({ const handlePointerMove = useCallback( (event: ReactPointerEvent) => { + if (modifierActiveRef.current) { + updateModifierEdgeHover(event.clientX, event.clientY); + return; + } if (rulerModeRef.current) { updateRulerHover(event.clientX, event.clientY); return; @@ -2542,21 +2626,7 @@ export function WorkplaneViewport({ drag.items.forEach((item) => { item.nextX = clamp(item.startX + deltaX, -workspaceRef.current.width / 2 + 6, workspaceRef.current.width / 2 - 6); item.nextZ = clamp(item.startZ + deltaZ, -workspaceRef.current.depth / 2 + 6, workspaceRef.current.depth / 2 - 6); - - if (item.visual) { - if (!item.hadPreviewSimplified) { - setComplexEdgeVisibility(item.visual, false); - item.hadPreviewSimplified = true; - } - item.visual.position.x = item.nextX; - item.visual.position.z = item.nextZ; - } - - if (item.helper && item.helperBox) { - item.helper.box.copy(item.helperBox); - item.helper.box.translate(new THREE.Vector3(item.nextX - item.startX, 0, item.nextZ - item.startZ)); - item.helper.updateMatrixWorld(true); - } + if (threeRef.current) applyDragItemPreview(threeRef.current, item); }); if (threeRef.current) { const previewShapes = previewShapesForDrag(shapesRef.current, drag); @@ -2574,9 +2644,13 @@ export function WorkplaneViewport({ threeRef.current.needsRender = true; } }, - [setMarqueeFromState, toPlanePoint, updateRulerHover, updateTransform], + [setMarqueeFromState, toPlanePoint, updateModifierEdgeHover, updateRulerHover, updateTransform], ); + const handlePointerLeave = useCallback(() => { + if (modifierActiveRef.current) clearModifierEdgeHover(); + }, [clearModifierEdgeHover]); + const finishDrag = useCallback( (event: ReactPointerEvent) => { const state = threeRef.current; @@ -2846,7 +2920,7 @@ export function WorkplaneViewport({ -
+
{marqueeRect ?
: null} {transformOverlay && !alignMode && !mirrorMode && !rulerMode && !modifierActive ? ( @@ -2909,12 +2984,14 @@ export function WorkplaneViewport({ shape={selectedShape} snap={snap} snapOpen={snapOpen} - accuracy={workspace.accuracy} + workspace={workspace} onUpdate={(patch, options) => onUpdateShape(selectedShape.id, patchWithResizeAnchor(selectedShape, patch, options?.resizeAxis, lastResizeAnchorRef.current))} onClose={() => onSelectShape(null)} onSnapChange={setSnap} onSnapOpenChange={setSnapOpen} onEditSketch={selectedShape.sketchProfile ? onEditSketch : undefined} + canSeparateParts={canSeparateParts} + onSeparateParts={onSeparateParts} /> ) : null} @@ -3442,7 +3519,16 @@ function rebuildShapes(state: ThreeState | null, shapes: WorkplaneShape[], selec rebuildSelectionHelpers(state, shapes, selectedIds); } -function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[], selectedIds: number[], previewActive = false) { +function modifierEdgeMaterialStyle(active: boolean, hovered: boolean, previewActive: boolean) { + const subduedSelectedPreviewEdge = previewActive && active && !hovered; + return { + color: active ? (hovered ? "#ffbf45" : "#ff8a1d") : hovered ? "#84edff" : "#17b7e5", + opacity: subduedSelectedPreviewEdge ? 0.18 : active || hovered ? 1 : 0.72, + linewidth: active || hovered ? 3 : 1, + }; +} + +function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[], selectedIds: number[], previewActive = false, hoverId: number | null = null) { if (!state) return; disposeChildren(state.modifierLayer); const selected = new Set(selectedIds); @@ -3451,17 +3537,19 @@ function rebuildModifierEdges(state: ThreeState | null, edges: CadModifierEdge[] const geometry = new THREE.BufferGeometry(); geometry.setAttribute("position", new THREE.Float32BufferAttribute(edge.points, 3)); const active = selected.has(edge.id); - const subduedSelectedPreviewEdge = previewActive && active; + const hovered = hoverId === edge.id; + const style = modifierEdgeMaterialStyle(active, hovered, previewActive); const material = new THREE.LineBasicMaterial({ - color: active ? "#ff8a1d" : "#17b7e5", + color: style.color, depthTest: false, depthWrite: false, transparent: true, - opacity: subduedSelectedPreviewEdge ? 0.18 : active ? 1 : 0.82, + opacity: style.opacity, + linewidth: style.linewidth, }); const line = new THREE.Line(geometry, material); line.userData.modifierEdgeId = edge.id; - line.renderOrder = active ? 1002 : 1001; + line.renderOrder = hovered ? 1003 : active ? 1002 : 1001; state.modifierLayer.add(line); }); state.needsRender = true; @@ -4089,6 +4177,39 @@ function findSelectedGroundFootprint(state: ThreeState, id: string) { return state.helperLayer.children.find((child) => child.name === "SelectedGroundFootprint" && child.userData.shapeId === id) ?? null; } +function applyDragItemPreview(state: ThreeState, item: DragItem) { + if (!item.visual || !item.visual.parent) { + item.visual = findShapeObject(state, item.id); + } + if (!item.helper || !item.helper.parent) { + item.helper = findSelectionHelper(state, item.id); + item.helperBox = item.helper ? item.helper.box.clone() : null; + } + + if (item.visual) { + if (!item.hadPreviewSimplified) { + setComplexEdgeVisibility(item.visual, false); + item.hadPreviewSimplified = true; + } + item.visual.position.x = item.nextX; + item.visual.position.z = item.nextZ; + item.visual.updateMatrixWorld(true); + } + + if (item.helper && item.helperBox) { + item.helper.box.copy(item.helperBox); + item.helper.box.translate(new THREE.Vector3(item.nextX - item.startX, 0, item.nextZ - item.startZ)); + item.helper.updateMatrixWorld(true); + } +} + +function refreshDragPreviewObjects(state: ThreeState | null, drag: DragState | null) { + if (!state || !drag) return; + drag.items.forEach((item) => applyDragItemPreview(state, item)); + updateSelectedGroundFootprintPreviews(state, drag); + state.needsRender = true; +} + function updateSelectedGroundFootprintPreviews(state: ThreeState, drag: DragState) { drag.items.forEach((item) => { const footprint = findSelectedGroundFootprint(state, item.id); @@ -4822,8 +4943,9 @@ function createHalfSphereGeometry(width: number, height: number, depth: number, function disposeChildren(group: THREE.Group) { while (group.children.length > 0) { - const child = group.children.pop(); + const child = group.children[group.children.length - 1]; if (child) { + group.remove(child); disposeObject(child); } } diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsx index adbccba..df689d8 100644 --- a/apps/web/src/components/icons.tsx +++ b/apps/web/src/components/icons.tsx @@ -148,24 +148,12 @@ export function ToolbarMirrorIcon() { return ; } -export function ToolbarChamferIcon(props: IconProps) { - return ( - - ); +export function ToolbarChamferIcon() { + return ; } -export function ToolbarFilletIcon(props: IconProps) { - return ( - - ); +export function ToolbarFilletIcon() { + return ; } export function ToolbarPreserveEdgeIcon(props: IconProps) { diff --git a/apps/web/src/components/workplane/EdgeModifierPanel.tsx b/apps/web/src/components/workplane/EdgeModifierPanel.tsx index b2c719d..eeda9ed 100644 --- a/apps/web/src/components/workplane/EdgeModifierPanel.tsx +++ b/apps/web/src/components/workplane/EdgeModifierPanel.tsx @@ -1,7 +1,128 @@ "use client"; -import { Check, LoaderCircle, X } from "lucide-react"; +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 type { WorkplaneWorkspaceSettings } from "@/types/sketchforge"; + +const MIN_EDGE_MODIFIER_AMOUNT = 0.001; +const EDGE_MODIFIER_AMOUNT_STEP = 0.001; + +function clamp(value: number, min: number, max: number) { + return Math.min(max, Math.max(min, value)); +} + +function formatSliderValue(value: number, accuracy: WorkplaneWorkspaceSettings["accuracy"], step: number) { + if (step >= 1) return String(Math.round(value)); + return formatMeasurementNumber(value, accuracy, step); +} + +type EdgeHistoryOption = { + id: string; + label: string; + targetName: string; + removesNewerCount: number; +}; + +function EdgeModifierSlider({ + label, + value, + min, + max, + step, + unit, + workspace, + length = false, + onChange, +}: { + label: string; + value: number; + min: number; + max: number; + step: number; + unit?: string; + workspace: WorkplaneWorkspaceSettings; + length?: boolean; + onChange: (value: number) => void; +}) { + const safeMin = Number.isFinite(min) ? min : 0; + const safeMax = Math.max(safeMin, Number.isFinite(max) ? max : safeMin); + const actualValue = Number.isFinite(value) ? value : safeMin; + const controlValue = length ? millimetersToDisplay(actualValue, workspace) : actualValue; + const controlMin = length ? millimetersToDisplay(safeMin, workspace) : safeMin; + const controlMax = length ? millimetersToDisplay(safeMax, workspace) : safeMax; + const controlStep = length ? displayStepFromMillimeters(step, workspace) : step; + const sliderValue = clamp(controlValue, controlMin, controlMax); + const position = ((sliderValue - controlMin) / Math.max(Number.EPSILON, controlMax - controlMin)) * 100; + const [editing, setEditing] = useState(false); + const [draft, setDraft] = useState(formatSliderValue(controlValue, workspace.accuracy, controlStep)); + const unitLabel = length ? lengthDisplayUnit(workspace).label : unit; + + useEffect(() => { + if (!editing) { + setDraft(formatSliderValue(controlValue, workspace.accuracy, controlStep)); + } + }, [controlStep, controlValue, editing, workspace.accuracy]); + + const toModelValue = (nextValue: number) => length ? displayToMillimeters(nextValue, workspace) : nextValue; + + const commitDraft = () => { + const next = Number(draft); + const finiteNext = Number.isFinite(next) ? next : controlValue; + onChange(clamp(toModelValue(finiteNext), safeMin, safeMax)); + setEditing(false); + }; + + const handleSliderChange = (nextValue: number) => { + const next = clamp(Number.isFinite(nextValue) ? nextValue : controlMin, controlMin, controlMax); + onChange(clamp(toModelValue(next), safeMin, safeMax)); + setDraft(formatSliderValue(next, workspace.accuracy, controlStep)); + }; + + return ( + + ); +} export function EdgeModifierPanel({ kind, @@ -10,12 +131,14 @@ export function EdgeModifierPanel({ chamferAngle, quality, sharpAngle, + workspace, tangentChain, preserveEdgeSize, targetName, groupedCount, appliedFeatureCount, reversibleFeatureCount, + historyOptions, selectedCount, availableCount, busy, @@ -28,7 +151,7 @@ export function EdgeModifierPanel({ onPreserveEdgeSizeChange, onSelectAll, onClear, - onRemoveLastFeature, + onRemoveFeature, onApply, onCancel, }: { @@ -38,12 +161,14 @@ export function EdgeModifierPanel({ chamferAngle: number; quality: CadModifierQuality; sharpAngle: number; + workspace: WorkplaneWorkspaceSettings; tangentChain: boolean; preserveEdgeSize: boolean; targetName: string; groupedCount: number; appliedFeatureCount: number; reversibleFeatureCount: number; + historyOptions: EdgeHistoryOption[]; selectedCount: number; availableCount: number; busy: boolean; @@ -56,11 +181,14 @@ export function EdgeModifierPanel({ onPreserveEdgeSizeChange: (value: boolean) => void; onSelectAll: () => void; onClear: () => void; - onRemoveLastFeature: () => void; + onRemoveFeature: (id: string) => void; onApply: () => void; onCancel: () => void; }) { + const [historyOpen, setHistoryOpen] = useState(false); const title = kind === "fillet" ? "Fillet edges" : "Chamfer edges"; + const amountMin = Math.min(MIN_EDGE_MODIFIER_AMOUNT, Math.max(Number.EPSILON, maxAmount)); + const amountMax = Math.max(amountMin, maxAmount); return (