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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

- **Fit curves, then sample them.** Schneider's algorithm (the one used by Potrace-like and vector-editor tools): chord-length parametrisation, least-squares cubic with given end tangents, Newton–Raphson reparametrisation, split at the point of the largest error until the error is below the tolerance. Runs between corners; between runs the tangent is not shared (a real corner), inside a run the split point's tangent is shared (G1). A loop without corners is cut in two with central-difference tangents. Tolerance default **0.25 mm** and sampling step **1 mm**, the values the owner judged best in the PoC (0.15 mm and 0.5 mm kept a faint ripple on a screwdriver neck; 0.25 and 1 gave the smoothest walls); the previous `OUTLINE_TOLERANCE` of 0.15 mm applies only to the "original polyline" option.
- **Noise first, then fit.** The loop is resampled uniformly (≈ 0.17 mm), smoothed along the curve with corners held fixed (Gaussian σ default 0.25 mm: the one tuned for cutouts), then fitted; the fit tolerance absorbs what is left of the noise. The corner detector (turning angle over a ±3-vertex window, local maxima, default 50°) keeps pointed tips sharp.
- **Sampling.** Each cubic is sampled at about 1 mm along its length (uniform in `t`); the chord error is `step² / (8 R)`, below 0.06 mm for curvature radii above 2 mm, inside the 0.25 mm fit tolerance. Where the radius is smaller the sampling is refined (step ≤ `sqrt(8 R · 0.03)`). The sampled polygon is what goes to the geometry kernel (Manifold needs polygons) and to STL; the curve is an intermediate representation.
- **Sampling.** The step along a cubic follows from the chord error, not from a fixed length: the allowed error is `ε = 0.1 × samplingStep` mm (0.1 mm at the default 1 mm, inside the 0.25 mm fit tolerance), the step is `sqrt(8 R ε)` for the local radius `R` (measured per cubic from its turning), limited to 0.05 mm below and 10 mm above, uniform in `t` per cubic. So tight curves (tips, small radii) are sampled finely, gentle runs and straight stretches coarsely, and the sampling step control scales the error (smaller = finer everywhere). Measured on the owner's fixtures with a fixed 1 mm step the fit gave 1611 and 1965 vertices against 398 and 651 for the 0.15 mm polyline, which is why the step is not fixed. With the chord error the fit gives 476 and 831 vertices on them, about 3.4 times fewer than before. The 0.15 mm polyline of these 480 × 640 photos is already sparse (spacing 3 to 4 mm), and the fit cannot go much below it: a cubic needs at least 2 samples and the tolerance caps the chord error, so about a quarter more than that polyline stays. The 5 × reduction applies to the full-resolution trace (8902 vertices in the PoC), which the stripped fixtures cannot show. The extreme points of every cubic in x and y are always sampled, so the bounding box (keychain size) is exact. The sampled polygon is what goes to the geometry kernel (Manifold needs polygons) and to STL; the curve is an intermediate representation.
- **Offset on the curve.** The clearance is applied to the samples along the analytic normals; at a convex corner (left turn of a counter-clockwise loop) round-join points at 15° steps, at a concave corner a mitre on the bisector (scale limited). Where this would self-intersect (clearance larger than the local radius) the kernel's offset (`CrossSection.offset`) is the fallback, as today.
- **Same stage for every source.** The stage takes a label mask or a soft field, so classic, AI (with the bicubic soft mask and the optional second pass of `32`) and keychain masks all go through it; the baseline detection code is untouched.
- **Advanced group.** The user-facing controls are Outline smoothness and Fit tolerance; the **corner angle** (degrees, default 50) and the **sampling step** (`LengthField`, default 1 mm) are rarely needed and sit in a collapsed "Advanced" group under them, with a reset to the defaults. `OutlineControls` (introduced for Keychain in `34`) is the one component, extended here with the tolerance and the polyline option and reused by the photo dialog; a lower step or angle gives a finer outline, a higher one fewer vertices (the vertex count is shown). Values are stored with the cutout session or keychain params and migrated with defaults.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ In the PoC (`poc/ai/`) a pocket built from fitted curves instead of the raw poly
## What Changes

- **One shared outline stage for every source of silhouette.** After the silhouette is found (classic detection, AI mask, or a keychain mask), the outline is traced, smoothed along the curve (sharp corners kept) and **fitted with cubic Bézier curves** (Schneider's algorithm) to a tolerance (default 0.25 mm), corners detected by the turning angle (default 50°) staying real corners with G1-continuous curves in between.
- **Compact and smooth geometry.** The fitted curves are sampled into a polygon with a chord error well below the tolerance (a step of about 1 mm along the curve), so the model gets a few hundred vertices instead of thousands and walls without ripple. Clearance offsets are made on the curve (round joins at convex corners, mitre at concave ones).
- **Compact and smooth geometry.** The fitted curves are sampled into a polygon with a chord error below the tolerance, the step along each curve following from that error (at most the sampling step on tight curves, longer on gentle ones, so a gentle run gets few vertices), so the model gets a few hundred vertices instead of thousands and walls without ripple. Clearance offsets are made on the curve (round joins at convex corners, mitre at concave ones).
- **Applies to both engines.** The classic detection (the baseline) is not changed: only the stage after it, so the baseline silhouettes stay identical and its outline gets smoother. The AI engine of `32` uses the same stage.
- **Controls.** "Outline smoothness" (σ, default 0.25 mm) and "Fit tolerance" (default 0.25 mm) and "Sampling step" (default 1 mm) under the silhouette step, with the vertex count shown; "Use the original polyline" as an option that restores the previous behaviour.
- **Controls.** "Outline smoothness" (σ, default 0.25 mm) and "Fit tolerance" (default 0.25 mm) and "Sampling step" (default 1 mm: the finest step, it also scales the chord error) under the silhouette step, with the vertex count shown; "Use the original polyline" as an option that restores the previous behaviour.
- **Keychain.** The image and shape silhouettes of Keychain use the same stage for their outline (see `34`).

## Capabilities
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The outline made from a silhouette, whether found by the classic detection, by t

#### Scenario: Fewer points
- **WHEN** the outline of a tool is made with the default tolerance
- **THEN** its polygon has at least five times fewer vertices than the original polyline, and no point of it is farther than the tolerance from the original polyline
- **THEN** its polygon has fewer vertices than the original polyline (at least five times fewer for a polyline of thousands of vertices; a polyline that is already sparse, spaced 3 to 4 mm at the 0.15 mm tolerance, is matched within about a quarter), and no point of it is farther than the tolerance from the original polyline

#### Scenario: Sharp tips
- **WHEN** a tool has a pointed tip
Expand All @@ -39,6 +39,10 @@ Besides the smoothness and the fit tolerance, the user SHALL be able to set the
- **WHEN** the sampling step is made smaller
- **THEN** the polygon has more vertices and follows the curve more closely

#### Scenario: Gentle runs are sampled coarsely
- **WHEN** a curve is gentle or straight
- **THEN** its vertices are farther apart than the sampling step, so that the chord error stays within the allowed error, and a tight curve (radius of about a millimetre) has vertices at most the sampling step apart

#### Scenario: Corner angle
- **WHEN** the corner angle is raised above the turning angle of a tip
- **THEN** that tip is smoothed instead of kept sharp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
- [x] 1.3 Use in `createCutouts` (`tracedCutouts`) with `traceSilhouette` kept as it is: the traced loop goes through the fit, `OutlineSource.points` is the sampled polygon, an option keeps the original polyline. Tests: with the polyline option the existing outline tests are unchanged; with the fit the vertex count drops and the polygon stays within the tolerance of the original; classic silhouettes of both fixtures are identical to the frozen baseline (`32` task 2.1); the AI engine of `32` goes through the same path.
- [x] 1.4 Keychain outline (silhouette and shape plates) through the same stage as in `34`. Tests: the existing keychain regression volumes stay within their tolerances; the outline has fewer vertices and no ripple.

- [x] 1.5 `sampleCurves`: the step per cubic from the chord error (`ε = 0.1 × step`, `sqrt(8 R ε)`, limits 0.05 and 10 mm) instead of `min(step, fine)`; `offsetCurve` and the keychain outline use the same samples. Tests: a gentle arc and a long straight run get vertices farther apart than the step, a tight arc and a tip stay within the step, the chord error never exceeds `ε`, a smaller step gives more vertices, the extreme points of a cubic are sampled (exact bounding box), on both fixtures the fitted outline has at most 1.3 times the vertices of the 0.15 mm polyline and stays within the fit tolerance, the existing fit, offset and keychain regression tests stay green (update only the vertex-count expectations that assumed 1 mm).

## 2. UI

- [x] 2.1 Extend `OutlineControls` (introduced for Keychain in `34`) and use it under the silhouette step of the photo dialog: outline smoothness and fit tolerance (lengths, so `LengthField`), the vertex count, the option "original polyline", and a collapsed Advanced group with corner angle (degrees) and sampling step (`LengthField`) and a reset; strings in `en.json` and `ru.json`. No artboard exists: built from `ui/` components and `theme.css` tokens, said in the commit; compare in en and ru and at 390 px. Component tests: controls update the outline and the count, the Advanced group is collapsed by default and its reset restores 50° and 1 mm, a finer step raises the vertex count, the polyline option restores the previous result, steppers on every numeric input, key parity.
Expand All @@ -18,4 +20,5 @@
## 4. Verification

- [x] 4.1 `npm test` and `npm run build` are green, no console errors; the classic detection output on both fixtures is unchanged.
- [ ] 4.2 In the browser, en and ru and at 390 px, with the owner's two photos and both engines: pockets show smooth walls at a grazing view in the 3D preview, the vertex count is several times lower, tips stay pointed, the clearance gives rounded convex corners, the exported STL of the bin is one valid solid, saved old sessions load unchanged.
- [x] 4.2 In the browser, en and ru and at 390 px, with the owner's two photos and both engines: pockets show smooth walls at a grazing view in the 3D preview, the vertex count is several times lower, tips stay pointed, the clearance gives rounded convex corners, the exported STL of the bin is one valid solid, saved old sessions load unchanged.
Checked 2026-10-28 on the two fixtures (480 × 640 stripped copies of the owner's photos), classic engine, en/ru, 390 px: vertices 1611 → 484 (flash) and 1965 → ~830 (noflash) after task 1.5, against 398 / 651 for the 0.15 mm polyline; walls smooth at a grazing view; exported STL one component, no unmatched edges; saved session with three old cutouts loaded unchanged. Not checked: the AI engine (needs a model download) and full-resolution photos.
81 changes: 81 additions & 0 deletions openspec/specs/smooth-outline/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# smooth-outline Specification

## Purpose
Defines the shared stage that turns a detected silhouette into a smooth outline with few points, used by Cutout with either detection engine and by Keychain.

## Requirements

### Requirement: Smooth outline from any silhouette
The outline made from a silhouette, whether found by the classic detection, by the AI engine or from a keychain image or shape, SHALL be smooth: it SHALL be fitted with smooth curves instead of following every pixel and every wobble of the detected edge, and SHALL be turned into a polygon with a small number of vertices. Sharp corners of the subject, such as the tip of a tool, SHALL stay sharp, and the curves between corners SHALL be continuous in direction. The user SHALL be able to set the smoothness and the fit tolerance and to choose to keep the original polyline.

#### Scenario: Smooth walls
- **WHEN** a pocket is made from a detected tool and viewed along its wall
- **THEN** the wall shows no ripple that follows the pixels or the noise of the detected edge

#### Scenario: Fewer points
- **WHEN** the outline of a tool is made with the default tolerance
- **THEN** its polygon has fewer vertices than the original polyline (at least five times fewer for a polyline of thousands of vertices; a polyline that is already sparse, spaced 3 to 4 mm at the 0.15 mm tolerance, is matched within about a quarter), and no point of it is farther than the tolerance from the original polyline

#### Scenario: Sharp tips
- **WHEN** a tool has a pointed tip
- **THEN** the tip stays pointed and its position is within the tolerance of the original

#### Scenario: Both engines
- **WHEN** the same photo is processed by the classic and the AI engine
- **THEN** both outlines go through the same stage and both come out smooth

#### Scenario: Original polyline
- **WHEN** the user chooses to keep the original polyline
- **THEN** the outline is the same as before this feature

### Requirement: Advanced outline settings
Besides the smoothness and the fit tolerance, the user SHALL be able to set the angle from which a vertex counts as a corner and the sampling step of the polygon, in an Advanced group that is collapsed by default and can be reset to the defaults. The same controls SHALL be offered for Cutout and for Keychain.

#### Scenario: Collapsed
- **WHEN** the outline controls are first shown
- **THEN** smoothness and tolerance are visible and the corner angle and sampling step are in a collapsed Advanced group

#### Scenario: Finer step
- **WHEN** the sampling step is made smaller
- **THEN** the polygon has more vertices and follows the curve more closely

#### Scenario: Gentle runs are sampled coarsely
- **WHEN** a curve is gentle or straight
- **THEN** its vertices are farther apart than the sampling step, so that the chord error stays within the allowed error, and a tight curve (radius of about a millimetre) has vertices at most the sampling step apart

#### Scenario: Corner angle
- **WHEN** the corner angle is raised above the turning angle of a tip
- **THEN** that tip is smoothed instead of kept sharp

#### Scenario: Reset
- **WHEN** the user resets the Advanced group
- **THEN** the angle returns to 50 degrees and the step to 1 mm

### Requirement: Clearance on the smooth outline
The clearance of a cutout SHALL be applied to the smooth outline so that the pocket stays smooth: rounded at convex corners, mitred at concave ones, and never smaller than the outline plus the clearance.

#### Scenario: Convex corner
- **WHEN** the clearance is 0.8 mm and the outline has a convex tip
- **THEN** the pocket around the tip is rounded with a radius of the clearance

#### Scenario: Containment
- **WHEN** a pocket is made with a clearance
- **THEN** the tool's outline lies inside the pocket everywhere

### Requirement: Detection unchanged
Adding the smooth outline SHALL NOT change which silhouettes the classic detection finds, their sizes or their numbering; only the polygon made from each of them.

#### Scenario: Same silhouettes
- **WHEN** the reference photos are processed
- **THEN** the number, sizes and areas of the silhouettes are identical to those before this feature

### Requirement: Compatibility and language
Sessions saved before this feature SHALL load unchanged. All text of this feature SHALL be available in every language of the app.

#### Scenario: Old session
- **WHEN** a session with outline cutouts saved before this feature is loaded
- **THEN** the cutouts are as they were

#### Scenario: Russian
- **WHEN** the interface language is Russian
- **THEN** the smoothness, tolerance and polyline option are in Russian
9 changes: 9 additions & 0 deletions src/features/cutout/photo/createCutouts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,13 @@ describe('подгонка контура в tracedCutouts (35)', () => {
}
expect(max).toBeLessThan(0.3)
})

it('на обоих снимках подогнанный контур: вершин не больше 1,3 от полилинии', () => {
for (const name of ['flash', 'noflash'] as const) {
const f = loadFixture(name)
const seg = segment(rectify(f.gray, f.corners, A4Portrait, f.color.rgb)!)
const count = (o: typeof optsFit | typeof optsPolyline) => tracedCutouts(seg, [1, 2, 3], A4Portrait, o).reduce((a, c) => a + (c.source as { points: unknown[] }).points.length, 0)
expect(count(optsFit)).toBeLessThanOrEqual(count(optsPolyline) * 1.3)
}
})
})
13 changes: 12 additions & 1 deletion src/geometry/cutout.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { getWasm } from './wasm'
import {
addCutout, baseOutline, buildCutout, MIN_OUTLINE_AREA, outlineCutout, polygonArea, validOutline, buildCutoutTools, circleCutout, CUTOUT_COLORS, cutoutBounds, fillCutoutColors, nextCutoutColor, cutoutLayout, cutoutNotices, defaultCutout, duplicateCutout, effectiveDepth, moveCutout, rectCutout,
addCutout, pocketSolid, baseOutline, buildCutout, MIN_OUTLINE_AREA, outlineCutout, polygonArea, validOutline, buildCutoutTools, circleCutout, CUTOUT_COLORS, cutoutBounds, fillCutoutColors, nextCutoutColor, cutoutLayout, cutoutNotices, defaultCutout, duplicateCutout, effectiveDepth, moveCutout, rectCutout,
removeCutout, renameCutout, toggleCutout, updateCutout, validateCutout, MIN_MARGIN, type Cutout, type CutoutParams, type MeshRegistry, type MeshSource,
} from './cutout'
import { alignEdge, centerCutout, distribute, fitFootprint, fitFootprintUnits, snapAxis, snapMove, snapTargets } from './cutout-placement'
Expand Down Expand Up @@ -631,6 +631,17 @@ describe('вырез по контуру с фото (25)', () => {
expect(bw.maxX).toBeCloseTo((30 + 5) * Math.SQRT1_2, 6)
})

it('зазор по кривой даёт тот же карман, что и смещение ядра (в пределах 1 %)', async () => {
const w = await getWasm()
const circle: [number, number][] = Array.from({ length: 120 }, (_, i) => [15 * Math.cos((i / 120) * 2 * Math.PI), 15 * Math.sin((i / 120) * 2 * Math.PI)])
const c = outlineCutout({ id: 'c', depth: 10, clearance: 0.8, source: { kind: 'outline', points: circle, size: { w: 30, l: 30 } } })
const l = cutoutLayout(params({ cutouts: [c] }))
const m = pocketSolid(w, c, l, new Map())!
const ref = w.CrossSection.ofPolygons([circle]).offset(0.8, 'Round', 2, 24).area()
expect(m.volume() / (10 + 1)).toBeGreaterThan(ref * 0.99)
expect(m.volume() / (10 + 1)).toBeLessThan(ref * 1.01)
})

it('центровка, привязка к краю и распределение работают с контуром как с другими вырезами', () => {
const c = centerCutout(out({ x: 13, y: -7 }))
expect([c.x, c.y]).toEqual([0, 0])
Expand Down
Loading
Loading