From 08e967fb229797156f881a2621387d1a9699b067 Mon Sep 17 00:00:00 2001 From: Michael Cantrell <117473426+Rareuncommon@users.noreply.github.com> Date: Wed, 30 Sep 2026 23:41:24 -0400 Subject: [PATCH] Add selected contours, planar extrusion limits and selection filters --- FEATURES.md | 10 +- PROGRESS.md | 37 ++++ README.md | 18 ++ Sources/CForgeWin/app.cpp | 1 + Sources/CForgeWin/gtk/gtk_render.c | 1 + Sources/ForgeApp/ForgeApp.swift | 9 + Sources/ForgeApp/PMPages.swift | 32 +++- Sources/ForgeApp/Ribbon.swift | 28 ++++ Sources/ForgeApp/ViewportView.swift | 21 +-- .../Commands/FeatureHistoryCommands.swift | 2 +- .../Commands/ProfileCommands.swift | 78 +++++++-- .../Commands/SelectionPickingCommands.swift | 95 +++++++++++ .../Commands/SessionCommands.swift | 3 + .../Commands/SketchRegionCommands.swift | 116 +++++++++++++ Sources/ForgeCommands/Document.swift | 1 + Sources/ForgeCommands/Engine.swift | 3 +- .../ForgeCommands/ExtrusionSurfaceLimit.swift | 58 +++++++ Sources/ForgeCommands/References.swift | 6 +- Sources/ForgeCommands/StandardRegistry.swift | 3 + Sources/ForgeRender/RayPicker.swift | 55 ++++++ Sources/ForgeSketch/Profiles.swift | 9 +- Sources/ForgeUI/AppModel.swift | 26 ++- .../ForgeUI/ExtrudeSelectionWorkflows.swift | 113 +++++++++++++ Sources/ForgeUI/PanelSpec.swift | 33 +++- Sources/ForgeUI/PropertyManager.swift | 40 ++++- Sources/ForgeUI/RibbonSpec.swift | 13 +- Sources/ForgeUI/SelectionWorkflows.swift | 71 ++++++++ Sources/ForgeWin/WinViewport.swift | 6 +- .../SelectionPickingTests.swift | 66 ++++++++ .../SketchRegionTests.swift | 141 ++++++++++++++++ .../SurfaceExtrudeTests.swift | 138 +++++++++++++++ .../CandidatePickingTests.swift | 25 +++ .../ExtrudeRegionSurfaceWorkflowTests.swift | 158 ++++++++++++++++++ .../ForgeUITests/SelectionWorkflowTests.swift | 126 ++++++++++++++ .../027_selected_annulus_to_offset_plane.json | 99 +++++++++++ Tests/IntegrationTests/test_mcp_stdio.py | 38 +++++ docs/research/modeling-workflow-gaps.md | 20 +++ 37 files changed, 1644 insertions(+), 55 deletions(-) create mode 100644 Sources/ForgeCommands/Commands/SelectionPickingCommands.swift create mode 100644 Sources/ForgeCommands/Commands/SketchRegionCommands.swift create mode 100644 Sources/ForgeCommands/ExtrusionSurfaceLimit.swift create mode 100644 Sources/ForgeUI/ExtrudeSelectionWorkflows.swift create mode 100644 Sources/ForgeUI/SelectionWorkflows.swift create mode 100644 Tests/ForgeCommandsTests/SelectionPickingTests.swift create mode 100644 Tests/ForgeCommandsTests/SketchRegionTests.swift create mode 100644 Tests/ForgeCommandsTests/SurfaceExtrudeTests.swift create mode 100644 Tests/ForgeRenderTests/CandidatePickingTests.swift create mode 100644 Tests/ForgeUITests/ExtrudeRegionSurfaceWorkflowTests.swift create mode 100644 Tests/ForgeUITests/SelectionWorkflowTests.swift create mode 100644 Tests/GoldenModelTests/Models/027_selected_annulus_to_offset_plane.json diff --git a/FEATURES.md b/FEATURES.md index d0a54e4..9f70d63 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -8,7 +8,7 @@ edit those columns by hand, then re-run the script. the feature-tree level) · `done` (regenerates, round-trips save/load, undo/redo, command + MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). -**Totals:** 1000 rows — not started: 836 · in progress: 136 · done: 28 · verified: 0 +**Totals:** 1000 rows — not started: 834 · in progress: 138 · done: 28 · verified: 0 ## Platform (SPEC §2–§6, §8–§9) @@ -69,7 +69,7 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `P/inspector` | Inspector panel instead of modal PropertyManagers (§6.2) | in progress | ForgeApp | — | — | PropertyManager panels (OK/Cancel, groups, selection boxes) for every UI operation; read-only entity descriptors | | `P/handles` | Direct-manipulation handles (§6.3) | not started | — | — | — | | | `P/explainable-failures` | Explainable failures in the viewport (§6.4) | not started | — | — | — | | -| `P/smart-selection` | Smart selection, filters, select-other (§6.5) | not started | — | — | — | | +| `P/smart-selection` | Smart selection, filters, select-other (§6.5) | in progress | ForgeCommands / ForgeRender / ForgeUI | Tests/ForgeCommandsTests/SelectionPickingTests.swift, Tests/ForgeUITests/SelectionWorkflowTests.swift, Tests/ForgeRenderTests/CandidatePickingTests.swift | execute:selection.set_filter, execute:view.pick_candidates | all/body/face/edge filters; occluded candidate cycling via Tab/ribbon/menu; hidden-body exclusion and style parity; radial picker, vertex filters, hover and chain selection pending | | `P/input-devices` | Trackpad gestures, 3Dconnexion, Pencil/Sidecar, keymaps (§1.4, §6.9) | in progress | ForgeApp | — | — | mouse + trackpad written, unverified; 3Dconnexion/keymaps pending | | `P/accessibility` | VoiceOver, keyboard-only, high contrast, Dynamic Type (§6.10) | not started | — | — | — | | | `P/performance` | Performance targets + benchmarks with regression alerts (§6.11, §9) | not started | — | — | — | | @@ -160,7 +160,7 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `7.1/tools/sketchxpert/conflict-repair` | ↳ conflict repair | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | — | see parent | | `7.1/tools/check-sketch-for-feature` | Tools: Check Sketch for Feature | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | check_sketch | loops, nesting, open ends, branches, crossings; exact areas | | `7.1/tools/repair-sketch` | Tools: Repair Sketch | not started | ForgeSketch | — | — | | -| `7.1/tools/sketch-contours-regions-selection` | Tools: sketch contours/regions selection | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | check_sketch | loop/region detection done; picking a region for a feature lands with extrude (M2) | +| `7.1/tools/sketch-contours-regions-selection` | Tools: sketch contours/regions selection | in progress | ForgeSketch | Tests/ForgeCommandsTests/SketchRegionTests.swift, Tests/ForgeUITests/ExtrudeRegionSurfaceWorkflowTests.swift | execute:sketch.regions, execute:body.extrude | closed-loop region discovery and point picking; stable complete-curve selectors, holes and nested islands; crossing/branching intersection cells pending | | `7.1/tools/sketch-ink-equivalent` | Tools: Sketch Ink equivalent | not started | ForgeSketch | — | — | | | `7.1/tools/sketch-ink-equivalent/pencil` | ↳ pencil | not started | ForgeSketch | — | — | | | `7.1/relations/coincident` | Relations: coincident | in progress | ForgeSketch | Tests/ForgeSketchTests/SolverTests.swift, Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:sketch.add_relation | round-trips document.save/open (golden test); not yet a feature-tree item (M2) | @@ -223,12 +223,12 @@ MCP, tests) · `verified` (done + golden/e2e coverage + reviewed on macOS). | `7.2/boss-base-and-cut/extrude` | Boss/base & cut: extrude | in progress | ForgeKernel / ForgeCommands | Tests/GoldenModelTests (013–016), Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:body.extrude | kernel-level from sketch profiles (holes, islands); parametric feature, cut and end conditions in M2 | | `7.2/boss-base-and-cut/extrude/blind` | ↳ blind | in progress | ForgeCommands | Tests/GoldenModelTests (013–016), Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:body.extrude | normal/reverse | | `7.2/boss-base-and-cut/extrude/through-all` | ↳ through all | in progress | ForgeCommands | Tests/ForgeCommandsTests/FeatureTreeTests.swift | execute:body.extrude | through_all and through_all_both (depth from the bodies in scope) | -| `7.2/boss-base-and-cut/extrude/up-to-next-vertex-surface-offset` | ↳ up to next/vertex/surface/offset | in progress | ForgeCommands | Tests/ForgeCommandsTests/FeatureTreeTests.swift | execute:body.extrude | up_to_vertex; up to next/surface/offset not started | +| `7.2/boss-base-and-cut/extrude/up-to-next-vertex-surface-offset` | ↳ up to next/vertex/surface/offset | in progress | ForgeCommands | Tests/ForgeCommandsTests/SurfaceExtrudeTests.swift, Tests/ForgeUITests/ExtrudeRegionSurfaceWorkflowTests.swift | execute:body.extrude | vertex and planar face/plane limits, oblique caps, true perpendicular offset in both directions; Up To Next, curved limits, Translate Surface and surface-limit draft pending | | `7.2/boss-base-and-cut/extrude/mid-plane` | ↳ mid-plane | in progress | ForgeCommands | Tests/ForgeCommandsTests/FeatureTreeTests.swift | execute:body.extrude | end_condition mid_plane | | `7.2/boss-base-and-cut/extrude/thin-feature` | ↳ thin feature | in progress | ForgeKernel / ForgeCommands | Tests/ForgeCommandsTests/FeatureTreeTests.swift, Tests/ForgeKernelTests/KernelTests.swift | execute:body.extrude | closed profiles: one direction (either side), mid plane, two directions; open-profile thin features pending | | `7.2/boss-base-and-cut/extrude/draft` | ↳ draft | in progress | ForgeKernel / ForgeCommands | Tests/ForgeCommandsTests/FeatureTreeTests.swift, Tests/ForgeKernelTests/KernelTests.swift | execute:body.extrude | Direction 1, inward/outward | | `7.2/boss-base-and-cut/extrude/direction-2` | ↳ direction-2 | in progress | ForgeCommands | Tests/ForgeCommandsTests/FeatureTreeTests.swift | execute:body.extrude | blind, through all, up to vertex | -| `7.2/boss-base-and-cut/extrude/contour-selection` | ↳ contour selection | not started | ForgeModel | — | — | | +| `7.2/boss-base-and-cut/extrude/contour-selection` | ↳ contour selection | in progress | ForgeCommands / ForgeUI | Tests/ForgeCommandsTests/SketchRegionTests.swift, Tests/ForgeUITests/ExtrudeRegionSurfaceWorkflowTests.swift | execute:sketch.regions, execute:body.extrude | closed-loop selectors with holes, desktop checklist/ray picking, preview/edit/rebuild/save/undo; intersection-cell decomposition pending | | `7.2/boss-base-and-cut/revolve` | Boss/base & cut: revolve | in progress | ForgeKernel / ForgeCommands | Tests/GoldenModelTests (013–016), Tests/ForgeCommandsTests/SketchCommandTests.swift | execute:body.revolve | about a sketch line, any angle; parametric feature in M2 | | `7.2/boss-base-and-cut/sweep` | Boss/base & cut: sweep | in progress | ForgeKernel / ForgeCommands | Tests/ForgeCommandsTests/SweepLoftRibTests.swift, Tests/ForgeKernelTests/KernelTests.swift, Tests/GoldenModelTests | execute:body.sweep | Swept Boss/Base and Swept Cut: sketch profile or circular profile along a path chain (lines, arcs, splines); follow path / keep normal constant; merge, scope; feature + UI pages. Guide curves, twist, thin, solid-body sweep: not implemented | | `7.2/boss-base-and-cut/sweep/profile` | ↳ profile | done | ForgeCommands | Tests/ForgeCommandsTests/SweepLoftRibTests.swift, Tests/ForgeKernelTests/KernelTests.swift | execute:body.sweep | sketch profile (holes kept) or circular_diameter | diff --git a/PROGRESS.md b/PROGRESS.md index 53d5d0e..6e5c1b5 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -1,5 +1,42 @@ # Progress +## Session 12 — 2026-09-30 — Selected contours, planar limits and selection filters + +- Added `sketch.regions` with stable complete-curve selectors, holes, nested islands, + analytic areas, sampled display outlines and point hits. `body.extrude.contours` + selects only the requested closed regions, retaining holes and allowing unrelated + open geometry. Changed contour membership fails explicitly instead of rebinding. +- Both desktop extrusion pages now have region checklists and explicit viewport region + picking, including when opened from a still-active sketch drawing tool. Stored + selectors survive feature editing. Qualified IDs compare canonically; async region + queries coalesce and are guarded against document/sketch/scene changes. +- Up To Surface and Offset From Surface support planar face/plane limits, parallel or + oblique, both directions, true perpendicular offset, persistent references, dependency + validation, cuts, previews and feature editing. Exact planar clipping uses geometry-sized + masks. Lost/suppressed supports fail; upstream edits and save/open regenerate correctly. +- All/body/face/edge selection filters and Select Other candidate cycling share ray + picking across macOS, Windows/Linux and `view.pick_candidates`. Tab/ribbon/menu actions + cycle occluded geometry while retaining other selections. Hidden bodies and reference + overlays are excluded. Session filter preferences survive geometry undo but are not saved. +- Fixed curved-edge candidate deduplication so an occluded segment cannot discard the + visible part of that same edge. All-filter picking follows shaded/wireframe styles; + explicit filters can still request geometry regardless of display style. +- Added the analytic selected-annulus/offset-plane golden model and a real MCP + selected-region/extrude/filter/save/open/rebuild workflow. + +Validation: build with tests and all **379 Swift tests** pass; **33 golden models**, +**five MCP subprocess workflows**, and **three packaging regressions** pass. Windows +frontend cross-platform and optimized Linux desktop/CLI builds pass. Native runtime +checks run in CI using virtual displays; no app windows were launched on the live desktop. +Matrix synchronization and whitespace checks pass. + +Remaining boundaries: contour selection handles complete closed loops, not intersection +cells of crossing/branching sketches. Region hit/display outlines are sampled. Surface +limits require planes, extend a face's supporting plane, reject crossing/behind limits, +and do not support curved limits, Translate Surface, Up To Next or draft+surface. +Select Other cycles candidates; radial UI, vertex filters, hover and tangent-chain +selection remain pending. Broader SolidWorks parity remains unfinished. + ## Session 11 — 2026-09-30 — Subentity measurement, visibility and curved slots - `query.measure` now resolves bodies, faces, edges and vertices, including persistent diff --git a/README.md b/README.md index 9f91477..27d85a9 100644 --- a/README.md +++ b/README.md @@ -129,3 +129,21 @@ The Slot tool offers straight, centerpoint straight, centerpoint arc and three-p variants. Curved slots use center/start/end/width or start/end/through/width clicks, respect construction mode and remain editable with sketch dimensions and relations. The typed command is `sketch.add_arc_slot`; it rejects collapsed or self-overlapping slots. + +Extrusion now supports **Selected Contours**: choose closed regions from the checklist +or enable **Pick Regions in View** and click inside them. Holes stay attached to their +outer region; nested islands are independent. MCP `sketch.regions` returns stable +`selector` arrays for `body.extrude.contours`. Crossing/branching geometry is not split +into intersection cells; changed contour membership produces an explicit reference error. + +**Up To Surface** and **Offset From Surface** accept planar faces and reference planes, +including tilted planes, in either direction. Pick a face/plane, then use **Use Selected +Face/Plane**. Offset is perpendicular to the limiting plane; **Beyond surface** reverses +it. The face's supporting plane is extended. Curved limits and draft with these end +conditions remain unsupported. + +The **Selection** ribbon offers All Geometry/Bodies/Faces/Edges filters. Click in the +viewport, then **Select Other** or **Tab** to cycle candidates behind the first hit. +Hidden bodies are excluded; other selected entities remain selected. Filters are session +preferences and do not restrict tree/explicit selections. MCP commands are +`selection.set_filter` and `view.pick_candidates`; the existing `view.pick` stays compatible. diff --git a/Sources/CForgeWin/app.cpp b/Sources/CForgeWin/app.cpp index 7b9dd34..1e29fcb 100644 --- a/Sources/CForgeWin/app.cpp +++ b/Sources/CForgeWin/app.cpp @@ -832,6 +832,7 @@ static const char *keyName(WPARAM vk) { case VK_DELETE: case VK_BACK: return "delete"; case VK_SPACE: return "space"; + case VK_TAB: return "tab"; default: return nullptr; } } diff --git a/Sources/CForgeWin/gtk/gtk_render.c b/Sources/CForgeWin/gtk/gtk_render.c index b81504e..1d616ff 100644 --- a/Sources/CForgeWin/gtk/gtk_render.c +++ b/Sources/CForgeWin/gtk/gtk_render.c @@ -369,6 +369,7 @@ static gboolean onKey(GtkEventControllerKey *k, guint keyval, guint code, GdkMod case GDK_KEY_Delete: case GDK_KEY_BackSpace: name = "delete"; break; case GDK_KEY_space: name = "space"; break; + case GDK_KEY_Tab: name = "tab"; break; default: { gunichar c = gdk_keyval_to_unicode(keyval); if (c < 32 || c == 127) return FALSE; diff --git a/Sources/ForgeApp/ForgeApp.swift b/Sources/ForgeApp/ForgeApp.swift index c86d98a..6b66131 100644 --- a/Sources/ForgeApp/ForgeApp.swift +++ b/Sources/ForgeApp/ForgeApp.swift @@ -70,6 +70,15 @@ struct ForgeApp: App { Button("Trimetric") { model.setOrientation(.trimetric) } Button("Normal To") { model.normalToSketch() }.keyboardShortcut("8", modifiers: .control).disabled(!model.canNormalTo) Divider() + Menu("Selection Filter") { + ForEach(SelectionFilter.allCases, id: \.rawValue) { filter in + Toggle(filter.title, isOn: Binding(get: { model.selectionFilter == filter }, set: { enabled in + if enabled { Task { await model.setSelectionFilter(filter) } } + })) + } + } + Button("Select Other (Tab)") { Task { await model.selectOther() } }.disabled(!model.canSelectOther) + Divider() Button("Zoom to Fit (F)") { model.zoomToFit() } Button("Previous View") { model.previousView() } Divider() diff --git a/Sources/ForgeApp/PMPages.swift b/Sources/ForgeApp/PMPages.swift index 8f456a8..34cd039 100644 --- a/Sources/ForgeApp/PMPages.swift +++ b/Sources/ForgeApp/PMPages.swift @@ -74,7 +74,7 @@ struct OperationPage: View { .help("Reverse Direction") .disabled(model.form.endCondition == .midPlane || model.form.endCondition == .throughAllBoth) Picker("End condition", selection: $model.form.endCondition) { - ForEach(EndConditionUI.allCases.filter { op == .cutExtrude || !model.bodies.isEmpty || $0.needsDepth || $0 == .upToVertex }, id: \.self) { + ForEach(EndConditionUI.allCases.filter { op == .cutExtrude || !model.bodies.isEmpty || $0.needsDepth || $0 == .upToVertex || $0.needsSurface }, id: \.self) { Text($0.rawValue).tag($0) } } @@ -89,6 +89,15 @@ struct OperationPage: View { PMField(label: "Vertex Y", text: $model.form.vertexY, unit: "mm") PMField(label: "Vertex Z", text: $model.form.vertexZ, unit: "mm") } + if model.form.endCondition.needsSurface { + PMField(label: "Face or plane", text: $model.form.surface) + Button("Use Selected Face/Plane") { model.useSelectedExtrudeSurface() } + PMNote(text: "Planar limits only. Faces use their supporting plane.") + if model.form.endCondition == .offsetFromSurface { + PMField(label: "Normal offset", text: $model.form.surfaceOffset, unit: "mm") + PMCheckbox(label: "Beyond surface", isOn: $model.form.reverseSurfaceOffset) + } + } if op == .extrude && !model.bodies.isEmpty && model.editingFeatureCreatesBody != true { PMCheckbox(label: "Merge result", isOn: $model.form.merge) } @@ -106,7 +115,7 @@ struct OperationPage: View { if model.form.endCondition != .midPlane && model.form.endCondition != .throughAllBoth { PMCheckGroup(title: "Direction 2", isOn: $model.form.direction2) { Picker("End condition", selection: $model.form.endCondition2) { - ForEach([EndConditionUI.blind, .throughAll, .upToVertex].filter { $0 != .throughAll || !model.bodies.isEmpty }, id: \.self) { Text($0.rawValue).tag($0) } + ForEach([EndConditionUI.blind, .throughAll, .upToVertex, .upToSurface, .offsetFromSurface].filter { $0 != .throughAll || !model.bodies.isEmpty }, id: \.self) { Text($0.rawValue).tag($0) } } .labelsHidden() .pickerStyle(.menu) @@ -118,6 +127,15 @@ struct OperationPage: View { if model.form.endCondition2 == .blind { PMField(label: "Depth", text: $model.form.depth2, unit: "mm", icon: .smartDimension) } + if model.form.endCondition2.needsSurface { + PMField(label: "Face or plane", text: $model.form.surface2) + Button("Use Selected Face/Plane") { model.useSelectedExtrudeSurface(direction2: true) } + PMNote(text: "Planar limits only. Faces use their supporting plane.") + if model.form.endCondition2 == .offsetFromSurface { + PMField(label: "Normal offset", text: $model.form.surfaceOffset2, unit: "mm") + PMCheckbox(label: "Beyond surface", isOn: $model.form.reverseSurfaceOffset2) + } + } } } PMCheckGroup(title: "Thin Feature", isOn: $model.form.thinOn) { @@ -140,7 +158,15 @@ struct OperationPage: View { PMPicker(label: "Sketch", selection: Binding(get: { model.operationSketch ?? "" }, set: { model.operationSketch = $0 }), icon: .sketch) { ForEach(model.sketches) { Text($0.name).tag($0.id) } } - PMNote(text: "All closed regions of the sketch are used; holes and islands are kept.") + PMCheckbox(label: "All closed regions", isOn: Binding(get: { model.form.contours == nil }, set: { model.form.contours = $0 ? nil : [] })) + Button(model.form.activeBox == "contours" ? "Stop Picking Regions" : "Pick Regions in View") { + model.form.activeBox = model.form.activeBox == "contours" ? "" : "contours" + } + if let error = model.contourQueryError { PMNote(text: error) } + ForEach(Array(model.contourChoices.enumerated()), id: \.element.id) { index, region in + PMCheckbox(label: "\(index + 1). \(region.title)", isOn: Binding(get: { model.contourIsSelected(region) }, set: { model.setContourSelected(region, $0) })) + } + PMNote(text: "Each selected outer contour keeps its holes. Nested islands are independent regions.") } if op == .cutExtrude || model.form.merge && !model.bodies.isEmpty { PMSection("Feature Scope") { diff --git a/Sources/ForgeApp/Ribbon.swift b/Sources/ForgeApp/Ribbon.swift index ad11109..58a3879 100644 --- a/Sources/ForgeApp/Ribbon.swift +++ b/Sources/ForgeApp/Ribbon.swift @@ -13,6 +13,8 @@ struct RibbonView: View { var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack(alignment: .top, spacing: 4) { + SelectionGroup() + RibbonSeparator() switch model.ribbonTab { case .features: FeaturesTab() case .sketch: SketchTab() @@ -32,6 +34,32 @@ struct RibbonView: View { } } +private struct SelectionGroup: View { + @Environment(AppModel.self) private var model + var body: some View { + RibbonGroup("Selection") { + RibbonStack { + ForEach([SelectionFilter.all, .bodies], id: \.rawValue) { filter in + RibbonSmall(.part, filter.title, active: model.selectionFilter == filter) { + Task { await model.setSelectionFilter(filter) } + } + } + } + RibbonStack { + ForEach([SelectionFilter.faces, .edges], id: \.rawValue) { filter in + RibbonSmall(.part, filter.title, active: model.selectionFilter == filter) { + Task { await model.setSelectionFilter(filter) } + } + } + RibbonSmall(.hideShow, "Select Other (Tab)", enabled: model.canSelectOther, + help: "Cycle through candidates beneath the last click, including occluded faces") { + Task { await model.selectOther() } + } + } + } + } +} + // MARK: tabs private struct FeaturesTab: View { diff --git a/Sources/ForgeApp/ViewportView.swift b/Sources/ForgeApp/ViewportView.swift index adcae4b..17d81a0 100644 --- a/Sources/ForgeApp/ViewportView.swift +++ b/Sources/ForgeApp/ViewportView.swift @@ -37,11 +37,8 @@ struct ViewportView: NSViewRepresentable { let p = ViewProjection(camera: camera, width: width, height: height) if model.projection != p { model.projection = p } } - view.onPick = { ref, extend, at in - Task { - await model.select(ref, extend: extend) - model.contextToolbarAt = ref == nil ? nil : at - } + view.onViewportPick = { camera, width, height, style, extend, at in + Task { await model.viewportPick(at: at, camera: camera, width: width, height: height, extend: extend, style: style) } } view.onSketchClick = { point, tolerance, curve, count, at in Task { await model.sketchClick(point, tolerance: tolerance, curve: curve, clickCount: count, viewPoint: at) } @@ -61,7 +58,7 @@ struct ViewportView: NSViewRepresentable { context.coordinator.sceneVersion = model.sceneVersion view.documentScene = ds view.renderer?.setScene(ds.scene) - view.sketchPlane = model.sketchState.tool == nil ? nil : model.sketchState.plane + view.sketchPlane = model.viewportSketchPlane if first { view.fit() } else { view.cameraChanged() } view.needsDisplay = true } @@ -82,7 +79,7 @@ struct ViewportView: NSViewRepresentable { view.needsDisplay = true } let commands = model.viewportCommands.log - view.sketchPlane = model.sketchState.tool == nil ? nil : model.sketchState.plane + view.sketchPlane = model.viewportSketchPlane if context.coordinator.appliedCommands < commands.count { for c in commands[context.coordinator.appliedCommands...] { switch c { @@ -113,7 +110,7 @@ struct ViewportView: NSViewRepresentable { final class ForgeMTKView: MTKView { var renderer: MetalViewportRenderer? var documentScene: DocumentScene? - var onPick: ((String?, Bool, CGPoint) -> Void)? + var onViewportPick: ((Camera, Double, Double, RenderStyle, Bool, CGPoint) -> Void)? /// Set while a sketch tool is active: clicks become sketch coordinates instead of picks. var sketchPlane: SketchPlane? var onSketchClick: ((Point2, Double, String?, Int, CGPoint) -> Void)? @@ -304,10 +301,9 @@ final class ForgeMTKView: MTKView { return } guard !dragged, let r = renderer else { return } - guard let ds = documentScene else { return } - let px = Int(Double(p.x) * scale), py = Int(Double(bounds.height - p.y) * scale) - let hit = r.pick(x: px, y: py, drawableWidth: Int(drawableSize.width), drawableHeight: Int(drawableSize.height)) - onPick?(hit.flatMap { ds.reference(for: $0) }, !event.modifierFlags.intersection([.shift, .command, .control]).isEmpty, CGPoint(x: p.x, y: bounds.height - p.y)) + onViewportPick?(r.camera, Double(bounds.width), Double(bounds.height), r.style, + !event.modifierFlags.intersection([.shift, .command, .control]).isEmpty, + CGPoint(x: p.x, y: bounds.height - p.y)) } override func keyDown(with event: NSEvent) { @@ -320,6 +316,7 @@ final class ForgeMTKView: MTKView { case 36, 76: key = "return" case 51, 117: key = "delete" case 49: key = "space" + case 48: key = "tab" default: key = event.characters ?? "" } if event.modifierFlags.intersection([.command, .control, .option]).isEmpty, onKey?(key, lastMouse) == true { return } diff --git a/Sources/ForgeCommands/Commands/FeatureHistoryCommands.swift b/Sources/ForgeCommands/Commands/FeatureHistoryCommands.swift index 3e97246..0ac66ca 100644 --- a/Sources/ForgeCommands/Commands/FeatureHistoryCommands.swift +++ b/Sources/ForgeCommands/Commands/FeatureHistoryCommands.swift @@ -116,7 +116,7 @@ extension Document { if f.isSketch, let sketch = f.sketchID { result[sketch] = f.id } } var writers = [String: String](), graph = [String: Set]() - let refKeys: Set = ["body", "target", "tool", "scope", "edges", "faces", "neutral_plane", "reference", "plane", "face", "sketch", "profile", "profiles", "path", "features", "axis", "direction", "direction2"] + let refKeys: Set = ["body", "target", "tool", "scope", "edges", "faces", "neutral_plane", "reference", "plane", "face", "surface", "sketch", "profile", "profiles", "path", "features", "axis", "direction", "direction2"] for (i, f) in features.enumerated() { let before = replay.snapshots[i] let after = i + 1 < replay.snapshots.count ? replay.snapshots[i + 1] : replay.currentBodyState diff --git a/Sources/ForgeCommands/Commands/ProfileCommands.swift b/Sources/ForgeCommands/Commands/ProfileCommands.swift index d81b23c..a5d8363 100644 --- a/Sources/ForgeCommands/Commands/ProfileCommands.swift +++ b/Sources/ForgeCommands/Commands/ProfileCommands.swift @@ -14,8 +14,8 @@ extension Sketch { /// As profileLoops, plus the sketch entity of each segment (in segment order), which names /// the faces swept from it (docs/adr/0002). - func profileLoopsWithIDs() throws -> (loops: [[ProfileSegment]], regions: [Int], ids: [String]) { - let report = profiles() + func profileLoopsWithIDs(contours: [[String]]? = nil) throws -> (loops: [[ProfileSegment]], regions: [Int], ids: [String]) { + let report = try selectedProfileReport(contours: contours) guard report.valid else { throw ForgeError( .preconditionFailed, "sketch \(id) is not a valid profile: " + report.issues.joined(separator: "; "), @@ -89,9 +89,9 @@ public enum ExtrudeDirection: String, Codable, Sendable, CaseIterable, SchemaEnu case normal, reverse, midPlane = "mid_plane" } -/// SolidWorks' extrude end conditions (docs/research §2.4) that need no face reference. +/// Supported extrusion end conditions; surface limits currently require planar geometry. public enum EndCondition: String, Codable, Sendable, CaseIterable, SchemaEnum { - case blind, throughAll = "through_all", throughAllBoth = "through_all_both", midPlane = "mid_plane", upToVertex = "up_to_vertex" + case blind, throughAll = "through_all", throughAllBoth = "through_all_both", midPlane = "mid_plane", upToVertex = "up_to_vertex", upToSurface = "up_to_surface", offsetFromSurface = "offset_from_surface" } public enum ThinType: String, Codable, Sendable, CaseIterable, SchemaEnum { @@ -130,13 +130,20 @@ public struct ExtrudeDirection2: Codable, Sendable, SchemaDocumented { public var endCondition: EndCondition? public var depth: Length? public var vertex: Point3? + public var surface: String? + public var offset: Length? + public var reverseOffset: Bool? enum CodingKeys: String, CodingKey { - case depth, vertex + case depth, vertex, surface, offset + case reverseOffset = "reverse_offset" case endCondition = "end_condition" } public static let fieldDocs: [String: FieldDoc] = [ - "end_condition": FieldDoc("blind, through_all or up_to_vertex", default: "blind"), + "end_condition": FieldDoc("blind, through_all, up_to_vertex, up_to_surface or offset_from_surface", default: "blind"), + "surface": "Planar face or reference plane for a surface end condition (the supporting plane is extended)", + "offset": "Nonnegative perpendicular distance from the surface, required for offset_from_surface", + "reverse_offset": FieldDoc("Offset beyond the surface instead of stopping short", default: false), "depth": "Depth for blind", "vertex": "Point the extrusion reaches for up_to_vertex (model coordinates)", ] @@ -217,11 +224,15 @@ enum FeatureScope { public enum BodyExtrude: Command { public struct Params: Codable, Sendable, SchemaDocumented, ValidatableParams { public var sketch: String? + public var contours: [[String]]? public var depth: Length? public var direction: ExtrudeDirection? public var endCondition: EndCondition? public var reverse: Bool? public var vertex: Point3? + public var surface: String? + public var offset: Length? + public var reverseOffset: Bool? public var direction2: ExtrudeDirection2? public var draft: DraftOption? public var thin: ThinOption? @@ -233,18 +244,23 @@ public enum BodyExtrude: Command { public var instancesOnly: Bool? enum CodingKeys: String, CodingKey { - case sketch, depth, direction, reverse, vertex, direction2, draft, thin, operation, merge, scope, name, instances + case sketch, contours, depth, direction, reverse, vertex, surface, offset, direction2, draft, thin, operation, merge, scope, name, instances + case reverseOffset = "reverse_offset" case endCondition = "end_condition" case instancesOnly = "instances_only" } public static let fieldDocs: [String: FieldDoc] = [ "sketch": FieldDoc("Sketch whose closed profile is extruded", default: "the sketch being edited"), + "contours": "Optional closed-region selectors from sketch.regions (each is the complete outer contour entity-ID set); holes retained, nil uses all regions", "depth": "Direction 1 depth for blind (total depth for mid_plane)", "direction": FieldDoc("Legacy shorthand: normal, reverse (= reverse: true) or mid_plane (= end_condition mid_plane)", default: "normal"), "end_condition": FieldDoc( - "Direction 1 end condition: blind, through_all (through every body in scope), through_all_both, mid_plane, up_to_vertex", + "Direction 1 end condition: blind, through_all (through every body in scope), through_all_both, mid_plane, up_to_vertex, up_to_surface, offset_from_surface", default: "blind"), "reverse": FieldDoc("Extrude against the sketch normal", default: false), + "surface": "Planar face or reference plane for Direction 1 surface limit (the supporting plane is extended)", + "offset": "Nonnegative perpendicular distance from the surface, required for offset_from_surface", + "reverse_offset": FieldDoc("Offset beyond the surface instead of stopping short", default: false), "vertex": "Point Direction 1 reaches, for up_to_vertex (model coordinates)", "direction2": "Also extrude the other way (not with mid_plane or through_all_both)", "draft": "Draft the sides, from the sketch plane (Direction 1 only: not with direction2, mid_plane or through_all_both)", @@ -257,13 +273,18 @@ public enum BodyExtrude: Command { "instances_only": FieldDoc("Build only the instances, not the original (used by pattern.* features)", default: false), ] public func validate() throws { + if let contours, contours.isEmpty || contours.contains(where: \.isEmpty) { + throw ForgeError(.invalidParams, "contours must contain at least one nonempty contour selector") + } let ec = endCondition ?? (direction == .midPlane ? .midPlane : .blind) if ec == .blind || ec == .midPlane { guard let depth else { throw ForgeError(.invalidParams, "depth is required for \(ec.rawValue)") } try requirePositive(depth, "depth") } if ec == .upToVertex && vertex == nil { throw ForgeError(.invalidParams, "vertex is required for up_to_vertex") } + try BodyExtrude.validateSurface(ec, surface: surface, offset: offset, reverseOffset: reverseOffset) if let d = draft { + guard ![ec, direction2?.endCondition ?? .blind].contains(where: { $0 == .upToSurface || $0 == .offsetFromSurface }) else { throw ForgeError(.invalidParams, "draft with a surface end condition is not supported") } guard d.angle.radians > 0, d.angle.radians < .pi / 2 else { throw ForgeError(.invalidParams, "draft angle must be between 0 and 90 degrees") } if direction2 != nil || ec == .midPlane || ec == .throughAllBoth { throw ForgeError(.invalidParams, "draft applies to Direction 1 only (not with direction2, mid_plane or through_all_both)") @@ -277,6 +298,7 @@ public enum BodyExtrude: Command { } } if let d2 = direction2 { + try BodyExtrude.validateSurface(d2.endCondition ?? .blind, surface: d2.surface, offset: d2.offset, reverseOffset: d2.reverseOffset) if ec == .midPlane || ec == .throughAllBoth { throw ForgeError(.invalidParams, "direction2 does not combine with \(ec.rawValue)") } switch d2.endCondition ?? .blind { case .blind: @@ -294,18 +316,31 @@ public enum BodyExtrude: Command { public static let name = "body.extrude" public static let summary = "Extruded Boss/Base or Extruded Cut from a sketch's closed profile (holes and islands kept)" public static let discussion = """ - SolidWorks' Extrude: Direction 1 end condition (blind, through all, through all both, mid plane, up to vertex) with reverse, an optional Direction 2, boss or cut, merge result and feature scope. Recorded as a feature: editing the sketch or feature.edit regenerates it. Also draft (Direction 1) and thin feature for closed profiles. The up-to-surface \ - end conditions and thin features from open sketches are not implemented yet. + SolidWorks' Extrude: Direction 1 end condition (blind, through all, through all both, mid plane, up to vertex) with reverse, an optional Direction 2, boss or cut, merge result and feature scope. Recorded as a feature: editing the sketch or feature.edit regenerates it. Also draft (Direction 1) and thin feature for closed profiles. Planar up-to-surface and offset-from-surface limits support both directions, including oblique planes; offsets are perpendicular to the surface. Curved limits, draft with surface limits and thin features from open sketches are not implemented yet. """ public static let category = CommandCategory.body public static let undo = UndoBehavior.undoable - public static let errors: [ErrorCode] = [.preconditionFailed, .unknownEntity, .kernelFailure, .emptyResult] + public static let errors: [ErrorCode] = [.invalidParams, .preconditionFailed, .unknownEntity, .referenceLost, .kernelFailure, .emptyResult] public static let examples: [JSONValue] = [ ["sketch": "sketch-1", "depth": 10], ["depth": "0.5 in", "direction": "mid_plane"], ["sketch": "sketch-2", "end_condition": "through_all", "operation": "cut"], ["sketch": "sketch-1", "depth": 10, "direction2": ["depth": 4], "merge": true], ] + static func validateSurface(_ condition: EndCondition, surface: String?, offset: Length?, reverseOffset: Bool?) throws { + let usesSurface = condition == .upToSurface || condition == .offsetFromSurface + guard usesSurface else { + guard surface == nil, offset == nil, reverseOffset == nil else { throw ForgeError(.invalidParams, "surface/offset/reverse_offset require a surface end condition") } + return + } + guard let surface, !surface.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw ForgeError(.invalidParams, "surface is required for \(condition.rawValue)") } + if condition == .offsetFromSurface { + guard let offset, offset.millimeters.isFinite, offset.millimeters >= 0 else { throw ForgeError(.invalidParams, "offset_from_surface requires a nonnegative offset") } + } else if offset != nil || reverseOffset != nil { + throw ForgeError(.invalidParams, "offset/reverse_offset require offset_from_surface") + } + } + /// The wall region of a Thin Feature: the band between offsets of the profile boundary. static func thinFace(_ face: Shape, _ t: ThinOption) throws -> Shape { let th = t.thickness.millimeters @@ -347,7 +382,7 @@ public enum BodyExtrude: Command { public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { var doc = try ctx.requireDocument() let sk = try doc.modelingSketch(p.sketch) - let (loops, regions, segmentIDs) = try sk.profileLoopsWithIDs() + let (loops, regions, segmentIDs) = try sk.profileLoopsWithIDs(contours: p.contours) let feature = doc.currentFeature var face = try Kernel.faces(loops: loops, regions: regions) // The profile's edges carry the sketch entities they came from: the side faces swept @@ -361,8 +396,9 @@ public enum BodyExtrude: Command { let ec = p.endCondition ?? (p.direction == .midPlane ? .midPlane : .blind) let s1: Double = (p.reverse ?? false) || p.direction == .reverse ? -1 : 1 let margin = 1.0 - // The extrusion as an interval [a, b] along the sketch normal. - func reach(_ cond: EndCondition, depth: Length?, vertex: Point3?, sign: Double) throws -> Double { + var surfaceLimits: [ExtrusionSurfaceLimit] = [] + // The provisional extrusion interval; oblique surface limits are clipped afterward. + func reach(_ cond: EndCondition, depth: Length?, vertex: Point3?, surface: String?, offset: Length?, reverseOffset: Bool?, sign: Double) throws -> Double { switch cond { case .blind: return depth!.millimeters @@ -375,6 +411,13 @@ public enum BodyExtrude: Command { let t = (vertex!.mm - origin).dot(n) * sign guard t > 1e-9 else { throw ForgeError(.invalidParams, "the vertex is not on the extrusion side of the sketch plane") } return t + case .upToSurface, .offsetFromSurface: + let limit = try ExtrusionSurfaceLimit(document: doc, reference: surface!, offset: offset?.millimeters ?? 0, + reverseOffset: reverseOffset ?? false, travel: n * sign, + role: sign > 0 ? "end_cap" : "start_cap") + let distance = try limit.reach(profile: face, travel: n * sign) + surfaceLimits.append(limit) + return distance case .midPlane, .throughAllBoth: preconditionFailure("handled by the caller") } @@ -388,8 +431,8 @@ public enum BodyExtrude: Command { let e = try extent(doc, p.scope, origin: origin, normal: n) (a, b) = (e.min - margin, e.max + margin) default: - let t1 = try reach(ec, depth: p.depth, vertex: p.vertex, sign: s1) - let t2 = try p.direction2.map { d2 in try reach(d2.endCondition ?? .blind, depth: d2.depth, vertex: d2.vertex, sign: -s1) } ?? 0 + let t1 = try reach(ec, depth: p.depth, vertex: p.vertex, surface: p.surface, offset: p.offset, reverseOffset: p.reverseOffset, sign: s1) + let t2 = try p.direction2.map { d2 in try reach(d2.endCondition ?? .blind, depth: d2.depth, vertex: d2.vertex, surface: d2.surface, offset: d2.offset, reverseOffset: d2.reverseOffset, sign: -s1) } ?? 0 (a, b) = s1 > 0 ? (-t2, t1) : (-t1, t2) } let solid: Shape @@ -403,7 +446,8 @@ public enum BodyExtrude: Command { solid = try Kernel.extrude(start, by: n * (b - a)) } let profile = NamedShape(face, faces: [], edges: edgeNames) - let named = try Naming.named(solid, [profile], feature: feature, roles: NamingRoles(fromEdge: "side")) + var named = try Naming.named(solid, [profile], feature: feature, roles: NamingRoles(fromEdge: "side")) + for limit in surfaceLimits { named = try limit.clip(named, feature: feature) } let tools = try FeatureScope.tools(named, p.instances, only: p.instancesOnly) let ids = try FeatureScope.apply(tools, cut: p.operation == .cut, merge: p.merge == true, &doc, p.scope, name: p.name, producedBy: name) diff --git a/Sources/ForgeCommands/Commands/SelectionPickingCommands.swift b/Sources/ForgeCommands/Commands/SelectionPickingCommands.swift new file mode 100644 index 0000000..f57aa43 --- /dev/null +++ b/Sources/ForgeCommands/Commands/SelectionPickingCommands.swift @@ -0,0 +1,95 @@ +import ForgeCore +import ForgeRender +import Foundation + +/// Viewport filters are session state; explicit selection.set remains unrestricted. +public enum SelectionFilter: String, Codable, Sendable, CaseIterable, SchemaEnum { + case all, bodies, faces, edges +} + +public enum SelectionSetFilter: Command { + public struct Params: Codable, Sendable, SchemaDocumented { + public var filter: SelectionFilter + public static let fieldDocs: [String: FieldDoc] = ["filter": "Viewport hit filter: all geometry, bodies, faces or model edges; explicit selection.set is unaffected"] + } + public struct Output: Codable, Sendable { public var filter: SelectionFilter } + public static let name = "selection.set_filter" + public static let summary = "Set the active document's viewport selection filter" + public static let category = CommandCategory.selection + public static let undo = UndoBehavior.session + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { + var doc = try ctx.requireDocument() + doc.selectionFilter = p.filter + ctx.document = doc + return Output(filter: p.filter) + } +} + +extension DocumentScene { + /// Pick only model/sketch objects. Planes, grids and display overlays never become + /// candidates, and hidden bodies have already been omitted by DocumentScene. + public func pickCandidates(origin: Vec3, direction: Vec3, edgeTolerance: Double, + filter: SelectionFilter, includeOccluded: Bool, style: RenderStyle = .shadedWithEdges) -> [String] { + var geometry = scene + geometry.items.removeAll { Int($0.objectID) >= bodies.count + sketches.count } + let hits = RayPicker.candidates(geometry, origin: origin, direction: direction, + edgeTolerance: edgeTolerance, includeOccluded: includeOccluded || (filter == .all && style == .wireframe)) + var refs: [String] = [], seen = Set() + for hit in hits { + let isBody = Int(hit.objectID) < bodies.count + let ref: String? + switch filter { + case .all: + if style == .wireframe && hit.element == .face { continue } + if style == .shaded && isBody && hit.element == .edge { continue } + ref = reference(for: hit) + case .bodies: ref = isBody ? bodies[Int(hit.objectID)] : nil + case .faces: ref = isBody && hit.element == .face ? reference(for: hit) : nil + case .edges: ref = isBody && hit.element == .edge ? reference(for: hit) : nil + } + if let ref, seen.insert(ref).inserted { refs.append(ref) } + } + return refs + } +} + +public enum ViewPickCandidates: Command { + public struct Params: Codable, Sendable, SchemaDocumented, ValidatableParams { + public var x: Int + public var y: Int + public var view: ViewSpec? + public var radius: Int? + public var filter: SelectionFilter? + public var includeOccluded: Bool? + enum CodingKeys: String, CodingKey { case x, y, view, radius, filter; case includeOccluded = "include_occluded" } + public static let fieldDocs: [String: FieldDoc] = [ + "x": "Pixel column in the rendered view", "y": "Pixel row from the top", + "view": "Same view options as view.render", "radius": FieldDoc("Edge tolerance in pixels (0–20)", default: 4), + "filter": FieldDoc("Candidate type", default: "current document selection filter"), + "include_occluded": FieldDoc("Include surfaces behind the nearest visible face for Select Other", default: true), + ] + public func validate() throws { + try view?.validate() + let (w, h) = (view ?? ViewSpec()).size + guard (0.. Output { + let doc = try ctx.requireDocument(), view = p.view ?? ViewSpec() + let ds = try DocumentScene(document: doc, bodies: view.bodies, showSketches: view.sketches ?? true) + let camera = view.camera(for: ds.scene), (w, h) = view.size + let ray = camera.ray(pixelX: Double(p.x), pixelY: Double(p.y), width: Double(w), height: Double(h)) + let filter = p.filter ?? doc.selectionFilter + return Output(candidates: ds.pickCandidates(origin: ray.origin, direction: ray.direction, + edgeTolerance: Double(p.radius ?? 4) * 2 * camera.visibleHalfHeight / Double(h), + filter: filter, includeOccluded: p.includeOccluded ?? true, style: view.style ?? .shadedWithEdges), filter: filter) + } +} diff --git a/Sources/ForgeCommands/Commands/SessionCommands.swift b/Sources/ForgeCommands/Commands/SessionCommands.swift index 714190b..fae93e8 100644 --- a/Sources/ForgeCommands/Commands/SessionCommands.swift +++ b/Sources/ForgeCommands/Commands/SessionCommands.swift @@ -115,6 +115,7 @@ public enum DocumentState: Command { public var sketches: [SketchSummary] public var activeSketch: String? public var selection: [String] + public var selectionFilter: SelectionFilter public var visibility: BodyVisibilityState public var undo: [String] public var redo: [String] @@ -122,6 +123,7 @@ public enum DocumentState: Command { enum CodingKeys: String, CodingKey { case document, bodies, sketches, selection, visibility, undo, redo, transaction + case selectionFilter = "selection_filter" case activeSketch = "active_sketch" } } @@ -141,6 +143,7 @@ public enum DocumentState: Command { bodies: try doc.orderedBodies.map(BodySummary.init), sketches: doc.orderedSketches.map { SketchSummary($0, active: $0.id == doc.activeSketch) }, activeSketch: doc.activeSketch, selection: doc.selection, + selectionFilter: doc.selectionFilter, visibility: BodyVisibilityState(doc), undo: s.undoLabels, redo: s.redoLabels, transaction: s.transactionLabel) } diff --git a/Sources/ForgeCommands/Commands/SketchRegionCommands.swift b/Sources/ForgeCommands/Commands/SketchRegionCommands.swift new file mode 100644 index 0000000..e3659eb --- /dev/null +++ b/Sources/ForgeCommands/Commands/SketchRegionCommands.swift @@ -0,0 +1,116 @@ +import ForgeCore +import ForgeSketch +import Foundation + +extension Sketch { + /// Select by the complete entity set, never by a transient loop ordinal or by one edge + /// which could silently become part of a different contour after trim/split operations. + func selectedProfileReport(contours: [[String]]?) throws -> ProfileReport { + let report = profiles() + guard let contours else { return report } + guard !contours.isEmpty else { throw ForgeError(.invalidParams, "select at least one contour") } + var seen = Set<[String]>() + var selected = Set() + for selector in contours { + let normalized = try selector.map { try localID($0, in: self) }.sorted() + guard !normalized.isEmpty, Set(normalized).count == normalized.count, seen.insert(normalized).inserted else { + throw ForgeError(.invalidParams, "contour selectors must be nonempty, unique sets of entity IDs") + } + guard let index = report.loops.firstIndex(where: { $0.entities.sorted() == normalized }), + report.loops[index].depth % 2 == 0 else { + throw ForgeError(.referenceLost, "selected contour changed, is no longer closed, or is now a hole", entities: normalized.map { "\(id)/\($0)" }, + suggestions: [SuggestedFix(description: "Choose an available closed region", command: "sketch.regions", params: ["sketch": .string(id)])]) + } + selected.formUnion(report.loops[index].entities) + for hole in report.loops where hole.parent == index { selected.formUnion(hole.entities) } + } + // Explicit selection may ignore unrelated open/crossing geometry; the selected + // boundaries themselves still undergo the complete profile validation. + return profiles(including: selected) + } +} + +public struct SketchRegion: Codable, Sendable { + /// Stable replay selector: sorted IDs of every curve of the outer contour. + public var selector: [String] + public var outerEntities: [String] + public var holes: [[String]] + public var areaMM2: Double + /// Sampled display boundaries in sketch coordinates; not a replacement for kernel geometry. + public var outerOutline: [[Double]] + public var holeOutlines: [[[Double]]] + enum CodingKeys: String, CodingKey { + case selector, holes + case outerEntities = "outer_entities", areaMM2 = "area_mm2" + case outerOutline = "outer_outline", holeOutlines = "hole_outlines" + } +} + +public enum SketchRegions: Command { + public struct Params: Codable, Sendable, SchemaDocumented { + public var sketch: String? + public var at: Point2? + public static let fieldDocs: [String: FieldDoc] = [ + "sketch": sketchParamDoc, + "at": "Optional sketch-coordinate point; return only closed regions containing it (excluding holes)", + ] + } + public struct Output: Codable, Sendable { + public var sketch: String + public var regions: [SketchRegion] + public var profileValid: Bool + public var issues: [String] + enum CodingKeys: String, CodingKey { case sketch, regions, issues; case profileValid = "profile_valid" } + } + public static let name = "sketch.regions" + public static let summary = "List selectable closed sketch regions with stable contour selectors and optional point hit testing" + public static let discussion = "Each region is one even-depth outer loop with its immediate holes; nested islands are separate regions. Pass selector arrays as body.extrude contours. Open geometry unrelated to a selected closed contour may be ignored. Crossing or branching geometry is not decomposed into intersection cells. Display outlines and point tests are sampled; extrusion geometry and area use the original curves." + public static let category = CommandCategory.sketch + public static let undo = UndoBehavior.none + public static let errors: [ErrorCode] = [.unknownEntity, .invalidParams] + public static let examples: [JSONValue] = [[:], ["sketch": "sketch-1", "at": [5, 5]]] + + static func contains(_ point: Point2, outline: [[Double]]) -> Bool { + guard outline.count > 2 else { return false } + var inside = false + var previous = outline.last! + for current in outline { + let dx = current[0] - previous[0], dy = current[1] - previous[1] + let length2 = dx * dx + dy * dy + if length2 > 0 { + let t = max(0, min(1, ((point.u - previous[0]) * dx + (point.v - previous[1]) * dy) / length2)) + if hypot(point.u - previous[0] - t * dx, point.v - previous[1] - t * dy) < 1e-8 { return true } + } + if (current[1] > point.v) != (previous[1] > point.v), + point.u < (previous[0] - current[0]) * (point.v - current[1]) / (previous[1] - current[1]) + current[0] { + inside.toggle() + } + previous = current + } + return inside + } + + public static func run(_ p: Params, _ ctx: inout CommandContext) throws -> Output { + let sketch = try ctx.requireDocument().sketch(p.sketch) + let report = sketch.profiles() + func outline(_ loop: ProfileLoop) -> [[Double]] { + zip(loop.entities, loop.forward).flatMap { id, forward in + let points = sketch.polyline(id).map { [$0.0, $0.1] } + return forward ? points : Array(points.reversed()) + } + } + var regions: [SketchRegion] = [] + for (index, loop) in report.loops.enumerated() where loop.depth % 2 == 0 { + let selector = loop.entities.sorted() + let holes = report.loops.filter { $0.parent == index } + let selected = sketch.profiles(including: Set(loop.entities + holes.flatMap(\.entities))) + guard selected.valid else { continue } + let outer = outline(loop), inner = holes.map(outline) + if let point = p.at, !contains(point, outline: outer) || inner.contains(where: { contains(point, outline: $0) }) { continue } + regions.append(SketchRegion(selector: selector, outerEntities: loop.entities, holes: holes.map(\.entities), + areaMM2: selected.regionAreaMM2, outerOutline: outer, holeOutlines: inner)) + } + regions.sort { $0.selector.lexicographicallyPrecedes($1.selector) } + return Output(sketch: sketch.id, regions: regions, profileValid: report.valid, issues: report.issues) + } +} diff --git a/Sources/ForgeCommands/Document.swift b/Sources/ForgeCommands/Document.swift index 2aa3c39..437e5dc 100644 --- a/Sources/ForgeCommands/Document.swift +++ b/Sources/ForgeCommands/Document.swift @@ -36,6 +36,7 @@ public struct Document: Sendable { public internal(set) var bodies: [String: Body] = [:] /// Explicit, queryable selection (SPEC §5.4: no hidden state). Entity reference strings. public var selection: [String] = [] + public var selectionFilter: SelectionFilter = .all /// Persistent display visibility; geometry and exports still include hidden bodies. public var hiddenBodyIDs: Set = [] /// Temporary isolation whitelist. Nil restores ordinary saved visibility. diff --git a/Sources/ForgeCommands/Engine.swift b/Sources/ForgeCommands/Engine.swift index cede35c..7da3a1e 100644 --- a/Sources/ForgeCommands/Engine.swift +++ b/Sources/ForgeCommands/Engine.swift @@ -294,7 +294,7 @@ public actor Engine { if dryRun && !descriptor.supportsDryRun { throw ForgeError(.unsupported, "'\(item.command)' cannot run in a dry-run batch") } - let localSessionCommands: Set = ["selection.set", "selection.clear", "sketch.edit", "sketch.exit"] + let localSessionCommands: Set = ["selection.set", "selection.clear", "selection.set_filter", "sketch.edit", "sketch.exit"] if atomic && !descriptor.supportsDryRun && !localSessionCommands.contains(item.command) { throw ForgeError(.unsupported, "'\(item.command)' cannot run in an atomic batch; execute it separately or use atomic: false") } @@ -421,6 +421,7 @@ extension Document { func preservingSelection(of current: Document) -> Document { var d = self d.selection = current.selection.filter { d.referenceExists($0) } + d.selectionFilter = current.selectionFilter return d } } diff --git a/Sources/ForgeCommands/ExtrusionSurfaceLimit.swift b/Sources/ForgeCommands/ExtrusionSurfaceLimit.swift new file mode 100644 index 0000000..09fd59e --- /dev/null +++ b/Sources/ForgeCommands/ExtrusionSurfaceLimit.swift @@ -0,0 +1,58 @@ +import ForgeCore +import ForgeKernel +import Foundation + +/// An oriented supporting plane: the kept material is its negative half-space. +/// A finite clipping box surrounds the actual extrusion bounds; only its z=0 face +/// can intersect the extrusion, so this is an exact planar cut independent of model size. +struct ExtrusionSurfaceLimit { + var origin: Vec3 + var normal: Vec3 + var x: Vec3 + var y: Vec3 + var reference: String + var role: String + + var toLocal: Transform3 { + Transform3(m: [x.x, x.y, x.z, -origin.dot(x), y.x, y.y, y.z, -origin.dot(y), normal.x, normal.y, normal.z, -origin.dot(normal)]) + } + var toWorld: Transform3 { + Transform3(m: [x.x, y.x, normal.x, origin.x, x.y, y.y, normal.y, origin.y, x.z, y.z, normal.z, origin.z]) + } + + init(document: Document, reference: String, offset: Double, reverseOffset: Bool, travel: Vec3, role: String) throws { + let ref = reference.hasPrefix("plane-") && StandardPlane(rawValue: String(reference.dropFirst(6))) != nil ? String(reference.dropFirst(6)) : reference + let plane = try document.resolvePlacement(ref) + let dot = plane.normal.dot(travel) + guard abs(dot) > 1e-9 else { throw ForgeError(.invalidParams, "the limiting plane is parallel to the extrusion direction", entities: [reference]) } + normal = dot > 0 ? plane.normal : -plane.normal + x = plane.xAxis + y = normal.cross(x).normalized + origin = plane.origin + normal * (reverseOffset ? offset : -offset) + self.reference = reference + self.role = role + } + + func reach(profile: Shape, travel: Vec3) throws -> Double { + let bounds = try Kernel.transform(profile, toLocal).boundingBox() + let denominator = normal.dot(travel) + let minimum = -bounds.max.z / denominator + let maximum = -bounds.min.z / denominator + guard minimum > 1e-7, maximum.isFinite else { + throw ForgeError(.invalidParams, "the limiting plane must lie ahead of the entire profile; it crosses, touches or lies behind the sketch", entities: [reference]) + } + // Overshoot so the provisional prism's end cap cannot survive the clipping operation. + return maximum + max(1, maximum * 1e-6) + } + + func clip(_ input: NamedShape, feature: String) throws -> NamedShape { + let bounds = try Kernel.transform(input.shape, toLocal).boundingBox() + let pad = max(1, bounds.diagonal * 0.01) + let local = try Kernel.box(origin: Vec3(bounds.min.x - pad, bounds.min.y - pad, bounds.min.z - pad), + size: Vec3(bounds.size.x + 2 * pad, bounds.size.y + 2 * pad, -bounds.min.z + pad)) + let mask = try Kernel.transform(local, toWorld) + let names = Array(repeating: ["\(feature):\(role)"], count: try mask.topology().faces) + let result = try Kernel.boolean(.common, input.shape, mask) + return try Naming.named(result, [input, NamedShape(mask, faces: names)], feature: feature) + } +} diff --git a/Sources/ForgeCommands/References.swift b/Sources/ForgeCommands/References.swift index 4b411a2..685b866 100644 --- a/Sources/ForgeCommands/References.swift +++ b/Sources/ForgeCommands/References.swift @@ -185,7 +185,11 @@ extension Document { var out: [String: JSONValue] = [:] for (k, x) in o { let kind: EntityRef.Kind? = k == "edges" ? .edge : (k == "faces" || k == "neutral_plane") ? .face : nil - out[k] = k == "body" || k == "sketch" || k == "features" ? x : walk(x, bare: kind) + if k == "surface", let name = x.stringValue, refPlanes[name] == nil, let plane = orderedRefPlanes.first(where: { $0.name == name }) { + out[k] = .string(plane.id) + } else { + out[k] = k == "body" || k == "sketch" || k == "features" ? x : walk(x, bare: kind) + } } return .object(out) default: diff --git a/Sources/ForgeCommands/StandardRegistry.swift b/Sources/ForgeCommands/StandardRegistry.swift index f8fcf1f..fabe0f8 100644 --- a/Sources/ForgeCommands/StandardRegistry.swift +++ b/Sources/ForgeCommands/StandardRegistry.swift @@ -30,6 +30,7 @@ extension CommandRegistry { r.register(SketchRemove.self) r.register(SketchGet.self) r.register(SketchCheck.self) + r.register(SketchRegions.self) r.register(SketchAddPoint.self) r.register(SketchAddLine.self) r.register(SketchAddCircle.self) @@ -111,6 +112,8 @@ extension CommandRegistry { r.register(SelectionSet.self) r.register(SelectionGet.self) r.register(SelectionClear.self) + r.register(SelectionSetFilter.self) + r.register(ViewPickCandidates.self) // view r.register(ViewSetVisibility.self) r.register(ViewIsolate.self) diff --git a/Sources/ForgeRender/RayPicker.swift b/Sources/ForgeRender/RayPicker.swift index 6a0608b..abb2404 100644 --- a/Sources/ForgeRender/RayPicker.swift +++ b/Sources/ForgeRender/RayPicker.swift @@ -44,6 +44,61 @@ public enum RayPicker { return bestFace?.0 } + /// Unique ray hits, including rear surfaces for Select Other when requested. + /// Normal picking excludes edges occluded by the nearest face. Reference geometry + /// should be removed by the caller before using this geometry-only picker. + public static func candidates(_ scene: RenderScene, origin: Vec3, direction: Vec3, + edgeTolerance: Double = 0, includeOccluded: Bool = true) -> [PickHit] { + guard direction.length > 1e-12 else { return [] } + let d = direction.normalized + struct Key: Hashable { var object: UInt32; var element: PickHit.Element; var index: UInt32 } + var hits: [Key: (hit: PickHit, depth: Double, offset: Double)] = [:] + var edgeSegments: [(hit: PickHit, depth: Double, offset: Double)] = [] + for item in scene.items { + let m = item.mesh + for t in 0.. 0 else { continue } + for e in 0..= 2 else { continue } + for k in start..<(end-1) { + let p = Vec3(Double(m.edgePoints[3*k]), Double(m.edgePoints[3*k+1]), Double(m.edgePoints[3*k+2])) + let q = Vec3(Double(m.edgePoints[3*k+3]), Double(m.edgePoints[3*k+4]), Double(m.edgePoints[3*k+5])) + let (offset, depth, point) = raySegmentDistance(origin: origin, dir: d, p, q) + guard offset <= edgeTolerance else { continue } + // Retain segment hits until visibility is known. An occluded part of + // one curved edge may be closer to the ray than its visible part; + // deduplicating here would incorrectly discard that visible edge. + edgeSegments.append((PickHit(objectID: item.objectID, element: .edge, index: m.edgeIDs[e], point: point), depth, offset)) + } + } + } + let nearestFace = hits.values.filter { $0.hit.element == .face }.map(\.depth).min() ?? .infinity + let limit = nearestFace + max(1e-8, edgeTolerance * 2) + let ordered = (Array(hits.values) + edgeSegments).filter { includeOccluded || $0.depth <= limit }.sorted { a, b in + let aEdge = a.hit.element == .edge && a.depth <= limit + let bEdge = b.hit.element == .edge && b.depth <= limit + if aEdge != bEdge { return aEdge } + if aEdge && a.offset != b.offset { return a.offset < b.offset } + if a.depth != b.depth { return a.depth < b.depth } + if a.hit.objectID != b.hit.objectID { return a.hit.objectID < b.hit.objectID } + if a.hit.element != b.hit.element { return a.hit.element == .edge } + return a.hit.index < b.hit.index + } + var seen = Set() + return ordered.compactMap { candidate in + let hit = candidate.hit + return seen.insert(Key(object: hit.objectID, element: hit.element, index: hit.index)).inserted ? hit : nil + } + } + static func intersect(origin: Vec3, dir: Vec3, _ a: Vec3, _ b: Vec3, _ c: Vec3) -> Double? { let e1 = b - a, e2 = c - a let p = dir.cross(e2) diff --git a/Sources/ForgeSketch/Profiles.swift b/Sources/ForgeSketch/Profiles.swift index bcfd19d..2b292e8 100644 --- a/Sources/ForgeSketch/Profiles.swift +++ b/Sources/ForgeSketch/Profiles.swift @@ -121,8 +121,8 @@ extension Sketch { /// Analyse the non-construction geometry as feature profiles (SPEC 7.1 "Check Sketch for /// Feature", "sketch contours/regions"). - public func profiles() -> ProfileReport { - let curves = orderedEntities.filter { $0.kind != .point && !$0.construction } + public func profiles(including entityIDs: Set? = nil) -> ProfileReport { + let curves = orderedEntities.filter { $0.kind != .point && !$0.construction && (entityIDs?.contains($0.id) ?? true) } let scale = max(1, params.map(abs).max() ?? 1) let tol = 1e-7 * scale var issues: [String] = [] @@ -197,7 +197,10 @@ extension Sketch { // Nesting by containment of a sample point, smallest container wins. let loopPolys = loops.map { loop -> [(Double, Double)] in - loop.entities.flatMap { polyline($0) } + zip(loop.entities, loop.forward).flatMap { id, forward in + let points = polyline(id) + return forward ? points : Array(points.reversed()) + } } for i in loops.indices { let probe = loopPolys[i][0] diff --git a/Sources/ForgeUI/AppModel.swift b/Sources/ForgeUI/AppModel.swift index 9caf701..07e8fa9 100644 --- a/Sources/ForgeUI/AppModel.swift +++ b/Sources/ForgeUI/AppModel.swift @@ -228,6 +228,9 @@ package final class AppModel { /// The rollback and re-selection that start an edit (awaited by tests). package var editTask: Task? package var selection: [String] = [] + package var selectionFilter: SelectionFilter = .all + package var viewportPickContext: ViewportPickContext? + private var pickDocumentID: String? package var inspector: JSONValue? package var lastError: ForgeError? package var log: [String] = [] @@ -236,7 +239,19 @@ package final class AppModel { package var ribbonTab: RibbonTab = .features package var operation: Operation? /// The sketch an extrude/revolve uses, and the values being edited in the PropertyManager. - package var operationSketch: String? + package var operationSketch: String? { + didSet { + guard oldValue != operationSketch else { return } + form.contours = nil + contourChoices = [] + Task { await refreshContourChoices() } + } + } + package var contourChoices: [ExtrudeContourChoice] = [] + package var contourQueryError: String? + @ObservationIgnored package var contourRequest = 0 + @ObservationIgnored package var contourQueryTask: Task? + @ObservationIgnored package var contourQueryKey: String? package var form = OperationForm() /// Bumped whenever the scene must be re-uploaded to the GPU. package var sceneVersion = 0 @@ -410,6 +425,9 @@ package final class AppModel { rollback = doc.rollback refPlanes = doc.orderedRefPlanes selection = doc.selection + if pickDocumentID != doc.id || selectionFilter != doc.selectionFilter { viewportPickContext = nil } + pickDocumentID = doc.id + selectionFilter = doc.selectionFilter sketchLineIDs = Dictionary(uniqueKeysWithValues: doc.orderedSketches.map { sk in let lines = sk.orderedEntities.filter { $0.kind == .line } return (sk.id, (lines.filter(\.construction) + lines.filter { !$0.construction }).map(\.id)) @@ -439,6 +457,7 @@ package final class AppModel { composeScene() } await refreshSketchState() + if operation == .extrude || operation == .cutExtrude { await refreshContourChoices() } if let first = selection.first, !first.hasPrefix("sketch-"), let o = try? await engine.execute("query.entity", ["ref": .string(first)]) { inspector = o.result } else { @@ -479,7 +498,7 @@ package final class AppModel { package func setOrientation(_ o: ViewOrientation) { viewportCommands.send(.orient(o)) } package func zoomToFit() { viewportCommands.send(.fit) } package func previousView() { viewportCommands.send(.previous) } - package func setStyle(_ s: RenderStyle) { viewportCommands.send(.style(s)) } + package func setStyle(_ s: RenderStyle) { viewportPickContext = nil; viewportCommands.send(.style(s)) } package func setPerspective(_ on: Bool) { display.perspective = on viewportCommands.send(.projection(on ? .perspective : .orthographic)) @@ -495,6 +514,9 @@ package final class AppModel { case "Z": viewportCommands.send(.zoom(1.25)) case "s", "S": shortcutBarAt = p case "space": orientationPaletteShown.toggle() + case "tab", "\t": + guard canSelectOther else { return false } + Task { await selectOther() } case "return": if activeSketch != nil, sketchState.tool == nil, let t = lastSketchTool { chooseTool(t) diff --git a/Sources/ForgeUI/ExtrudeSelectionWorkflows.swift b/Sources/ForgeUI/ExtrudeSelectionWorkflows.swift new file mode 100644 index 0000000..572375b --- /dev/null +++ b/Sources/ForgeUI/ExtrudeSelectionWorkflows.swift @@ -0,0 +1,113 @@ +import ForgeCommands +import ForgeCore +import ForgeSketch +import Foundation + +package struct ExtrudeContourChoice: Identifiable { + package var selector: [String] + package var area: Double + package var id: String { selector.sorted().joined(separator: "|") } + package var title: String { "Region · \(String(format: "%.3f", area)) mm²" } +} + +extension AppModel { + package func refreshContourChoices() async { + guard let sketch = operationSketch else { + contourRequest += 1 + contourChoices = []; contourQueryError = nil + contourQueryTask = nil; contourQueryKey = nil + return + } + guard let document = await engine.activeDocument, operationSketch == sketch else { return } + let revision = sceneVersion + let key = "\(document.id)|\(sketch)|\(revision)" + // begin(), operationSketch.didSet and explicit callers can all request the same + // regions in one run-loop turn. Await one task rather than invalidating each other. + if contourQueryKey == key, let task = contourQueryTask { + await task.value + return + } + contourRequest += 1 + let request = contourRequest + contourQueryKey = key + let task = Task { [weak self] in + guard let self else { return } + do { + let result = try await engine.execute("sketch.regions", ["sketch": .string(sketch)], document: document.id).result + guard await engine.activeDocument?.id == document.id, request == contourRequest, + operationSketch == sketch, sceneVersion == revision else { return } + contourChoices = (result["regions"]?.arrayValue ?? []).compactMap { region in + guard let selector = region["selector"]?.arrayValue?.compactMap(\.stringValue), !selector.isEmpty, + let area = region["area_mm2"]?.doubleValue else { return nil } + return ExtrudeContourChoice(selector: selector, area: area) + } + contourQueryError = nil + } catch { + guard await engine.activeDocument?.id == document.id, request == contourRequest, + operationSketch == sketch, sceneVersion == revision else { return } + contourChoices = [] + contourQueryError = ForgeError.wrap(error).message + } + } + contourQueryTask = task + await task.value + if request == contourRequest { contourQueryTask = nil; contourQueryKey = nil } + } + + private func canonicalContour(_ selector: [String]) -> [String] { + let prefix = (operationSketch ?? "") + "/" + return selector.map { $0.hasPrefix(prefix) ? String($0.dropFirst(prefix.count)) : $0 }.sorted() + } + + package func contourIsSelected(_ choice: ExtrudeContourChoice) -> Bool { + form.contours == nil || form.contours!.contains { canonicalContour($0) == canonicalContour(choice.selector) } + } + + package func setContourSelected(_ choice: ExtrudeContourChoice, _ selected: Bool) { + var contours = form.contours ?? contourChoices.map(\.selector) + contours.removeAll { canonicalContour($0) == canonicalContour(choice.selector) } + if selected { contours.append(choice.selector) } + form.contours = contours + } + + package func useSelectedExtrudeSurface(direction2: Bool = false) { + guard let ref = selectedFace ?? selection.last(where: { $0.hasPrefix("plane-") }) else { + lastError = ForgeError(.invalidParams, "Select a planar face or plane for the extrusion limit.") + return + } + if direction2 { form.surface2 = ref } else { form.surface = ref } + } + + /// Contour picking is explicit so an extrusion can still select a limiting face. + package func pickExtrusionContour(origin: Vec3, direction: Vec3) async -> Bool { + guard operation == .extrude || operation == .cutExtrude, form.activeBox == "contours" else { return false } + guard let id = operationSketch, let doc = await engine.activeDocument, let sk = doc.sketches[id] else { return true } + let requestedOperation = operation, requestedFeature = editingFeature + let denominator = direction.dot(sk.plane.normal) + guard abs(denominator) > 1e-10 else { return true } + let distance = (sk.plane.origin - origin).dot(sk.plane.normal) / denominator + guard distance >= 0 else { return true } + let offset = origin + direction * distance - sk.plane.origin + let point: JSONValue = [.number(offset.dot(sk.plane.xAxis)), .number(offset.dot(sk.plane.yAxis))] + do { + let result = try await engine.execute("sketch.regions", ["sketch": .string(id), "at": point], document: doc.id).result + guard await engine.activeDocument?.id == doc.id, operationSketch == id, form.activeBox == "contours", + operation == requestedOperation, editingFeature == requestedFeature else { return true } + let regions = result["regions"]?.arrayValue ?? [] + guard regions.count == 1, let selector = regions[0]["selector"]?.arrayValue?.compactMap(\.stringValue), !selector.isEmpty else { + lastError = ForgeError(.invalidParams, regions.isEmpty ? "Click inside a closed sketch region, outside its holes." : "Several regions overlap here; choose one from Selected Contours.") + return true + } + if form.contours == nil { form.contours = [] } + let choice = ExtrudeContourChoice(selector: selector, area: regions[0]["area_mm2"]?.doubleValue ?? 0) + setContourSelected(choice, !contourIsSelected(choice)) + lastError = nil + await updatePreview() + } catch { + guard await engine.activeDocument?.id == doc.id, operationSketch == id, form.activeBox == "contours", + operation == requestedOperation, editingFeature == requestedFeature else { return true } + lastError = ForgeError.wrap(error) + } + return true + } +} diff --git a/Sources/ForgeUI/PanelSpec.swift b/Sources/ForgeUI/PanelSpec.swift index 33ad0cf..54776ed 100644 --- a/Sources/ForgeUI/PanelSpec.swift +++ b/Sources/ForgeUI/PanelSpec.swift @@ -162,7 +162,30 @@ extension AppModel { } private var endConditionOptions: [(tag: String, title: String)] { - EndConditionUI.allCases.filter { operation == .cutExtrude || !bodies.isEmpty || $0.needsDepth || $0 == .upToVertex }.map { ($0.rawValue, $0.rawValue) } + EndConditionUI.allCases.filter { operation == .cutExtrude || !bodies.isEmpty || $0.needsDepth || $0 == .upToVertex || $0.needsSurface }.map { ($0.rawValue, $0.rawValue) } + } + + private func extrudeSurfaceControls(direction2: Bool) -> [PanelControl] { + let prefix = direction2 ? "surface2" : "surface" + var controls = [field(prefix, "Face or plane", direction2 ? \.surface2 : \.surface), + PanelControl(id: prefix + "Pick", kind: .buttons([(title: "Use Selected Face/Plane", action: { [unowned self] in useSelectedExtrudeSurface(direction2: direction2) })])), + note(prefix + "Note", "Planar limits only. Faces use their supporting plane.")] + if (direction2 ? form.endCondition2 : form.endCondition) == .offsetFromSurface { + controls += [field(prefix + "Offset", "Normal offset", unit: "mm", direction2 ? \.surfaceOffset2 : \.surfaceOffset), + check(prefix + "ReverseOffset", "Beyond surface", direction2 ? \.reverseSurfaceOffset2 : \.reverseSurfaceOffset)] + } + return controls + } + + private var extrudeContourControls: [PanelControl] { + var controls = [PanelControl(id: "allContours", kind: .check(label: "All closed regions", get: { [unowned self] in form.contours == nil }, set: { [unowned self] all in form.contours = all ? nil : [] })), + PanelControl(id: "pickContours", kind: .buttons([(title: form.activeBox == "contours" ? "Stop Picking Regions" : "Pick Regions in View", action: { [unowned self] in form.activeBox = form.activeBox == "contours" ? "" : "contours" })]))] + if let error = contourQueryError { controls.append(note("contourError", error, warning: true)) } + for (index, region) in contourChoices.enumerated() { + controls.append(PanelControl(id: "contour-" + region.id, kind: .check(label: "\(index + 1). \(region.title)", get: { [unowned self] in contourIsSelected(region) }, set: { [unowned self] selected in setContourSelected(region, selected) }))) + } + controls.append(note("contoursNote", "Each selected outer contour keeps its holes. Nested islands are independent regions.")) + return controls } // MARK: operations @@ -193,15 +216,17 @@ extension AppModel { } } if f.endCondition == .upToVertex { d1 += [field("vertexX", "Vertex X", unit: "mm", \.vertexX), field("vertexY", "Vertex Y", unit: "mm", \.vertexY), field("vertexZ", "Vertex Z", unit: "mm", \.vertexZ)] } + if f.endCondition.needsSurface { d1 += extrudeSurfaceControls(direction2: false) } s.append(PanelSection("Direction 1", controls: d1)) if f.endCondition != .midPlane && f.endCondition != .throughAllBoth { var d2: [PanelControl] = [ PanelControl(id: "end2", kind: .choice( - label: "End condition", options: [EndConditionUI.blind, .throughAll, .upToVertex].filter { $0 != .throughAll || !bodies.isEmpty }.map { ($0.rawValue, $0.rawValue) }, + label: "End condition", options: [EndConditionUI.blind, .throughAll, .upToVertex, .upToSurface, .offsetFromSurface].filter { $0 != .throughAll || !bodies.isEmpty }.map { ($0.rawValue, $0.rawValue) }, get: { [unowned self] in form.endCondition2.rawValue }, set: { [unowned self] in if let v = EndConditionUI(rawValue: $0) { form.endCondition2 = v } })), ] if f.endCondition2 == .blind { d2.append(field("depth2", "Depth", unit: "mm", \.depth2)) } if f.endCondition2 == .upToVertex { d2 += [field("vertex2X", "Vertex X", unit: "mm", \.vertex2X), field("vertex2Y", "Vertex Y", unit: "mm", \.vertex2Y), field("vertex2Z", "Vertex Z", unit: "mm", \.vertex2Z)] } + if f.endCondition2.needsSurface { d2 += extrudeSurfaceControls(direction2: true) } s.append(PanelSection("Direction 2", toggle: (get: { [unowned self] in form.direction2 }, set: { [unowned self] in form.direction2 = $0 }), controls: d2)) } var thin = [choice("thinType", "Type", [("one_direction", "One-Direction"), ("mid_plane", "Mid-Plane"), ("two_direction", "Two-Direction")], \.thinType), @@ -210,8 +235,8 @@ extension AppModel { if f.thinType == "one_direction" { thin.append(check("thinReverse", "Reverse (inside the profile)", \.thinReverse)) } s.append(PanelSection("Thin Feature", toggle: (get: { [unowned self] in form.thinOn }, set: { [unowned self] in form.thinOn = $0 }), controls: thin)) s.append(PanelSection("Selected Contours", controls: [ - sketchChoice, note("contoursNote", "All closed regions of the sketch are used; holes and islands are kept."), - ])) + sketchChoice, + ] + extrudeContourControls)) if op == .cutExtrude || f.merge && !bodies.isEmpty { var scope: [PanelControl] = [ PanelControl(id: "scopeAll", kind: .check(label: "All bodies", get: { [unowned self] in form.scope.isEmpty }, set: { [unowned self] all in diff --git a/Sources/ForgeUI/PropertyManager.swift b/Sources/ForgeUI/PropertyManager.swift index 3b19043..0f97fa5 100644 --- a/Sources/ForgeUI/PropertyManager.swift +++ b/Sources/ForgeUI/PropertyManager.swift @@ -11,7 +11,7 @@ import Observation /// SolidWorks' end conditions as shown in the Extrude page (the engine's body.extrude names). package enum EndConditionUI: String, CaseIterable { - case blind = "Blind", throughAll = "Through All", throughAllBoth = "Through All - Both", midPlane = "Mid Plane", upToVertex = "Up To Vertex" + case blind = "Blind", throughAll = "Through All", throughAllBoth = "Through All - Both", midPlane = "Mid Plane", upToVertex = "Up To Vertex", upToSurface = "Up To Surface", offsetFromSurface = "Offset From Surface" package var param: String { switch self { @@ -20,6 +20,8 @@ package enum EndConditionUI: String, CaseIterable { case .throughAllBoth: "through_all_both" case .midPlane: "mid_plane" case .upToVertex: "up_to_vertex" + case .upToSurface: "up_to_surface" + case .offsetFromSurface: "offset_from_surface" } } @@ -28,6 +30,7 @@ package enum EndConditionUI: String, CaseIterable { self = v } + package var needsSurface: Bool { self == .upToSurface || self == .offsetFromSurface } package var needsDepth: Bool { self == .blind || self == .midPlane } } @@ -39,6 +42,9 @@ package struct OperationForm { package var bodyOriginX = "0", bodyOriginY = "0", bodyOriginZ = "0" package var vertexX = "0", vertexY = "0", vertexZ = "10" package var vertex2X = "0", vertex2Y = "0", vertex2Z = "-10" + package var surface = "", surfaceOffset = "0", reverseSurfaceOffset = false + package var surface2 = "", surfaceOffset2 = "0", reverseSurfaceOffset2 = false + package var contours: [[String]]? package var depth = "10" package var endCondition = EndConditionUI.blind package var reverse = false @@ -97,6 +103,7 @@ extension AppModel { /// Start an operation: its page appears in the PropertyManager. package func begin(_ op: Operation) { form.result = nil + form.activeBox = "" switch op { case .moveBody: form.target = selectedBodies.first ?? bodies.first?.id ?? "" @@ -123,6 +130,11 @@ extension AppModel { form.draftOn = false form.thinOn = false form.scope = [] + form.contours = nil + if op == .extrude || op == .cutExtrude { + form.surface = selectedFace ?? selection.last(where: { $0.hasPrefix("plane-") }) ?? form.surface + Task { await refreshContourChoices() } + } if op == .cutExtrude { // A cut goes into the material: opposite to the sketch normal by default. form.reverse = true @@ -229,6 +241,10 @@ extension AppModel { let ec = p["end_condition"]?.stringValue ?? (p["direction"]?.stringValue == "mid_plane" ? "mid_plane" : "blind") form.endCondition = EndConditionUI(param: ec) ?? .blind form.depth = t(p["depth"]) ?? form.depth + form.surface = p["surface"]?.stringValue ?? "" + form.surfaceOffset = t(p["offset"]) ?? "0" + form.reverseSurfaceOffset = p["reverse_offset"]?.boolValue ?? false + form.contours = p["contours"]?.arrayValue?.map { $0.arrayValue?.compactMap(\.stringValue) ?? [] } if let v = p["vertex"]?.arrayValue, v.count == 3 { form.vertexX = t(v[0]) ?? "0"; form.vertexY = t(v[1]) ?? "0"; form.vertexZ = t(v[2]) ?? "0" } @@ -237,6 +253,9 @@ extension AppModel { form.direction2 = true form.endCondition2 = EndConditionUI(param: d2["end_condition"]?.stringValue ?? "blind") ?? .blind form.depth2 = t(d2["depth"]) ?? form.depth2 + form.surface2 = d2["surface"]?.stringValue ?? "" + form.surfaceOffset2 = t(d2["offset"]) ?? "0" + form.reverseSurfaceOffset2 = d2["reverse_offset"]?.boolValue ?? false if let v = d2["vertex"]?.arrayValue, v.count == 3 { form.vertex2X = t(v[0]) ?? "0"; form.vertex2Y = t(v[1]) ?? "0"; form.vertex2Z = t(v[2]) ?? "0" } @@ -433,7 +452,15 @@ extension AppModel { case .extrude, .cutExtrude: guard let sk = operationSketch else { return nil } var p: [String: JSONValue] = ["sketch": .string(sk), "end_condition": .string(form.endCondition.param)] + if let contours = form.contours { p["contours"] = .array(contours.map { .array($0.map(JSONValue.string)) }) } if form.endCondition.needsDepth { p["depth"] = quantity(form.depth) } + if form.endCondition.needsSurface { + p["surface"] = .string(form.surface) + if form.endCondition == .offsetFromSurface { + p["offset"] = quantity(form.surfaceOffset) + p["reverse_offset"] = .bool(form.reverseSurfaceOffset) + } + } if form.endCondition == .upToVertex { p["vertex"] = [quantity(form.vertexX), quantity(form.vertexY), quantity(form.vertexZ)] } if form.reverse && form.endCondition != .midPlane && form.endCondition != .throughAllBoth { p["reverse"] = true } if form.draftOn && !form.direction2 && form.endCondition != .midPlane && form.endCondition != .throughAllBoth { @@ -450,6 +477,13 @@ extension AppModel { if form.direction2 && form.endCondition != .midPlane && form.endCondition != .throughAllBoth { var d2: [String: JSONValue] = ["end_condition": .string(form.endCondition2.param)] if form.endCondition2 == .blind { d2["depth"] = quantity(form.depth2) } + if form.endCondition2.needsSurface { + d2["surface"] = .string(form.surface2) + if form.endCondition2 == .offsetFromSurface { + d2["offset"] = quantity(form.surfaceOffset2) + d2["reverse_offset"] = .bool(form.reverseSurfaceOffset2) + } + } if form.endCondition2 == .upToVertex { d2["vertex"] = [quantity(form.vertex2X), quantity(form.vertex2Y), quantity(form.vertex2Z)] } p["direction2"] = .object(d2) } @@ -724,7 +758,9 @@ extension AppModel { let f = form let placement = [f.bodyDX, f.bodyDY, f.bodyDZ, String(f.bodyCopy), String(f.bodyRotation), f.bodyAngle, f.bodyAxis, JSONCoding.string(.array(f.bodyCustomAxis)), f.bodyOriginX, f.bodyOriginY, f.bodyOriginZ, - f.vertexX, f.vertexY, f.vertexZ, f.vertex2X, f.vertex2Y, f.vertex2Z].joined(separator: "|") + f.vertexX, f.vertexY, f.vertexZ, f.vertex2X, f.vertex2Y, f.vertex2Z, + f.surface, f.surfaceOffset, String(f.reverseSurfaceOffset), f.surface2, f.surfaceOffset2, String(f.reverseSurfaceOffset2), + JSONCoding.string(f.contours.map { .array($0.map { .array($0.map(JSONValue.string)) }) } ?? .null)].joined(separator: "|") return [op.title, placement, operationSketch ?? "", f.depth, f.endCondition.rawValue, String(f.reverse), String(f.direction2), f.endCondition2.rawValue, f.depth2, String(f.merge), f.scope.joined(separator: ","), f.seeds.joined(separator: ","), f.linDirection, f.linSpacing, f.linCount, String(f.linReverse), String(f.linDirection2On), f.linDirection2, f.linSpacing2, f.linCount2, f.cirAxis, f.cirAngle, f.cirCount, String(f.cirEqual), diff --git a/Sources/ForgeUI/RibbonSpec.swift b/Sources/ForgeUI/RibbonSpec.swift index fb566ef..54448e1 100644 --- a/Sources/ForgeUI/RibbonSpec.swift +++ b/Sources/ForgeUI/RibbonSpec.swift @@ -27,11 +27,22 @@ package struct RibbonGroupSpec { extension AppModel { /// The groups of the current ribbon tab. package var ribbonGroups: [RibbonGroupSpec] { - switch ribbonTab { + let groups: [RibbonGroupSpec] = switch ribbonTab { case .features: featureGroups case .sketch: sketchGroups case .evaluate: evaluateGroups } + return [selectionGroup] + groups + } + + private var selectionGroup: RibbonGroupSpec { + RibbonGroupSpec(title: "Selection", buttons: SelectionFilter.allCases.map { filter in + button("filter-" + filter.rawValue, .part, filter.title, + help: "Filter viewport selection to \(filter.title.lowercased()); drawing tools and tree selection are unaffected", + active: selectionFilter == filter, large: false) { [unowned self] in Task { await setSelectionFilter(filter) } } + } + [button("selectOther", .hideShow, "Select Other (Tab)", + help: "Click geometry, then cycle through all candidates beneath that point, including occluded faces", + enabled: canSelectOther, large: false) { [unowned self] in Task { await selectOther() } }]) } private func button( diff --git a/Sources/ForgeUI/SelectionWorkflows.swift b/Sources/ForgeUI/SelectionWorkflows.swift new file mode 100644 index 0000000..35f86c6 --- /dev/null +++ b/Sources/ForgeUI/SelectionWorkflows.swift @@ -0,0 +1,71 @@ +import ForgeCommands +import ForgeCore +import ForgeRender +import ForgeSketch +import Foundation + +package struct ViewportPickContext { + var view: ViewProjection + var point: CGPoint + var current: String? + var style: RenderStyle +} + +extension SelectionFilter { + package var title: String { + switch self { case .all: "All Geometry"; case .bodies: "Bodies"; case .faces: "Faces"; case .edges: "Edges" } + } +} + +extension AppModel { + /// Extrusion pages collect model/contour picks even when opened directly from a + /// sketch drawing tool. Front ends share this routing decision for press and release. + package var viewportSketchPlane: SketchPlane? { + guard operation != .extrude, operation != .cutExtrude else { return nil } + return sketchState.tool == nil ? nil : sketchState.plane + } + + package func setSelectionFilter(_ filter: SelectionFilter) async { + await run("selection.set_filter", ["filter": .string(filter.rawValue)]) + } + + package var canSelectOther: Bool { + guard viewportSketchPlane == nil, let context = viewportPickContext else { return false } + return projection == nil || context.view == projection + } + + /// Shared desktop pick path. Filters apply to viewport geometry only; tree and + /// explicit command selections remain available regardless of the current filter. + package func viewportPick(at point: CGPoint, camera: Camera, width: Double, height: Double, extend: Bool, style: RenderStyle = .shadedWithEdges) async { + guard width > 0, height > 0, viewportSketchPlane == nil, let ds = scene.value else { return } + let version = sceneVersion + let view = ViewProjection(camera: camera, width: width, height: height) + let ray = camera.ray(pixelX: point.x, pixelY: point.y, width: width, height: height) + if await pickExtrusionContour(origin: ray.origin, direction: ray.direction) { viewportPickContext = nil; return } + guard sceneVersion == version, viewportSketchPlane == nil else { return } + let candidates = ds.pickCandidates(origin: ray.origin, direction: ray.direction, + edgeTolerance: 8 * camera.visibleHalfHeight / height, filter: selectionFilter, includeOccluded: false, style: style) + let ref = candidates.first + viewportPickContext = ViewportPickContext(view: view, point: point, current: ref, style: style) + await select(ref, extend: extend) + contextToolbarAt = ref == nil ? nil : point + } + + /// Recompute candidates from the current visible scene, never cached object IDs. + /// Each step replaces this click's candidate while retaining other selected entities. + package func selectOther() async { + guard canSelectOther, var context = viewportPickContext, let ds = scene.value else { return } + let view = context.view + let ray = view.camera.ray(pixelX: context.point.x, pixelY: context.point.y, width: view.width, height: view.height) + let refs = ds.pickCandidates(origin: ray.origin, direction: ray.direction, + edgeTolerance: 8 * view.camera.visibleHalfHeight / view.height, filter: selectionFilter, includeOccluded: true, style: context.style) + guard !refs.isEmpty else { viewportPickContext = nil; return } + let index = context.current.flatMap { refs.firstIndex(of: $0) }.map { ($0 + 1) % refs.count } ?? 0 + let ref = refs[index] + let preserved = selection.filter { $0 != context.current && $0 != ref } + context.current = ref + viewportPickContext = context + await run("selection.set", ["entities": .array((preserved + [ref]).map(JSONValue.string)), "mode": "replace"]) + contextToolbarAt = context.point + } +} diff --git a/Sources/ForgeWin/WinViewport.swift b/Sources/ForgeWin/WinViewport.swift index 69d3252..f26a9f6 100644 --- a/Sources/ForgeWin/WinViewport.swift +++ b/Sources/ForgeWin/WinViewport.swift @@ -68,7 +68,7 @@ final class WinViewport { private var scale: Float { fw_dpi_scale(app) } /// Sketch plane while a sketch tool is active (clicks become sketch coordinates). - private var sketchPlane: SketchPlane? { model.sketchState.tool == nil ? nil : model.sketchState.plane } + private var sketchPlane: SketchPlane? { model.viewportSketchPlane } /// Model units per pixel at the camera target. private var pixelSize: Double { 2 * camera.visibleHalfHeight / Double(max(height, 1)) } @@ -517,8 +517,8 @@ final class WinViewport { return } guard pressAt != nil, !dragged else { return } - let ref = reference(at: x, y) let extend = mods & (FW_MOD_SHIFT | FW_MOD_CTRL) != 0 - Task { await model.select(ref, extend: extend) } + let viewCamera = camera, viewWidth = Double(width), viewHeight = Double(height), viewStyle = style + Task { await model.viewportPick(at: CGPoint(x: x, y: y), camera: viewCamera, width: viewWidth, height: viewHeight, extend: extend, style: viewStyle) } } } diff --git a/Tests/ForgeCommandsTests/SelectionPickingTests.swift b/Tests/ForgeCommandsTests/SelectionPickingTests.swift new file mode 100644 index 0000000..230379f --- /dev/null +++ b/Tests/ForgeCommandsTests/SelectionPickingTests.swift @@ -0,0 +1,66 @@ +import ForgeCore +import ForgeRender +import Testing +@testable import ForgeCommands + +@Suite("Selection filters and candidate picking") +struct SelectionPickingTests { + private func engine() async throws -> Engine { + let e = Engine() + try await e.execute("document.new") + try await e.execute("body.create_box", ["width": 10, "height": 10, "depth": 10]) + try await e.execute("body.create_box", ["width": 10, "height": 10, "depth": 10, "origin": [0, 0, -20]]) + return e + } + + @Test func candidateCommandFindsOccludedBodiesAndRespectsFilterAndVisibility() async throws { + let e = try await engine() + try await e.execute("selection.set_filter", ["filter": "bodies"]) + let params: JSONValue = ["x": 200, "y": 200, "view": ["width": 400, "height": 400, "orientation": "front"]] + let all = try await e.execute("view.pick_candidates", params).result + #expect(all["candidates"] == ["body-1", "body-2"]) + let front = try await e.execute("view.pick_candidates", ["x": 200, "y": 200, + "include_occluded": false, "view": ["width": 400, "height": 400, "orientation": "front"]]).result + #expect(front["candidates"] == ["body-1"]) + try await e.execute("view.set_visibility", ["bodies": ["body-1"], "visible": false]) + let visible = try await e.execute("view.pick_candidates", params).result + #expect(visible["candidates"] == ["body-2"]) + let state = try await e.execute("document.state").result + #expect(state["selection_filter"] == "bodies") + // Filter is a viewing preference, preserved while model edits are undone. + try await e.execute("edit.undo") + #expect(await e.activeDocument?.selectionFilter == .bodies) + await #expect(throws: ForgeError.self) { + try await e.execute("view.pick_candidates", ["x": -1, "y": 20]) + } + await #expect(throws: ForgeError.self) { + try await e.execute("selection.set_filter", ["filter": "invalid"]) + } + } + + @Test func facesDeduplicateTrianglesAndEdgesRemainOccludedDuringNormalPicking() async throws { + let e = try await engine(), doc = try #require(await e.activeDocument) + let ds = try DocumentScene(document: doc) + let origin = Vec3(5, 5, 100), direction = Vec3(0, 0, -1) + let faces = ds.pickCandidates(origin: origin, direction: direction, edgeTolerance: 0, filter: .faces, includeOccluded: true) + #expect(faces.count == 4) + #expect(Set(faces).count == 4) + #expect(faces.prefix(2).allSatisfy { $0.hasPrefix("body-1/") }) + #expect(faces.suffix(2).allSatisfy { $0.hasPrefix("body-2/") }) + let edgeRay = Vec3(0, 5, 100) + let edges = ds.pickCandidates(origin: edgeRay, direction: direction, edgeTolerance: 0.05, filter: .edges, includeOccluded: false) + #expect(edges.count == 1) + #expect(edges.first?.hasPrefix("body-1/edge-") == true) + let allEdges = ds.pickCandidates(origin: edgeRay, direction: direction, edgeTolerance: 0.05, filter: .edges, includeOccluded: true) + #expect(allEdges.count == 4) + } + + @Test func explicitSelectionIsNotRestrictedAndNewDocumentResetsFilter() async throws { + let e = try await engine() + try await e.execute("selection.set_filter", ["filter": "edges"]) + try await e.execute("selection.set", ["entities": ["body-1"]]) + #expect(await e.activeDocument?.selection == ["body-1"]) + try await e.execute("document.new") + #expect(await e.activeDocument?.selectionFilter == .all) + } +} diff --git a/Tests/ForgeCommandsTests/SketchRegionTests.swift b/Tests/ForgeCommandsTests/SketchRegionTests.swift new file mode 100644 index 0000000..1e9a9ea --- /dev/null +++ b/Tests/ForgeCommandsTests/SketchRegionTests.swift @@ -0,0 +1,141 @@ +import ForgeCore +import Foundation +import Testing +@testable import ForgeCommands + +@Suite("Selected sketch regions") +struct SketchRegionTests { + func engine() async throws -> Engine { + let e = Engine() + try await e.execute("document.new") + try await e.execute("sketch.create", ["plane": "front"]) + return e + } + + func regions(_ e: Engine, at: JSONValue? = nil) async throws -> [JSONValue] { + var params: [String: JSONValue] = [:] + params["at"] = at + return try #require(try await e.execute("sketch.regions", .object(params)).result["regions"]?.arrayValue) + } + + @Test func selectedContourSurvivesLoopOrderingChangesAndRoundTrips() async throws { + let e = try await engine() + try await e.execute("sketch.add_rectangle", ["points": [[0, 0], [10, 20]]]) + try await e.execute("sketch.add_rectangle", ["points": [[30, 0], [35, 5]]]) + let choices = try await regions(e) + let selected = try #require(choices.first { $0["area_mm2"] == 200 }?["selector"]) + let preview = try await e.execute("body.extrude", ["depth": 3, "contours": .array([selected])], dryRun: true) + #expect(abs((volume(preview) ?? 0) - 600) < 1e-6) + #expect(await e.activeDocument!.bodies.isEmpty) + try await e.execute("body.extrude", ["depth": 3, "contours": .array([selected])]) + // Profile discovery places closed circles before chained lines; this changes old ordinals. + try await e.execute("sketch.add_circle", ["center": [50, 0], "radius": 2]) + try await e.execute("document.regenerate") + #expect(abs(try await e.activeDocument!.body("body-1").shape.massProperties().volume - 600) < 1e-6) + #expect(try await regions(e).contains { $0["selector"] == selected }) + let path = FileManager.default.temporaryDirectory.appendingPathComponent("forge-region-\(UUID().uuidString).forgepart") + defer { try? FileManager.default.removeItem(at: path) } + try await e.execute("document.save", ["path": .string(path.path)]) + let loaded = Engine() + try await loaded.execute("document.open", ["path": .string(path.path)]) + try await loaded.execute("document.regenerate") + #expect(abs(try await loaded.activeDocument!.body("body-1").shape.massProperties().volume - 600) < 1e-6) + #expect(await loaded.activeDocument!.features.last!.params["contours"] == .array([selected])) + } + + @Test func holesAndNestedIslandsRemainSeparateSelectableRegions() async throws { + let e = try await engine() + for radius in [10, 6, 2] { try await e.execute("sketch.add_circle", ["center": [0, 0], "radius": .number(Double(radius))]) } + let choices = try await regions(e) + #expect(choices.count == 2) + let ring = try #require(choices.first { ($0["holes"]?.arrayValue?.count ?? 0) == 1 }) + let island = try #require(choices.first { ($0["holes"]?.arrayValue?.count ?? 0) == 0 }) + #expect(abs(ring["area_mm2"]!.doubleValue! - 64 * .pi) < 1e-8) + #expect(abs(island["area_mm2"]!.doubleValue! - 4 * .pi) < 1e-8) + let onlyRing = try await e.execute("body.extrude", ["depth": 2, "contours": .array([ring["selector"]!])]) + #expect(abs((volume(onlyRing) ?? 0) - 128 * .pi) < 1e-6) + try await e.execute("edit.undo") + #expect(await e.activeDocument!.bodies.isEmpty) + try await e.execute("edit.redo") + #expect(abs(try await e.activeDocument!.body("body-1").shape.massProperties().volume - 128 * .pi) < 1e-6) + try await e.execute("feature.edit", ["feature": "feature-2", "params": ["contours": .array([ring["selector"]!, island["selector"]!])]]) + #expect(abs(try await e.activeDocument!.body("body-1").shape.massProperties().volume - 136 * .pi) < 1e-6) + #expect(try await regions(e, at: [8, 0]).first?["selector"] == ring["selector"]) + #expect(try await regions(e, at: [4, 0]).isEmpty) + #expect(try await regions(e, at: [0, 0]).first?["selector"] == island["selector"]) + #expect(try await regions(e, at: [20, 20]).isEmpty) + } + + @Test func explicitClosedContourCanIgnoreUnrelatedOpenGeometry() async throws { + let e = try await engine() + try await e.execute("sketch.add_rectangle", ["points": [[0, 0], [10, 5]]]) + let selector = try #require(try await regions(e).first?["selector"]) + try await e.execute("sketch.add_line", ["start": [30, 0], "end": [40, 0]]) + let query = try await e.execute("sketch.regions").result + #expect(query["profile_valid"] == false) + #expect(query["regions"]?.arrayValue?.count == 1) + await #expect(throws: ForgeError.self) { try await e.execute("body.extrude", ["depth": 2]) } + let result = try await e.execute("body.extrude", ["depth": 2, "contours": .array([selector])]) + #expect(abs((volume(result) ?? 0) - 100) < 1e-6) + } + + @Test func changedContourFailsExplicitlyInsteadOfSelectingAnotherRegion() async throws { + let e = try await engine() + try await e.execute("sketch.add_circle", ["center": [0, 0], "radius": 5]) + try await e.execute("sketch.add_circle", ["center": [20, 0], "radius": 2]) + let selected = try #require(try await regions(e).first { ($0["area_mm2"]?.doubleValue ?? 0) > 50 }?["selector"]) + let entity = try #require(selected.arrayValue?.first?.stringValue) + try await e.execute("body.extrude", ["depth": 2, "contours": .array([selected])]) + try await e.execute("sketch.split", ["entity": .string(entity), "at": [[5, 0], [-5, 0]]]) + #expect(await e.activeDocument!.bodies.isEmpty) + #expect(await e.activeDocument!.features.last?.status.error?.code == .referenceLost) + try await e.execute("edit.undo") + #expect(abs(try await e.activeDocument!.body("body-1").shape.massProperties().volume - 50 * .pi) < 1e-6) + } + + @Test func invalidDuplicateHoleAndCrossSketchSelectorsAreRejected() async throws { + let e = try await engine() + let outer = try await e.execute("sketch.add_circle", ["center": [0, 0], "radius": 10]).result["created"]!.arrayValue!.first! + let hole = try await e.execute("sketch.add_circle", ["center": [0, 0], "radius": 5]).result["created"]!.arrayValue!.first! + for contours in [JSONValue.array([]), .array([.array([])]), .array([.array([hole])]), .array([.array([outer, outer])]), + .array([.array([outer]), .array([outer])]), [["missing"]], [["sketch-99/circle-1"]]] { + await #expect(throws: ForgeError.self) { try await e.execute("body.extrude", ["depth": 1, "contours": contours]) } + } + #expect(await e.activeDocument!.bodies.isEmpty) + let qualified: JSONValue = .array([.array([.string("sketch-1/" + outer.stringValue!)])]) + let result = try await e.execute("body.extrude", ["depth": 1, "contours": qualified]) + #expect(abs((volume(result) ?? 0) - 75 * .pi) < 1e-6) + } + + @Test func cutUsesOnlyTheSelectedRegionAndTracksItsDimension() async throws { + let e = Engine() + try await e.execute("document.new") + try await e.execute("body.create_box", ["width": 30, "height": 10, "depth": 5]) + try await e.execute("sketch.create", ["plane": "front"]) + let circle = try await e.execute("sketch.add_circle", ["center": [5, 5], "radius": 2]).result["created"]!.arrayValue!.first! + try await e.execute("sketch.add_circle", ["center": [25, 5], "radius": 2]) + let selector = try #require(try await regions(e, at: [5, 5]).first?["selector"]) + let dimension = try await e.execute("sketch.add_dimension", ["type": "radius", "entities": .array([circle]), "value": 2]).result["constraints"]!.arrayValue!.first! + let cut = try await e.execute("body.extrude", ["operation": "cut", "depth": 5, "contours": .array([selector])]) + #expect(abs((volume(cut) ?? 0) - (1500 - 20 * .pi)) < 1e-6) + try await e.execute("sketch.set_dimension", ["constraint": dimension, "value": 3]) + #expect(abs(try await e.activeDocument!.body("body-1").shape.massProperties().volume - (1500 - 45 * .pi)) < 1e-6) + } + + + @Test func nestingUsesLoopTraversalWhenIndividualEdgesAreReversed() async throws { + let e = try await engine() + for endpoints in [JSONValue.array([[0, 0], [10, 0]]), [[10, 10], [10, 0]], [[10, 10], [0, 10]], [[0, 0], [0, 10]]] { + try await e.execute("sketch.add_line", ["start": endpoints.arrayValue![0], "end": endpoints.arrayValue![1]]) + } + try await e.execute("sketch.add_circle", ["center": [5, 5], "radius": 1]) + let choices = try await regions(e) + #expect(choices.count == 1) + let region = try #require(choices.first) + #expect(region["holes"]?.arrayValue?.count == 1) + #expect(abs(region["area_mm2"]!.doubleValue! - (100 - .pi)) < 1e-8) + let result = try await e.execute("body.extrude", ["depth": 1, "contours": .array([region["selector"]!])]) + #expect(abs((volume(result) ?? 0) - (100 - .pi)) < 1e-6) + } + +} diff --git a/Tests/ForgeCommandsTests/SurfaceExtrudeTests.swift b/Tests/ForgeCommandsTests/SurfaceExtrudeTests.swift new file mode 100644 index 0000000..c0f9ef1 --- /dev/null +++ b/Tests/ForgeCommandsTests/SurfaceExtrudeTests.swift @@ -0,0 +1,138 @@ +import ForgeCore +import Foundation +import Testing +@testable import ForgeCommands + +@Suite("Planar extrusion end conditions") +struct SurfaceExtrudeTests { + private func engine() async throws -> Engine { + let e = Engine() + try await e.execute("document.new") + return e + } + private func profile(_ e: Engine) async throws { + try await e.execute("sketch.create", ["plane": "front"]) + try await e.execute("sketch.add_rectangle", ["points": [[0, 0], [4, 3]]]) + try await e.execute("sketch.exit") + } + private func volume(_ e: Engine, _ body: String = "body-1") async throws -> Double { + try #require(try await e.execute("query.mass_properties", ["body": .string(body)]).result["volume_mm3"]?.doubleValue) + } + + @Test func parallelPlaneBothDirectionsOffsetsAndUndo() async throws { + let e = try await engine() + try await e.execute("plane.create", ["reference": "front", "offset": 10, "name": "Ceiling"]) + try await e.execute("plane.create", ["reference": "front", "offset": -5]) + try await profile(e) + try await e.execute("body.extrude", ["sketch": "sketch-1", "end_condition": "offset_from_surface", "surface": "Ceiling", "offset": "0.2 cm", "direction2": ["end_condition": "up_to_surface", "surface": "plane-2"]]) + #expect(abs(try await volume(e) - 12 * 13) < 1e-6) + let doc = try #require(await e.activeDocument) + let feature = try #require(doc.features.last) + #expect(feature.params["surface"] == "plane-1") + let parents = try await e.execute("feature.dependencies", ["feature": .string(feature.id)]).result["parents"] + #expect(parents?.arrayValue?.contains("feature-1") == true) + #expect(parents?.arrayValue?.contains("feature-2") == true) + try await e.execute("feature.edit", ["feature": .string(feature.id), "params": ["reverse_offset": true]]) + #expect(abs(try await volume(e) - 12 * 17) < 1e-6) + try await e.execute("edit.undo") + #expect(abs(try await volume(e) - 12 * 13) < 1e-6) + try await e.execute("edit.redo") + #expect(abs(try await volume(e) - 12 * 17) < 1e-6) + } + + @Test func reverseDirectionAndSecondDirectionOffset() async throws { + let e = try await engine() + try await e.execute("plane.create", ["reference": "front", "offset": 10]) + try await e.execute("plane.create", ["reference": "front", "offset": -5, "flip": true]) + try await profile(e) + try await e.execute("body.extrude", ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "plane-2", "reverse": true, + "direction2": ["end_condition": "offset_from_surface", "surface": "plane-1", "offset": 2]]) + #expect(abs(try await volume(e) - 12 * 13) < 1e-6) + let box = try await e.activeDocument!.body("body-1").shape.boundingBox() + #expect(abs(box.min.z + 5) < 1e-6 && abs(box.max.z - 8) < 1e-6) + } + + @Test func obliqueFaceUsesPerpendicularOffsetAndPersistentNames() async throws { + let e = try await engine() + try await e.execute("body.create_box", ["origin": [-50, -50, -2], "width": 100, "height": 100, "depth": 2]) + try await e.execute("body.transform", ["body": "body-1", "rotate": ["axis": [0, 1, 0], "angle": "30 deg"], "translate": [0, 0, 10]]) + let faces = try #require(try await e.execute("query.faces", ["body": "body-1"]).result["faces"]?.arrayValue) + let top = try #require(faces.first { $0["persistent_id"]?.stringValue?.contains("feature-1:+z") == true }) + let transient = try #require(top["id"]) + try await profile(e) + try await e.execute("body.extrude", ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": transient]) + let height = 10 - 2 * tan(Double.pi / 6) + #expect(abs(try await volume(e, "body-2") - 12 * height) < 1e-6) + let feature = try #require(await e.activeDocument?.features.last) + #expect(feature.params["surface"]?.stringValue?.contains("/face@") == true) + #expect(feature.references?.count == 1) + try await e.execute("feature.edit", ["feature": .string(feature.id), "params": ["end_condition": "offset_from_surface", "offset": 2]]) + #expect(abs(try await volume(e, "body-2") - 12 * (height - 2 / cos(Double.pi / 6))) < 1e-6) + try await e.execute("feature.edit", ["feature": "feature-2", "params": ["translate": [0, 0, 14]]]) + #expect(abs(try await volume(e, "body-2") - 12 * (height + 4 - 2 / cos(Double.pi / 6))) < 1e-6) + let newFaces = try #require(try await e.execute("query.faces", ["body": "body-2"]).result["faces"]?.arrayValue) + #expect(newFaces.contains { $0["persistent_id"]?.stringValue?.contains("\(feature.id):end_cap") == true }) + } + + @Test func planeRegenerationSuppressionSaveAndReopen() async throws { + let e = try await engine() + try await e.execute("plane.create", ["reference": "front", "offset": 10]) + try await profile(e) + try await e.execute("body.extrude", ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "plane-1"]) + try await e.execute("feature.edit", ["feature": "feature-1", "params": ["offset": 15]]) + #expect(abs(try await volume(e) - 180) < 1e-6) + try await e.execute("feature.suppress", ["feature": "feature-1"]) + #expect(await e.activeDocument?.features.last?.status.state == .error) + #expect(await e.activeDocument?.bodies.isEmpty == true) + try await e.execute("feature.suppress", ["feature": "feature-1", "suppressed": false]) + #expect(abs(try await volume(e) - 180) < 1e-6) + let path = FileManager.default.temporaryDirectory.appendingPathComponent("forge-surface-\(UUID().uuidString).forgepart") + defer { try? FileManager.default.removeItem(at: path) } + try await e.execute("document.save", ["path": .string(path.path)]) + try await e.execute("document.new") + try await e.execute("document.open", ["path": .string(path.path)]) + try await e.execute("document.regenerate") + #expect(abs(try await volume(e) - 180) < 1e-6) + } + + @Test func surfaceCutDryRunAndDependencyReorder() async throws { + let e = try await engine() + try await e.execute("body.create_box", ["width": 10, "height": 10, "depth": 10]) + try await e.execute("plane.create", ["reference": "front", "offset": 6]) + try await profile(e) + let params: JSONValue = ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "plane-1", "operation": "cut", "scope": ["body-1"]] + try await e.execute("body.extrude", params, dryRun: true) + #expect(abs(try await volume(e) - 1000) < 1e-6) + try await e.execute("body.extrude", params) + #expect(abs(try await volume(e) - (1000 - 4 * 3 * 6)) < 1e-6) + await #expect(throws: ForgeError.self) { + try await e.execute("feature.reorder", ["feature": "feature-4", "before": "feature-2"]) + } + #expect(abs(try await volume(e) - 928) < 1e-6) + } + + @Test func invalidLimitsAreAtomic() async throws { + let e = try await engine() + try await e.execute("plane.create", ["reference": "front", "offset": 10]) + try await e.execute("body.create_sphere", ["radius": 2, "center": [0, 0, 20]]) + try await profile(e) + let before = try #require(await e.activeDocument) + let bad: [JSONValue] = [ + ["sketch": "sketch-1", "end_condition": "up_to_surface"], + ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "plane-top"], + ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "plane-front"], + ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "body-1/face-0"], + ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "plane-1", "reverse": true], + ["sketch": "sketch-1", "end_condition": "offset_from_surface", "surface": "plane-1"], + ["sketch": "sketch-1", "end_condition": "offset_from_surface", "surface": "plane-1", "offset": -1], + ["sketch": "sketch-1", "end_condition": "offset_from_surface", "surface": "plane-1", "offset": 12], + ["sketch": "sketch-1", "end_condition": "up_to_surface", "surface": "plane-1", "draft": ["angle": "2 deg"]], + ["sketch": "sketch-1", "depth": 3, "surface": "plane-1"], + ] + for params in bad { + await #expect(throws: ForgeError.self) { try await e.execute("body.extrude", params) } + #expect(await e.activeDocument?.features.count == before.features.count) + #expect(await e.activeDocument?.bodyOrder == before.bodyOrder) + } + } +} diff --git a/Tests/ForgeRenderTests/CandidatePickingTests.swift b/Tests/ForgeRenderTests/CandidatePickingTests.swift new file mode 100644 index 0000000..9d814f2 --- /dev/null +++ b/Tests/ForgeRenderTests/CandidatePickingTests.swift @@ -0,0 +1,25 @@ +import ForgeCore +import ForgeKernel +import ForgeRender +import Testing + +@Suite("Candidate segment visibility") +struct CandidatePickingTests { + @Test func nearerOccludedSegmentCannotHideVisiblePartOfSameEdge() { + // The face is at z=5. Edge 7 bends from a visible x=.1 segment at z=6 + // around the side to an exactly-on-ray segment at z=0 behind that face. + let mesh = Mesh(positions: [-2,-2,5, 2,-2,5, 0,2,5], normals: [], indices: [0,1,2], triangleFaces: [3], + edgeOffsets: [0,6], edgeIDs: [7], + edgePoints: [0.1,-1,6, 0.1,1,6, 3,1,6, 3,1,0, 0,1,0, 0,-1,0]) + let scene = RenderScene(items: [RenderItem(objectID: 0, mesh: mesh, color: RGBA(1,1,1))]) + for includeOccluded in [false, true] { + let hits = RayPicker.candidates(scene, origin: Vec3(0,0,10), direction: Vec3(0,0,-1), + edgeTolerance: 0.2, includeOccluded: includeOccluded) + #expect(hits.count == 2) + #expect(hits.first?.element == .edge) + #expect(hits.first?.index == 7) + #expect(abs((hits.first?.point?.z ?? 0) - 6) < 1e-7) + #expect(hits.last?.element == .face) + } + } +} diff --git a/Tests/ForgeUITests/ExtrudeRegionSurfaceWorkflowTests.swift b/Tests/ForgeUITests/ExtrudeRegionSurfaceWorkflowTests.swift new file mode 100644 index 0000000..3ec8dda --- /dev/null +++ b/Tests/ForgeUITests/ExtrudeRegionSurfaceWorkflowTests.swift @@ -0,0 +1,158 @@ +import ForgeCore +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop selected contours and surface limits") +struct ExtrudeRegionSurfaceWorkflowTests { + private func model() async -> AppModel { + let m = AppModel() + await m.bootstrap() + return m + } + private func twoRegions(_ m: AppModel) async { + await m.run("sketch.create", ["plane": "front"]) + await m.run("sketch.add_rectangle", ["points": [[0, 0], [10, 10]]]) + await m.run("sketch.add_circle", ["center": [5, 5], "radius": 2]) + await m.run("sketch.add_rectangle", ["points": [[20, 0], [25, 5]]]) + await m.run("sketch.exit") + } + + @Test func panelChecklistSelectsOneRegionKeepsHoleAndSurvivesFeatureEditing() async throws { + let m = await model() + await twoRegions(m) + m.begin(.extrude) + await m.refreshContourChoices() + #expect(m.contourChoices.count == 2) + let region = try #require(m.contourChoices.first { $0.area > 50 }) + let all = try #require(m.panelPage.sections.flatMap(\.controls).first { $0.id == "allContours" }) + guard case .check(_, _, let setAll) = all.kind else { Issue.record("Expected all-region checkbox"); return } + setAll(false) + let check = try #require(m.panelPage.sections.flatMap(\.controls).first { $0.id == "contour-" + region.id }) + guard case .check(_, _, let setRegion) = check.kind else { Issue.record("Expected region checkbox"); return } + setRegion(true) + m.form.depth = "3" + let key = m.previewKey + m.form.contours = nil + #expect(m.previewKey != key) + m.form.contours = [region.selector] + await m.updatePreview() + #expect(m.preview.items.count == 1) + await m.commitOperation() + #expect(m.lastError == nil) + let before = try #require(await m.engine.activeDocument?.body("body-1")) + #expect(abs(try before.shape.massProperties().volume - (100 - 4 * .pi) * 3) < 1e-6) + let feature = try #require(m.features.last) + m.editFeature(feature) + await m.editTask?.value + #expect(m.form.contours == [region.selector]) + await m.commitOperation() + let after = try #require(await m.engine.activeDocument?.body("body-1")) + #expect(abs(try after.shape.massProperties().volume - (100 - 4 * .pi) * 3) < 1e-6) + } + + @Test func viewportRegionPickingIgnoresHolesAndTogglesSelectedRegion() async throws { + let m = await model() + await twoRegions(m) + m.begin(.extrude) + await m.refreshContourChoices() + m.form.activeBox = "contours" + #expect(await m.pickExtrusionContour(origin: Vec3(2, 2, 100), direction: Vec3(0, 0, -1))) + #expect(m.form.contours?.count == 1) + let selected = m.form.contours + #expect(await m.pickExtrusionContour(origin: Vec3(5, 5, 100), direction: Vec3(0, 0, -1))) + #expect(m.lastError?.code == .invalidParams) + #expect(m.form.contours == selected) + #expect(await m.pickExtrusionContour(origin: Vec3(2, 2, 100), direction: Vec3(0, 0, -1))) + #expect(m.form.contours?.isEmpty == true) + m.form.activeBox = "" + #expect(await m.pickExtrusionContour(origin: Vec3(2, 2, 100), direction: Vec3(0, 0, -1)) == false) + } + + @Test func surfaceAndOffsetBothDirectionsPreviewAndEditorRoundtrip() async throws { + let m = await model() + await m.run("plane.create", ["reference": "front", "offset": 10]) + await m.run("plane.create", ["reference": "front", "offset": -5]) + await m.run("sketch.create", ["plane": "front"]) + await m.run("sketch.add_rectangle", ["points": [[0, 0], [4, 3]]]) + await m.run("sketch.exit") + m.begin(.extrude) + m.form.endCondition = .offsetFromSurface + await m.select(["plane-1"]) + m.useSelectedExtrudeSurface() + #expect(m.form.surface == "plane-1") + m.form.surfaceOffset = "0.2 cm" + m.form.direction2 = true + m.form.endCondition2 = .upToSurface + await m.select(["plane-2"]) + m.useSelectedExtrudeSurface(direction2: true) + #expect(m.form.surface2 == "plane-2") + await m.updatePreview() + let bounds = try #require(m.preview.items.first?.mesh.bounds) + #expect(abs(bounds.min.z + 5) < 1e-5 && abs(bounds.max.z - 8) < 1e-5) + await m.commitOperation() + #expect(m.lastError == nil) + let feature = try #require(m.features.last) + m.editFeature(feature) + await m.editTask?.value + #expect(m.form.endCondition == .offsetFromSurface && m.form.endCondition2 == .upToSurface) + #expect(m.form.surface == "plane-1" && m.form.surface2 == "plane-2") + #expect(m.form.surfaceOffset == "0.2 cm") + await m.commitOperation() + let body = try #require(await m.engine.activeDocument?.body("body-1")) + #expect(abs(try body.shape.massProperties().volume - 156) < 1e-6) + } + + @Test func surfaceFieldsInvalidatePreviewAndChangingSketchClearsContourIntent() async throws { + let m = await model() + await twoRegions(m) + m.begin(.extrude) + await m.refreshContourChoices() + m.form.contours = [try #require(m.contourChoices.first).selector] + for path in [\OperationForm.surface, \.surfaceOffset, \.surface2, \.surfaceOffset2] { + let old = m.previewKey + m.form[keyPath: path] += "1" + #expect(m.previewKey != old) + } + var old = m.previewKey + m.form.reverseSurfaceOffset.toggle() + #expect(m.previewKey != old) + old = m.previewKey + m.form.reverseSurfaceOffset2.toggle() + #expect(m.previewKey != old) + m.operationSketch = nil + #expect(m.form.contours == nil && m.contourChoices.isEmpty) + } + + @Test func qualifiedContourSelectorsRoundTripThroughChecklistWithoutDuplicates() async throws { + let m = await model() + await twoRegions(m) + m.begin(.extrude) + await m.refreshContourChoices() + let choice = try #require(m.contourChoices.first) + let sketch = try #require(m.operationSketch) + m.form.contours = [choice.selector.map { sketch + "/" + $0 }] + #expect(m.contourIsSelected(choice)) + m.setContourSelected(choice, true) + #expect(m.form.contours == [choice.selector]) + await m.updatePreview() + #expect(m.previewError == nil) + m.setContourSelected(choice, false) + #expect(m.form.contours?.isEmpty == true) + } + + + @Test func concurrentContourRefreshesAllAwaitPopulatedChoices() async throws { + let m = await model() + await twoRegions(m) + m.begin(.extrude) + let requests = (0..<5).map { _ in Task { @MainActor in + await m.refreshContourChoices() + return m.contourChoices.count + } } + for request in requests { #expect(await request.value == 2) } + #expect(m.contourQueryError == nil) + } + +} diff --git a/Tests/ForgeUITests/SelectionWorkflowTests.swift b/Tests/ForgeUITests/SelectionWorkflowTests.swift new file mode 100644 index 0000000..07e3ecd --- /dev/null +++ b/Tests/ForgeUITests/SelectionWorkflowTests.swift @@ -0,0 +1,126 @@ +import ForgeCommands +import ForgeCore +import ForgeRender +import Foundation +import Testing +@testable import ForgeUI + +@MainActor +@Suite("Desktop filtered selection and Select Other") +struct SelectionWorkflowTests { + private func model() async -> AppModel { + let m = AppModel() + await m.bootstrap() + await m.run("body.create_box", ["width": 10, "height": 10, "depth": 10]) + await m.run("body.create_box", ["width": 10, "height": 10, "depth": 10, "origin": [0, 0, -20]]) + return m + } + private func camera() -> Camera { + var camera = Camera(target: Vec3(5, 5, 0), distance: 100, orthoHalfHeight: 20) + camera.setOrientation(.front) + return camera + } + private func click(_ m: AppModel, at point: CGPoint = CGPoint(x: 200, y: 200), extend: Bool = false) async { + m.projection = ViewProjection(camera: camera(), width: 400, height: 400) + await m.viewportPick(at: point, camera: camera(), width: 400, height: 400, extend: extend) + } + + @Test func bodyFilterCyclesThroughOccludedBodyAndWraps() async throws { + let m = await model() + await m.setSelectionFilter(.bodies) + await click(m) + #expect(m.selection == ["body-1"]) + #expect(m.canSelectOther) + await m.selectOther() + #expect(m.selection == ["body-2"]) + await m.selectOther() + #expect(m.selection == ["body-1"]) + // Recompute against the current scene, never resurrect a hidden candidate. + await m.setBodiesVisible(["body-2"], false) + await m.selectOther() + #expect(m.selection == ["body-1"]) + await m.setBodiesVisible(["body-1"], false) + await m.selectOther() + #expect(!m.canSelectOther) + } + + @Test func filtersSelectFacesEdgesAndBodiesAtSameBoundary() async throws { + let m = await model() + let boundary = CGPoint(x: 150, y: 200) + await m.setSelectionFilter(.faces) + await click(m, at: boundary) + #expect(m.selection.first?.contains("/face-") == true) + await m.setSelectionFilter(.edges) + #expect(!m.canSelectOther) + await click(m, at: boundary) + #expect(m.selection.first?.contains("/edge-") == true) + await m.setSelectionFilter(.bodies) + await click(m, at: boundary) + #expect(m.selection == ["body-1"]) + // Empty interior has no edge hit, so normal replacement clears selection. + await m.setSelectionFilter(.edges) + await click(m) + #expect(m.selection.isEmpty) + } + + @Test func cyclingPreservesOtherSelectionsAndCameraChangeDisablesIt() async throws { + let m = await model() + await m.setSelectionFilter(.faces) + await m.select("plane-front", extend: false) + await click(m, extend: true) + let first = try #require(m.selection.last) + #expect(m.selection.count == 2) + await m.selectOther() + #expect(m.selection.count == 2) + #expect(m.selection.first == "plane-front") + #expect(m.selection.last != first) + var changed = camera() + changed.orbit(dx: 0.2, dy: 0) + m.projection = ViewProjection(camera: changed, width: 400, height: 400) + #expect(!m.canSelectOther) + let prior = m.selection + await m.selectOther() + #expect(m.selection == prior) + } + + @Test func activeDrawingToolYieldsToExtrusionContourPickingOnAllDesktops() async throws { + let m = AppModel() + await m.bootstrap() + await m.newSketch(on: .front) + await m.run("sketch.add_rectangle", ["points": [[0, 0], [10, 10]]]) + m.chooseTool(.circle) + #expect(m.viewportSketchPlane != nil) + m.begin(.extrude) + await m.refreshContourChoices() + m.form.activeBox = "contours" + #expect(m.activeSketch != nil) + #expect(m.viewportSketchPlane == nil) + let count = m.sketchState.sketch?.orderedEntities.count + await click(m) + #expect(m.form.contours?.count == 1) + #expect(m.sketchState.sketch?.orderedEntities.count == count) + #expect(!m.canSelectOther) + await click(m) + #expect(m.form.contours?.isEmpty == true) + } + + @Test func allGeometryPickingRespectsWireframeAndShadedDisplay() async throws { + let m = await model() + await m.viewportPick(at: CGPoint(x: 200, y: 200), camera: camera(), width: 400, height: 400, extend: false, style: .wireframe) + #expect(m.selection.isEmpty) + await m.viewportPick(at: CGPoint(x: 150, y: 200), camera: camera(), width: 400, height: 400, extend: false, style: .shaded) + #expect(m.selection.first?.contains("/face-") == true) + await m.viewportPick(at: CGPoint(x: 150, y: 200), camera: camera(), width: 400, height: 400, extend: false, style: .wireframe) + #expect(m.selection.first?.contains("/edge-") == true) + } + + @Test func selectionControlsExistOnEveryDesktopRibbonTab() async throws { + let m = await model() + for tab in [RibbonTab.features, .sketch, .evaluate] { + m.ribbonTab = tab + let group = try #require(m.ribbonGroups.first { $0.title == "Selection" }) + #expect(group.buttons.filter { $0.id.hasPrefix("filter-") }.count == 4) + #expect(group.buttons.contains { $0.id == "selectOther" }) + } + } +} diff --git a/Tests/GoldenModelTests/Models/027_selected_annulus_to_offset_plane.json b/Tests/GoldenModelTests/Models/027_selected_annulus_to_offset_plane.json new file mode 100644 index 0000000..351fe0c --- /dev/null +++ b/Tests/GoldenModelTests/Models/027_selected_annulus_to_offset_plane.json @@ -0,0 +1,99 @@ +{ + "forge_script": 1, + "name": "027_selected_annulus_to_offset_plane", + "description": "Select only R5/R2 annular region, ignore separate R3 region. Normal plane offset10, stop2mm short: volume=pi*(25-4)*8=168pi.", + "commands": [ + { + "command": "document.new", + "params": {} + }, + { + "command": "plane.create", + "params": { + "reference": "front", + "offset": 10 + } + }, + { + "command": "sketch.create", + "params": { + "plane": "front" + } + }, + { + "command": "sketch.add_circle", + "params": { + "center": [ + 0, + 0 + ], + "radius": 5 + } + }, + { + "command": "sketch.add_circle", + "params": { + "center": [ + 0, + 0 + ], + "radius": 2 + } + }, + { + "command": "sketch.add_circle", + "params": { + "center": [ + 20, + 0 + ], + "radius": 3 + } + }, + { + "command": "body.extrude", + "params": { + "sketch": "sketch-1", + "contours": [ + [ + "circle-1" + ] + ], + "end_condition": "offset_from_surface", + "surface": "plane-1", + "offset": 2 + } + } + ], + "expect": { + "body_count": 1, + "bodies": [ + { + "body": "body-1", + "volume_mm3": { + "value": 527.7875658030853, + "tol": 1e-06 + }, + "bbox_min": { + "value": [ + -5, + -5, + 0 + ], + "tol": 1e-06 + }, + "bbox_max": { + "value": [ + 5, + 5, + 8 + ], + "tol": 1e-06 + }, + "faces": 4, + "valid": true, + "closed": true + } + ] + } +} diff --git a/Tests/IntegrationTests/test_mcp_stdio.py b/Tests/IntegrationTests/test_mcp_stdio.py index 5ab6f0a..037973b 100644 --- a/Tests/IntegrationTests/test_mcp_stdio.py +++ b/Tests/IntegrationTests/test_mcp_stdio.py @@ -114,6 +114,44 @@ def test_curved_slot_measurement_and_body_visibility(self): self.assertEqual(reopened[3]["result"]["structuredContent"]["result"]["visible_bodies"], ["body-1"]) self.assertAlmostEqual(reopened[4]["result"]["structuredContent"]["from_entity"]["volume_mm3"], 72 * math.pi, places=6) + def test_selected_contour_surface_limit_and_selection_filters(self): + import math + executable = os.environ.get("FORGE_CLI", ".build/debug/forge-cli") + with tempfile.TemporaryDirectory() as temporary: + saved = str(Path(temporary) / "selected-region.forgepart") + responses = self.run_calls(executable, [ + ("new_document", {}), + ("execute", {"command": "plane.create", "params": {"reference": "front", "offset": 10}}), + ("execute", {"command": "sketch.create", "params": {"plane": "front"}}), + ("execute", {"command": "sketch.add_circle", "params": {"center": [0, 0], "radius": 5}}), + ("execute", {"command": "sketch.add_circle", "params": {"center": [0, 0], "radius": 2}}), + ("execute", {"command": "sketch.add_circle", "params": {"center": [20, 0], "radius": 3}}), + ("execute", {"command": "sketch.regions", "params": {"sketch": "sketch-1", "at": [4, 0]}}), + ("execute", {"command": "sketch.exit", "params": {}}), + ("execute", {"command": "body.extrude", "params": {"sketch": "sketch-1", "contours": [["circle-1"]], + "end_condition": "offset_from_surface", "surface": "plane-1", "offset": 2}}), + ("measure", {"from": "body-1"}), + ("execute", {"command": "selection.set_filter", "params": {"filter": "faces"}}), + ("execute", {"command": "document.state", "params": {}}), + ("save", {"path": saved}), + ]) + for response in responses: + self.assertFalse(response["result"]["isError"], response) + regions = responses[6]["result"]["structuredContent"]["result"]["regions"] + self.assertEqual(len(regions), 1) + self.assertEqual(regions[0]["selector"], ["circle-1"]) + self.assertEqual(regions[0]["holes"], [["circle-3"]]) + self.assertAlmostEqual(responses[9]["result"]["structuredContent"]["from_entity"]["volume_mm3"], 168 * math.pi, places=6) + self.assertEqual(responses[11]["result"]["structuredContent"]["result"]["selection_filter"], "faces") + reopened = self.run_calls(executable, [ + ("open", {"path": saved}), ("rebuild", {}), ("measure", {"from": "body-1"}), + ("execute", {"command": "document.state", "params": {}}), + ]) + for response in reopened: + self.assertFalse(response["result"]["isError"], response) + self.assertAlmostEqual(reopened[2]["result"]["structuredContent"]["from_entity"]["volume_mm3"], 168 * math.pi, places=6) + self.assertEqual(reopened[3]["result"]["structuredContent"]["result"]["selection_filter"], "all") + def run_calls(self, executable, calls): messages = [{"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {"protocolVersion": "2025-11-25"}}] messages.extend({"jsonrpc": "2.0", "id": index + 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}} diff --git a/docs/research/modeling-workflow-gaps.md b/docs/research/modeling-workflow-gaps.md index 162df92..5cb081c 100644 --- a/docs/research/modeling-workflow-gaps.md +++ b/docs/research/modeling-workflow-gaps.md @@ -60,6 +60,26 @@ freedom, width editing, construction, atomic validation, undo and persistence. G Fix Slot/Equal Slots relations remain pending. +## Further delivery: selected contours, planar limits and selection filters + +Extrusions now store complete outer-curve ID sets as contour intent. Region discovery +returns holes, nested islands, analytic area, sampled display outlines and point hits. +Desktop checklists and explicit ray picking share these selectors, including while +starting an extrusion from an active drawing tool. Unrelated open geometry can be ignored +for explicit selections; crossing/branching sketches still need intersection-cell decomposition. + +Planar Up To Surface and Offset From Surface use exact clipped geometry for parallel or +oblique limits, true perpendicular offset, both directions, persistent references and +upstream dependency tracking. The supporting plane of a face is extended. Curved limits, +Translate Surface, Up To Next and draft combined with surface limits remain pending. +[Official Extrude PropertyManager](https://help.solidworks.com/2021/english/solidworks/sldworks/r_extrude_propertymanager.htm). + +All/body/face/edge filters and Select Other candidate cycling now share CPU ray candidate +queries across the native desktops and MCP. Hidden bodies and reference overlays are +excluded. Filters are session preferences; explicit/tree selections stay unrestricted. +The UI provides Tab/ribbon/menu cycling. Radial candidate UI, vertex filters, hover previews +and chain/tangent selection remain pending. + ## How to interpret the evidence - **Engine available, guided UI missing** means there is a registered command but no