Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion openspec/EDITOR.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ Scene
| 41 | `41-editor-op-stack` | 1.12.0 | Неразрушающий стек операций объекта + дерево/timeline, булевы между телами, Mirror, Linear/Circular Pattern, Hollow, Offset, Apply/Flatten |
| 42 | `42-editor-mesh-repair` | 1.13.0 | Диагностика и ремонт STL (дыры, нормали, самопересечения, Make Solid), Decimate, Smooth, Lay on Face, измерения (расстояние/угол/толщина), анализ нависаний |
| 43 | `43-editor-cut-split` | 1.14.0 | Plane Cut, Split по столу с соединителями (шипы/ласточкин хвост из `06a`), отверстия под магниты/винты в произвольном месте, текст на грани |
| 44 | `44-editor-face-tools` | 1.15.0 | Выбор граней/рёбер, Push/Pull грани, Fillet/Chamfer рёбер, эскиз на грани, Hole wizard |
| 44 | `44-editor-face-tools` | 1.15.0 | Выбор граней/рёбер, Push/Pull грани, Fillet/Chamfer рёбер, эскиз на грани (Hole wizard — в 43) |
| 45 | `45-editor-project-default` | 2.0.0 | Файл проекта `.pkit` (сохранить/открыть), автосохранение с восстановлением, **редактор — вход по умолчанию** (`/` ведёт в редактор, генераторы — раздел «Генераторы»; major: маршрут `/` меняется), «открыть генератор как объект сцены» (деталь из Gridfinity/Rack/Keychain вставляется в редактор) |

Жёсткий порядок: `39` → `40`/`42` независимы после `39` → `41` после `40` (нужны тела из эскиза), `43` после `41` и `42`, `44` после `41`, `45` последним.
Expand Down
2 changes: 1 addition & 1 deletion openspec/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
| 41 | `41-editor-op-stack` | 40 | v1.12.0. Неразрушающий стек операций (пересчёт от источников, `EDITOR.md` 2a), дерево/timeline, булевы, Mirror, Pattern, Hollow, Offset |
| 42 | `42-editor-mesh-repair` | 41 | v1.13.0. Диагностика и ремонт STL, Decimate, Smooth, Lay on Face, измерения, анализ нависаний |
| 43 | `43-editor-cut-split` | 41, 42 | v1.14.0. Plane Cut, Split на стол с соединителями (шипы, штифты, магниты, ласточкин хвост), инструмент «Отверстие» (винты, вставки, магниты) и текст на грани |
| 44 | `44-editor-face-tools` | 41 | v1.15.0 (план). Выбор граней/рёбер, Push/Pull, Fillet/Chamfer, эскиз на грани, Hole wizard |
| 44 | `44-editor-face-tools` | 41, 42 | v1.15.0. Режимы выбора граней/рёбер (распознавание по мешу), Push/Pull, Fillet/Chamfer прямых и круговых рёбер, эскиз на грани с проекцией рёбер (Hole wizard перенесён в 43) |
| 45 | `45-editor-project-default` | 43, 44 | v2.0.0 (план, major: `/` ведёт в редактор). Файл проекта `.pkit` (ZIP: scene.json + сетки), автосохранение, редактор — вход по умолчанию, генераторы как вставляемые объекты |

```mermaid
Expand Down
2 changes: 2 additions & 0 deletions openspec/changes/44-editor-face-tools/.openspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-27
40 changes: 40 additions & 0 deletions openspec/changes/44-editor-face-tools/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Design

## Context

The kernel is a triangle mesh (`manifold-3d`). Faces and edges of a B-rep do not exist, but what users call a face or an edge can be recognised: a flat region, a smooth patch, a chain of sharp edges. `42` already provides `planarRegion`. The risk, noted in `EDITOR.md`, is the "topological naming problem": references to recognised elements break when the model changes. The approach here: references describe *geometry* (a point, a normal, a kind and the region's approximate extent) and are re-resolved against the current mesh each time; ambiguity or absence is an explicit failure.

## Goals / Non-Goals

**Goals**: faces and edges you can select with the mouse on any mesh; Push/Pull, Fillet and Chamfer for the common planar/circular cases; sketch on face; references that survive reasonable edits.
**Non-Goals**: a full B-rep, complete fillet theory, constrained face relations.

## Decisions

1. **Recognition (`topology/faces.ts`).** On a (cached) adjacency structure of the mesh: a *flat region* is grown from a seed triangle over edge-adjacent triangles with normal angle ≤ 1° to the seed normal and plane distance ≤ 0.02 mm; a *smooth patch* is grown by dihedral angle ≤ threshold (default 30°) between neighbouring triangles. Result: `FaceRegion {tris, kind: 'planar'|'cylinder'|'cone'|'sphere'|'smooth', plane?, axis?, radius?, area, centroid, boundaryLoops}`; primitive classification by least-squares fit with residual limits (cylinder/cone/sphere), used for messages and snapping, not required for planar operations. Segmentation of the whole mesh (all regions) is computed once per mesh version in the worker and cached by mesh hash; picking uses the region id per triangle.
2. **Edges (`topology/edges.ts`).** Feature edges are mesh edges whose dihedral angle exceeds the threshold (default 30°); chains join edges through vertices where exactly two feature edges meet; each chain is classified `line` (max deviation from the best-fit line ≤ 0.02 mm), `circle` (planar, radius fit residual ≤ 0.02 mm, arcs allowed) or `free`. Convex/concave is the sign of the dihedral. Edge ids are per mesh version.
3. **References (`topology/reference.ts`).** `FaceRef {kind:'face', point, normal, extent}` and `EdgeRef {kind:'edge', shape: line|circle, p0, p1 | centre, axis, radius}` in object-local space. `resolveFace(mesh, ref)` finds the region whose plane contains `point` within tolerance and whose normal matches within 5°, preferring the region containing the point; if two or none qualify the result is `ambiguous`/`missing`. `resolveEdge` similarly by geometry. The tolerance scales with the bounding box (tight 0.02 mm up to 1e-4 × diagonal). Operations store refs; evaluation resolves them against the solid *before* the operation, so earlier edits are accounted for.
4. **Push / Pull (`ops/pushPull.ts`).** For a planar region with outline loops projected to its plane: build `CrossSection` polygons (outer loops with holes, EvenOdd), extrude along the normal by *d* (`Manifold.extrude`, positive) and union with the body; for negative *d*, subtract the same prism extruded inwards. Faces whose region is not planar are refused (`face.error.notPlanar`). The prism overlaps the body by 0.01 mm to guarantee a watertight union. Multiple regions with the same plane and normal are processed together. A negative distance larger than the available material is clamped and reports the limit.
5. **Edge chamfer / fillet (`ops/edgeBreak3d.ts`).** Per chain:
- *straight edge between two planar faces*: the tool is a prism along the edge whose cross-section is, for a chamfer, the triangle cut off by the symmetric distance (convex) or the triangle to fill (concave); for a fillet, the region between the corner and the arc tangent to both faces (polygonal arc, segment count from the 0.02 mm sagitta, 4–24). Convex: subtract; concave: union. Ends are cut by the planes of the adjacent faces so the tool does not overshoot; a prism end that meets another selected chain is mitre-cut by the bisecting plane.
- *circular edge between planar/cylindrical faces* (rim of a cylinder, hole edge): the tool is the same cross-section revolved about the fitted axis (`Manifold.revolve`).
- *chains of mixed straight and circular segments* (rounded rectangle outline): tools per segment with tangent joins; the circular segment tools are revolved and the straight ones are prisms; joints are made watertight by overlapping 0.01 mm.
Limits: size ≤ 0.5 × the shorter adjacent face extent measured across the edge (otherwise `edge.error.tooLarge` with the maximum), dihedral between 20° and 160° (outside is refused with the reason), adjacent faces must be planar or cylindrical. Corner vertices where three selected edges meet use mitred prisms; the blend is a visible approximation and documented as such in the UI help text.
6. **Sketch on face.** The sketch plane gets a second kind `{face: FaceRef, frame}`: origin at the picked point projected on the face, z = face normal, x = direction of the longest straight boundary edge (fallback: the projection of the world X onto the plane, then world Y). `frame` caches the last resolved frame; `resolveFace` is retried when the body changes; if it fails, the cached frame is used and the sketch is flagged `detached` (the user can re-pick the face). Projected geometry: boundary loops become lines (straight chains) and arcs/circles (circular chains) with coincident points; `construction` or real by the user's choice; projected geometry is *not* kept in sync with later changes (explicit refresh button), which avoids hidden dependencies.
7. **Highlight and picking in the viewport.** Selection state `{mode, ids}` lives in the editor state; region membership is rendered through a per-triangle colour attribute (hover/selected) on a lightweight overlay mesh drawn with polygon offset, edges as line segments; picking resolves the triangle under the cursor to a region/edge id through the cached segmentation (ray against mesh with the BVH from `42`; edge picking by screen distance to chain polylines, 6 px).
8. **Performance.** Segmentation and edges for 500k triangles must finish in the worker within a few seconds with a progress job; the Face/Edge modes are available for meshes up to a limit (default 1.5 M triangles) with a clear message otherwise; results are cached by mesh hash and shared by hover, selection and operations.
9. **Stack integration.** `pushPull {faces: FaceRef[], distance}`, `edgeBreak {edges: EdgeRef[], kind: chamfer|fillet, size}` are `41` stack operations: editable, reorderable, suppressible; failed refs fail the operation with `face.error.missing|ambiguous` / `edge.error.*` and the reason.
10. **Selection state is not history**, but the operations that use it are. Escape clears; Delete in Face mode is not defined (out of scope).

## Risks / Trade-offs

- **Reference stability** is the weakest point: geometry-based references fail after large edits. Mitigation: failures are explicit and local to one operation; re-picking is one click; tolerances scale with the model; this is documented in the user-visible messages.
- **Fillet visual quality**: faceted arcs and approximate corners. Segment count follows a tolerance; export quality matters more than the on-screen preview, so the preview is coarser and the export rebuild uses the fine setting.
- **Segmentation of noisy scans** produces many tiny regions; the UI suggests Smooth/Decimate from `42` and offers a larger angle threshold.
- **Watertightness of unions** relies on small overlaps; covered by validity tests on every tool shape.
- **Scope creep** toward a general modelling kernel: operations are limited to what the recognised geometry supports and refuse the rest with a reason.

## Open Questions

- Default dihedral threshold for feature edges (30°) and the flat-region tolerance (1°) — tuned on five reference models in task 2.4.
- Whether Face mode should also offer "select tangent chain" by default on double click (assumed yes).
31 changes: 31 additions & 0 deletions openspec/changes/44-editor-face-tools/proposal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Proposal

## Why

Until now the editor works on whole objects. Direct modelling — "grab this face and push it", "round this edge", "draw on this face" — is what makes CAD fast for small adjustments of existing parts, including imported STLs that have no history. It is also the answer to the most common request that a mesh kernel cannot do directly: fillets and chamfers. `openspec/EDITOR.md` (section 2a) fixes the approach: a mesh has no B-rep faces, so faces and edges are *recognised* from the mesh (flat regions, smooth patches, feature-edge chains), and the operations are built from boolean tools that match what was recognised, never by editing triangles.

## What Changes

- **Selection modes** Object / Face / Edge, switchable on the tool bar and by `1`/`2`/`3` held with Ctrl (or the mode buttons). In Face mode a click selects a *face region*: a flat region (coplanar, tolerance 1°) or, when the surface is smooth, a smooth patch (triangles joined with dihedral below a threshold, default 30°); Shift adds regions, double click grows to tangent-connected regions. In Edge mode a click selects a *feature edge chain*: sharp edges (dihedral above the threshold) joined through vertices of degree two; chains classify as straight, circular (circle fit within tolerance) or free.
- **Push / Pull.** Drag or type a distance on a selected planar face: positive pulls the face out (adds a prism of the face outline), negative pushes it in (subtracts). Works for faces with holes, for several faces of the same normal, and on sketch-built and imported bodies alike. Non-planar faces are refused with the reason.
- **Fillet and Chamfer of edges.** Convex and concave straight edges between two planar faces, and circular edge loops (the top rim of a cylinder, a hole's edge), with a radius or distance; built as swept/revolved tool profiles combined by Boolean. Corners where several selected edges meet are filled with an acceptable blend (mitre-joined tools, not a rolling-ball); free-form and curved-surface edges are refused with the reason.
- **Sketch on face.** A planar face (or a flat region of an imported mesh) becomes a sketch plane with an origin at the picked point, the x direction along the longest straight edge or a world axis; **Project edges** brings the face outline, selected edges and circles (recognised from circular chains) into the sketch as geometry or construction. The sketch's plane stores a face reference that is re-resolved when the body changes; if it cannot be resolved the sketch keeps its last frame and shows a "detached" warning.
- **Stack operations.** Push/Pull, Fillet and Chamfer are operations of the stack of `41` with stored face/edge *references* (point, normal, kind) rather than triangle indices, re-resolved at evaluation time; a reference that does not resolve to exactly one element fails the operation with the reason.
- **Highlighting and feedback.** Hovered and selected faces/edges are highlighted, selection size is shown in the status bar (n faces, area, length), and the available operations follow the selection.

## Capabilities

### New Capabilities
- `editor-subelement-selection`: face and edge modes, recognition, highlighting, references.
- `editor-face-ops`: Push/Pull, sketch on face, project edges.
- `editor-edge-ops`: Fillet and Chamfer of straight and circular edges.

### Modified Capabilities

## Impact

- New `src/geometry/topology/{faces,edges,reference,classify}.ts` (React-free; `planarRegion` of `42` becomes its core), `geometry/features/ops/{pushPull,edgeBreak3d}.ts`, sketch plane kind `{face: Ref}` in `editor/sketch/plane.ts`, `features/editor/{FaceSelect,EdgeSelect,PushPullTool,EdgeBreakTool,ProjectEdges}`, viewport highlight layers and pointer modes, strings, tests.
- The 2D `edgeBreak` for extrusions of `40` is unchanged; this change adds the 3D variant for any body.
- Out of scope: variable-radius and rolling-ball fillets, fillets across curved faces and free-form edges, setback corners, draft and taper, move/rotate of faces, delete face/heal, face-to-face constraints, edge selection through loops on irregular meshes with noise (use Smooth/Decimate from `42` first), measurement of selected elements (the measure tool of `42` stays separate).
- Version 1.15.0 (minor: a new capability).
- Depends on: `41-editor-op-stack` and `42-editor-mesh-repair` (planar regions, picking, stack operations), via `43-editor-cut-split` in the linear order.
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Spec Delta

## Purpose
Defines Fillet and Chamfer of straight and circular edges of any body.

## ADDED Requirements

### Requirement: Chamfer
The Editor SHALL chamfer selected convex or concave edges between two planar faces and circular edges by a distance, with a live preview.

#### Scenario: Box edge
- **WHEN** one top edge of a 20 mm cube is chamfered by 2 mm
- **THEN** the cube loses a triangular prism of cross-section 2 mm² and its volume decreases by 2 × 20 = 40 mm³

#### Scenario: Cylinder rim
- **WHEN** the top rim of a 20 mm diameter cylinder is chamfered by 1 mm
- **THEN** the top face has diameter 18 mm and a 45° ring slopes down

#### Scenario: Concave edge
- **WHEN** an inner corner edge is chamfered
- **THEN** material is added in the corner

### Requirement: Fillet
The Editor SHALL fillet selected convex or concave edges with a radius, built as a smooth arc whose smoothness follows a chord tolerance.

#### Scenario: Box edge
- **WHEN** one top edge of a 20 mm cube is filleted with radius 3 mm
- **THEN** the volume decreases by (1 − π/4) × 9 × 20 ≈ 38.6 mm³ within the arc tolerance

#### Scenario: Hole rim
- **WHEN** the edge of a through hole is filleted
- **THEN** the hole mouth is rounded all around

#### Scenario: Several edges
- **WHEN** the four top edges of a cube are filleted together
- **THEN** the corners are blended and the result is a valid closed solid

### Requirement: Limits and messages
The operations SHALL refuse edges they cannot treat, with the reason: free-form or curved-surface edges, dihedral angles outside the supported range, and sizes larger than the adjacent faces allow, giving the maximum size.

#### Scenario: Too large
- **WHEN** the radius is larger than half the shorter adjacent face
- **THEN** the operation fails with the maximum allowed radius

#### Scenario: Free-form edge
- **WHEN** a selected chain is free-form
- **THEN** it is refused with "not a line or circle"

### Requirement: Editable operations
Fillet and Chamfer SHALL be stack operations that keep their edge references and size and can be edited, suppressed or reordered.

#### Scenario: Change the radius
- **WHEN** the user changes the radius of an existing fillet
- **THEN** the body updates without re-picking edges

#### Scenario: Suppress
- **WHEN** the operation is suppressed
- **THEN** the edges are sharp again
Loading
Loading