editor interaction: workplanes placed with move/turn handles (make_workplane_offset_rworkplane) and chained on the active one; a hole placed with the pointer; pick-intent keys 1-6; sketches drawn only when they are what a click picks; no shape-specific shortcut features, same-name ops labelled with what they make; sketch splines as anchors with two handles (insert/remove/convert anchor SDK ops, pen tool); a sketch can be made into a wire
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -392,6 +392,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [constrain_symmetric_rsketch](constrain_symmetric_rsketch.md) *(from operators/sketch.py)* `top-level`
|
||||
- [constrain_tangent_rsketch](constrain_tangent_rsketch.md) *(from operators/sketch.py)* `top-level`
|
||||
- [constrain_vertical_rsketch](constrain_vertical_rsketch.md) *(from operators/sketch.py)* `top-level`
|
||||
- [convert_spline_to_anchors_rsketch](convert_spline_to_anchors_rsketch.md) *(from operators/sketch.py)* `top-level`
|
||||
- [convert_to_bspline_redge](convert_to_bspline_redge.md) *(from operators/geometry.py)* `top-level`
|
||||
- [convert_to_bspline_rface](convert_to_bspline_rface.md) *(from operators/geometry.py)* `top-level`
|
||||
- [diff_sketch_rsketchdiff](diff_sketch_rsketchdiff.md) *(from operators/sketch.py)* `top-level`
|
||||
@@ -410,6 +411,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [ground_component_rassembly](ground_component_rassembly.md) *(from operators/product.py)* `top-level`
|
||||
- [identity_placement_rplacement](identity_placement_rplacement.md) *(from operators/product.py)* `top-level`
|
||||
- [insert_curve_knot_redge](insert_curve_knot_redge.md) *(from operators/geometry.py)* `top-level`
|
||||
- [insert_spline_anchor_rsketch](insert_spline_anchor_rsketch.md) *(from operators/sketch.py)* `top-level`
|
||||
- [insert_surface_knot_rface](insert_surface_knot_rface.md) *(from operators/geometry.py)* `top-level`
|
||||
- [inspect_assembly_constraints_rconstraintreport](inspect_assembly_constraints_rconstraintreport.md) *(from operators/product.py)* `top-level`
|
||||
- [inspect_body_overlaps_rlist](inspect_body_overlaps_rlist.md) *(from operators/product.py)* `top-level`
|
||||
@@ -455,6 +457,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [ref.vertex](ref.vertex.md) *(from ref.py)* `submodule:ref`
|
||||
- [ref.vertices](ref.vertices.md) *(from ref.py)* `submodule:ref`
|
||||
- [register_property_resolver](register_property_resolver.md) *(from ql.py)* `submodule:ql`
|
||||
- [remove_spline_anchor_rsketch](remove_spline_anchor_rsketch.md) *(from operators/sketch.py)* `top-level`
|
||||
- [render_screenshot_rpath](render_screenshot_rpath.md) *(from operators/features.py)* `top-level`
|
||||
- [sample_curve_rcurvature](sample_curve_rcurvature.md) *(from operators/geometry.py)* `top-level`
|
||||
- [sample_surface_risocurves](sample_surface_risocurves.md) *(from operators/geometry.py)* `top-level`
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# convert_spline_to_anchors_rsketch
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def convert_spline_to_anchors_rsketch(sketch, spline)
|
||||
```
|
||||
|
||||
*Source: operators/sketch.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import convert_spline_to_anchors_rsketch`
|
||||
|
||||
## Description
|
||||
|
||||
Write a B-spline in anchor form (Bezier spans: anchors on the curve, a handle on each side).
|
||||
|
||||
A non-rational B-spline of degree 3 or less keeps its exact shape (degree elevation and knot insertion); a rational one
|
||||
or one of a higher degree is approximated within 1e-4 and the notes of metadata ``last_edit`` say how close. The end
|
||||
points keep their ids; an inner control point that does not move keeps its id, the others are new points ``p<n>``, and
|
||||
control points no entity uses any more are deleted with their constraints. A B-spline already in anchor form is left
|
||||
as it is (a note says so). Refused for a periodic B-spline. See ``insert_spline_anchor_rsketch`` for the form.
|
||||
@@ -0,0 +1,30 @@
|
||||
# insert_spline_anchor_rsketch
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def insert_spline_anchor_rsketch(sketch, spline, at)
|
||||
```
|
||||
|
||||
*Source: operators/sketch.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import insert_spline_anchor_rsketch`
|
||||
|
||||
## Description
|
||||
|
||||
Insert an anchor into a B-spline in anchor form, at the curve point nearest ``at``, without changing the curve.
|
||||
|
||||
The anchor form is a pen tool's curve: anchors on the curve, each with an in-handle and an out-handle. It is a cubic
|
||||
B-spline whose control points are ``[A0, out0, in1, A1, out1, in2, A2, ...]`` (every one a sketch point) and whose
|
||||
inner knots have multiplicity 3, so every span is a cubic Bezier from one anchor to the next; the editor's spline tool
|
||||
draws them, ``convert_spline_to_anchors_rsketch`` turns another B-spline into one. Moving an anchor or a handle is
|
||||
moving its point (the solver moves every control point of such a spline).
|
||||
|
||||
The span under ``at`` is split at that place (de Casteljau), so the curve is the same: the span's two handles get
|
||||
shorter (they keep their ids; a dimension or fix on them no longer holds and is dropped, see the notes) and the new
|
||||
anchor and its two handles are new points ``p<n>`` (the lowest free numbers). The new knot is the curve parameter of
|
||||
the place, with multiplicity 3. ``at`` is a point (x, y) in sketch coordinates or a point id. The sketch is solved
|
||||
first. Refused for a B-spline that is not in anchor form and at an existing anchor. Metadata ``last_edit`` notes name
|
||||
the new anchor and its handles; ``diff_sketch_rsketchdiff(before, after)`` lists them too.
|
||||
@@ -0,0 +1,24 @@
|
||||
# remove_spline_anchor_rsketch
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def remove_spline_anchor_rsketch(sketch, spline, anchor)
|
||||
```
|
||||
|
||||
*Source: operators/sketch.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import remove_spline_anchor_rsketch`
|
||||
|
||||
## Description
|
||||
|
||||
Remove an inner anchor (and its two handles) from a B-spline in anchor form.
|
||||
|
||||
``anchor`` is the point id of an anchor that is not an end. The spans on either side become one span: its handles are
|
||||
the outer handles of the two spans, which keep their ids and directions and get the lengths that fit the old curve best
|
||||
(least squares, never reversed), so removing an anchor that ``insert_spline_anchor_rsketch`` made gives back the curve
|
||||
it split. A handle that a constraint or another entity holds keeps its place. The removed points are deleted unless
|
||||
another entity uses them, and the constraints on deleted points are dropped (the notes of metadata ``last_edit`` name
|
||||
them). Refused for an end anchor, a handle, a point that is not on the spline, and a B-spline not in anchor form.
|
||||
@@ -913,6 +913,7 @@ fields when their target expression is unitless.
|
||||
`load_brep_region_rshell`、`load_brep_region_rsolid`、
|
||||
`make_solid_from_shell_rsolid`、`trim_rsketch`、`extend_rsketch`、
|
||||
`fillet_corner_rsketch`、`chamfer_corner_rsketch`、`project_rsketch`、
|
||||
`insert_spline_anchor_rsketch`、`remove_spline_anchor_rsketch`、`convert_spline_to_anchors_rsketch`、
|
||||
`explode_rassembly` 或曲线/曲面编辑操作(`convert_to_bspline_*`、`set_*_poles_*`、
|
||||
`move_*_poles_*`、`set_*_weights_*`、`insert_*_knot_*`、`elevate_*_degree_*`、`rebuild_*`)。
|
||||
- 为兼容早期 `2.0` model payload,importer 将缺失的
|
||||
@@ -1020,6 +1021,9 @@ New canonical profile nodes use the `make_*_r*` names listed in `canonical_contr
|
||||
- `fillet_corner_rsketch`
|
||||
- `chamfer_corner_rsketch`
|
||||
- `project_rsketch`
|
||||
- `insert_spline_anchor_rsketch`
|
||||
- `remove_spline_anchor_rsketch`
|
||||
- `convert_spline_to_anchors_rsketch`
|
||||
- `make_constrain_coincident_rsketch`
|
||||
- `make_constrain_point_on_rsketch`
|
||||
- `make_constrain_horizontal_rsketch`
|
||||
@@ -1358,6 +1362,13 @@ Notes:
|
||||
- Params: `sketch_id`, `source_kind`, `source` (source sketch id, or the number of shapes), `entities` (source entity ids or `null`; sketch sources only), `construction`
|
||||
- Projected ids are `proj_<source sketch id>_<n>` (`proj_shape_<n>` for shapes); the target sketch's `projections` metadata lists `{source, entity, projected}`.
|
||||
|
||||
#### `insert_spline_anchor_rsketch` / `remove_spline_anchor_rsketch` / `convert_spline_to_anchors_rsketch`
|
||||
|
||||
- Inputs: 1 `Sketch`
|
||||
- Outputs: 1 updated `Sketch`
|
||||
- Params: `sketch_id`, `spline` (B-spline id); insert: `at` (`[x, y]` or a point id); remove: `anchor` (point id)
|
||||
- The edit is made on the solved geometry and picks its own ids (`p<n>`), so replay is deterministic.
|
||||
|
||||
#### `explode_rassembly`
|
||||
|
||||
- Inputs: 1 `Assembly`
|
||||
|
||||
@@ -55,9 +55,25 @@ HOLE_DIAMETER = scad.var(name="hole_diameter", default=6.0, unit="mm", comment="
|
||||
("name a face": pick the faces, type the tag). A colour slot is the `color` kind of the catalog
|
||||
(`simplecadapi.types.Color`); the picker's `#rrggbb` is written as linear RGB. A person's face name is a tag: read it
|
||||
with `scad.ql.tag(...)`, never invent another naming scheme.
|
||||
- Workplanes: with a selection, Space (or the command "Workplane from selection") writes a `workplane` feature
|
||||
- Placing a workplane by hand: Space with nothing selected (or one flat face; the command "Workplane") shows a draft plane
|
||||
with move arrows and turn rings on its base (the picked face, else the active workplane, else XY; the panel lists XY,
|
||||
XZ, YZ and every workplane). Drag (1 mm / 5 degree steps, Shift for free) or type the six numbers; G move, R turn,
|
||||
Enter creates, Esc cancels. The cell is `wp = scad.make_workplane_offset_rworkplane(<base>, offset=(...), rx=..., ry=...,
|
||||
rz=...)` (on a face: `make_workplane_from_face_rworkplane(face, x_dir=...)` as the base), the numbers in its params cell.
|
||||
Each new plane becomes the active one and the next Space starts on it: a chain of planes in space, each sketched on and
|
||||
promoted to a wire (below) to loft or sweep between. Shift+Space looks straight at the active workplane.
|
||||
- A hole is placed with the pointer: while its form is open a ghost of the hole (its diameter and depth) follows the model
|
||||
under the pointer, along the surface's normal there by default ("along the picked face's normal"), and a click writes
|
||||
the start point and direction into the form. Nothing is computed by the kernel until Add.
|
||||
- Pick intents have keys: 1 vertex, 2 edge, 3 face, 4 solid, 5 component, 6 sketch. Sketches are drawn only while sketches
|
||||
are what a click picks (or one is picked, edited, or a form takes a sketch profile).
|
||||
- There are no shape-specific shortcuts ("extrude a rectangle", "loft two circles"): a profile is a sketch, and loft, sweep
|
||||
and the rest are the SDK operations themselves (`op.loft_rsolid`, `op.sweep_rsolid` ...). Operations that differ only in
|
||||
what they make are labelled with it ("Loft → solid", "Loft → surface"). Older cells written by those shortcuts still run;
|
||||
the editor shows them as code features.
|
||||
- Workplanes from picks: with any other selection, Space (or the command "Workplane from selection") writes a `workplane` feature
|
||||
(`# ---- feature: wp (datum) ----`, `wp = scad.make_workplane_*_rworkplane(...)` with the picks resolved inline, offset
|
||||
and flip in the params cell). One flat face -> on it; a face and an edge -> x along the edge; two parallel faces ->
|
||||
and flip in the params cell). (The command alone on one flat face -> on it.) A face and an edge -> x along the edge; two parallel faces ->
|
||||
the midplane; three vertices (in pick order) -> through them; one edge -> through it, turned by an angle. The new
|
||||
workplane becomes the active one (the camera turns to it, it is drawn blue); a new sketch goes on it, and the plane
|
||||
chooser lists every workplane variable. Each workplane variable of the notebook (GUI or code) is drawn as a small
|
||||
@@ -85,6 +101,7 @@ sca feature rm base | sca feature undo | sca feature redo
|
||||
sca sketch ls | get CELL | put CELL -f doc.json | solve CELL
|
||||
sca sketch op CELL trim --args '{"entity": "h", "at": [8, 0]}' [--dry-run]
|
||||
sca sketch op CELL extend --args '{"entity": "h", "end": "end"}'
|
||||
sca sketch op CELL insert_spline_anchor --args '{"spline": "s1", "at": [12, 8]}' # also remove_spline_anchor, convert_spline_to_anchors
|
||||
```
|
||||
|
||||
- The edits are the SDK's own operations, not editor features: `sca sketch op CELL trim ...` calls `scad.trim_rsketch` on the
|
||||
@@ -103,5 +120,16 @@ sca sketch op CELL extend --args '{"entity": "h", "end": "end"}'
|
||||
crossings trim would cut at (`crossings`, B-splines included). trim cuts B-splines (and lines/arcs/circles at B-splines),
|
||||
extend lengthens a B-spline or a line onto one; a trimmed or extended B-spline has non-uniform knots, so its document entity
|
||||
also carries `"knots"` (distinct, increasing) and `"multiplicities"` (they add up to control points + degree + 1).
|
||||
- The spline tool (B) is a pen: a click places an anchor, press-and-drag pulls out its two handles; the curve is a B-spline in
|
||||
anchor form (`"knots": [0, 1, ..], "multiplicities": [4, 3, .., 4]`, control points `[A0, out0, in1, A1, ..]`; see
|
||||
`sketch-and-features.md`, "B-splines with anchors"). Picking the spline shows its handles: dragging an anchor carries its
|
||||
handles, dragging a handle keeps a smooth anchor smooth (Alt while dragging: a corner; S smooths again), a double-click on
|
||||
the curve inserts an anchor and Delete removes the picked anchor (the SDK edits above). A B-spline with control points
|
||||
(older documents) shows its control polygon and a "convert to anchors" button (K).
|
||||
- A sketch document may say `"output": "wire"`: the cell then ends in
|
||||
`name = scad.make_wire_from_sketch_rwire(sketch=_sketch, profile=<i>, ...)` (a closed loop or an open chain from
|
||||
`inspect_sketch_rsketchprofiles`, whose `closed` says which) and the notebook lists it as a wire, so `op.sweep_rsolid`
|
||||
(path) and `op.loft_rsolid` (sections) take it; face sketches stay the profiles extrude/revolve/cut take. The editor's
|
||||
sketch bar has the face / wire switch and the profile list.
|
||||
- Errors name ids (`there is no entity 'x'`, `nothing is ahead of the end of h`); fix the call, do not retry it unchanged.
|
||||
- Everything a command writes is an ordinary cell; `sca cell` still works on it (see the `# gui:` rules above).
|
||||
|
||||
@@ -68,7 +68,9 @@ Read the exact page under `references/docs/api/` for every API used:
|
||||
solve keeps the branch nearest the initial geometry).
|
||||
- Editing: `trim_rsketch`, `extend_rsketch` (see "Trim and extend" below),
|
||||
`fillet_corner_rsketch`, `chamfer_corner_rsketch` (see "Fillet and chamfer a
|
||||
corner"), `project_rsketch` (see "Relating sketches: project").
|
||||
corner"), `project_rsketch` (see "Relating sketches: project"),
|
||||
`insert_spline_anchor_rsketch`, `remove_spline_anchor_rsketch`,
|
||||
`convert_spline_to_anchors_rsketch` (see "B-splines with anchors").
|
||||
- Promotion: `make_wire_from_sketch_rwire`, `make_face_from_sketch_rface`.
|
||||
- Diagnostics: `inspect_sketch_rsketchresult` (non-recording),
|
||||
`diff_sketch_rsketchdiff` (non-recording report of what an edit changed).
|
||||
@@ -136,6 +138,32 @@ print(scad.diff_sketch_rsketchdiff(before, sketch))
|
||||
`Sketch.to_dict()` yourself; the last edit's notes are in
|
||||
`sketch.get_metadata("last_edit")`.
|
||||
|
||||
## B-splines with anchors
|
||||
|
||||
A cubic B-spline whose inner knots have multiplicity 3 is a chain of Bezier spans:
|
||||
control points `[A0, out0, in1, A1, out1, in2, A2, ...]`, the anchors `A<i>` on the
|
||||
curve, each with an in-handle and an out-handle (a pen tool's curve; the editor's
|
||||
spline tool draws this form, knots `0..n`, multiplicities `[4, 3, ..., 3, 4]`). Every
|
||||
control point is a sketch point and the solver moves all of them, so moving an anchor
|
||||
or a handle is moving a point; the two handles of an anchor are independent (their
|
||||
lengths are the pull on each side; in one line the anchor is smooth). Trim and extend
|
||||
keep the form.
|
||||
|
||||
```python
|
||||
sketch = scad.insert_spline_anchor_rsketch(sketch, "s1", (12.0, 8.0)) # curve unchanged: new p<n> anchor + 2 handles
|
||||
sketch = scad.remove_spline_anchor_rsketch(sketch, "s1", "p2") # merge the spans beside an inner anchor
|
||||
sketch = scad.convert_spline_to_anchors_rsketch(sketch, "s7") # a control-point B-spline -> anchor form
|
||||
```
|
||||
|
||||
- Insert splits the span at the curve point nearest `at` (de Casteljau): the curve
|
||||
stays, the span's two handles get shorter (same ids; a dimension or fix on them is
|
||||
dropped, see `last_edit` notes) and the new anchor and its handles are new points.
|
||||
- Remove keeps the outer handles' ids and directions and fits their lengths to the
|
||||
old curve (remove after insert gives the curve back); a handle a constraint holds
|
||||
stays put. End anchors and handles are refused by name.
|
||||
- Convert is exact for degree <= 3 without weights, else approximated within 1e-4
|
||||
(the notes say how close); periodic splines are refused.
|
||||
|
||||
## Fillet and chamfer a corner
|
||||
|
||||
`fillet_corner_rsketch(sketch, a, b, radius)` rounds the corner where two lines
|
||||
|
||||
+183
-15
@@ -16,6 +16,8 @@ import { AssemblyPanel } from "@/components/AssemblyPanel";
|
||||
import { ConnectorGizmos, type Gizmo } from "@/components/ConnectorGizmos";
|
||||
import { WorkplanePatches } from "@/components/WorkplanePatches";
|
||||
import { TagSplits, parseTagSplits, type TagSplit } from "@/components/TagSplits";
|
||||
import { WorkplanePlacePanel, WorkplanePlacer, type PlaceBase, type PlaceMode } from "@/components/WorkplanePlacer";
|
||||
import { NAMED_FRAMES, ZERO_PLACE, cleanValues, faceFrame, type PlaceFrame, type PlaceValues } from "@/lib/workplane-place";
|
||||
import { parseWorkplanes, resolvePlane, workplanePlane, workplaneRequest, type WorkplaneFrame } from "@/lib/workplanes";
|
||||
import { fitDistanceMm } from "@/lib/sketch-view";
|
||||
import { viewPose } from "@/lib/sketch-plane";
|
||||
@@ -49,13 +51,14 @@ import { Boxes, Cable } from "lucide-react";
|
||||
import { Viewport, type PickResult, type SelectionMode } from "@/scene/Viewport";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
const MODES: { mode: SelectionMode; label: string }[] = [
|
||||
{ mode: "component", label: "comp" },
|
||||
{ mode: "solid", label: "solid" },
|
||||
{ mode: "face", label: "face" },
|
||||
{ mode: "edge", label: "edge" },
|
||||
{ mode: "vertex", label: "vert" },
|
||||
{ mode: "sketch", label: "sketch" },
|
||||
/** The pick intents and their keys: 1 vertex, 2 edge, 3 face, 4 solid (Plasticity's order), 5 component, 6 sketch. */
|
||||
const MODES: { mode: SelectionMode; label: string; key: string }[] = [
|
||||
{ mode: "component", label: "comp", key: "5" },
|
||||
{ mode: "solid", label: "solid", key: "4" },
|
||||
{ mode: "face", label: "face", key: "3" },
|
||||
{ mode: "edge", label: "edge", key: "2" },
|
||||
{ mode: "vertex", label: "vert", key: "1" },
|
||||
{ mode: "sketch", label: "sketch", key: "6" },
|
||||
];
|
||||
|
||||
/** Editor application: left = notebook (cells, workspace), middle = the live
|
||||
@@ -103,6 +106,10 @@ export function App() {
|
||||
// The notebook's workplanes as the kernel reported them, and the one Space made (or chose) last: new sketches go on it.
|
||||
const [workplanes, setWorkplanes] = useState<WorkplaneFrame[]>([]);
|
||||
const [tagSplits, setTagSplits] = useState<TagSplit[]>([]);
|
||||
// A workplane being placed by hand (Space): its base, the numbers the handles write, move or turn, its name.
|
||||
const [placing, setPlacing] = useState<{ base: string; values: PlaceValues; mode: PlaceMode; name: string; face: { item: SelectionItem; frame: PlaceFrame } | null; error: string | null } | null>(null);
|
||||
const placingRef = useRef(placing);
|
||||
placingRef.current = placing;
|
||||
const [activeWorkplane, setActiveWorkplane] = useState<string | null>(null);
|
||||
const [selectionMode, setSelectionMode] = useState<SelectionMode>("solid");
|
||||
const [sceneVersion, setSceneVersion] = useState(0);
|
||||
@@ -116,6 +123,8 @@ export function App() {
|
||||
const gui = useFeatures();
|
||||
const refreshFeatures = gui.refresh;
|
||||
const [dialog, setDialog] = useState<DialogRequest | null>(null);
|
||||
const dialogRef = useRef(dialog);
|
||||
dialogRef.current = dialog;
|
||||
const [guiBusy, setGuiBusy] = useState(false);
|
||||
const [guiError, setGuiError] = useState<string | null>(null);
|
||||
const modeBeforeDialog = useRef<SelectionMode | null>(null);
|
||||
@@ -157,6 +166,14 @@ export function App() {
|
||||
[currentPath],
|
||||
);
|
||||
const [pickedSketches, setPickedSketches] = useState<string[]>([]);
|
||||
// Sketches are drawn while they are what a click picks, while one is picked or edited, and while a form takes a
|
||||
// sketch profile; otherwise they would only clutter the model.
|
||||
const dialogTakesProfile = !!dialog?.spec.slots.some((slot) => slot.kind === "profile");
|
||||
const sketchesShown = selectionMode === "sketch" || pickedSketches.length > 0 || sketchSession !== null || dialogTakesProfile;
|
||||
const shownSketches = useMemo(
|
||||
() => (sketchesShown ? hiddenSketches : new Set(sketchList.map((info) => info.name))),
|
||||
[sketchesShown, hiddenSketches, sketchList],
|
||||
);
|
||||
const [hoverSketch, setHoverSketch] = useState<string | null>(null);
|
||||
const [pushArrow, setPushArrow] = useState<{ sketch: string; direction: Vec3; distance: number } | null>(null);
|
||||
const [barNote, setBarNote] = useState<string | null>(null);
|
||||
@@ -448,6 +465,8 @@ export function App() {
|
||||
leftTabRef.current = leftTab;
|
||||
const selectComponent = asm.setSelected;
|
||||
const handlePick = useCallback((result: PickResult) => {
|
||||
if (placingRef.current) return; // a click on the handles is not a pick
|
||||
if (dialogRef.current?.spec.id === "hole") return; // a click places the hole (HolePlacer), it picks nothing
|
||||
if (choosingRef.current) {
|
||||
void pickSketchFace(result);
|
||||
return;
|
||||
@@ -712,6 +731,93 @@ export function App() {
|
||||
}
|
||||
}, [gui.run, log.push]);
|
||||
|
||||
// -- placing a workplane by hand ----------------------------------------------------------------------------------
|
||||
|
||||
/** The bases a workplane can be placed on: the datum planes, every workplane of the notebook, and the picked face. */
|
||||
const placeBases = useMemo<PlaceBase[]>(() => {
|
||||
const out: PlaceBase[] = (["XY", "XZ", "YZ"] as const).map((name) => ({ value: name, label: name, frame: NAMED_FRAMES[name] }));
|
||||
for (const wp of workplanes) out.push({ value: wp.name, label: wp.name, frame: { origin: wp.origin, x_axis: wp.x_axis, y_axis: wp.y_axis, normal: wp.normal } });
|
||||
if (placing?.face) out.push({ value: "face", label: "picked face", frame: placing.face.frame });
|
||||
return out;
|
||||
}, [workplanes, placing?.face]);
|
||||
const placeBase = placeBases.find((item) => item.value === placing?.base) ?? placeBases[0];
|
||||
|
||||
/** Start placing: on the picked flat face, else on the active workplane (one after another builds a 3D frame of
|
||||
* planes), else on XY. */
|
||||
const startPlacing = useCallback(() => {
|
||||
const items = selectionRef.current;
|
||||
const face = items.length === 1 && items[0].kind === "face" ? items[0] : null;
|
||||
const frame = face ? faceFrame(face.properties) : null;
|
||||
if (face && !frame) {
|
||||
setBarNote("That face is not flat: a workplane lies on a plane. Pick a flat face, or nothing to place one on the active workplane.");
|
||||
return;
|
||||
}
|
||||
const taken = gui.state?.taken ?? [];
|
||||
let name = "wp";
|
||||
for (let n = 2; taken.includes(name); n++) name = `wp_${n}`;
|
||||
const base = face ? "face" : activeWorkplaneRef.current && workplanesRef.current.some((wp) => wp.name === activeWorkplaneRef.current) ? activeWorkplaneRef.current : "XY";
|
||||
setBarNote(null);
|
||||
setPlacing({ base, values: ZERO_PLACE, mode: "translate", name, face: face && frame ? { item: face, frame } : null, error: null });
|
||||
}, [gui.state?.taken]);
|
||||
|
||||
const createPlaced = useCallback(async () => {
|
||||
const current = placingRef.current;
|
||||
if (!current) return;
|
||||
setGuiBusy(true);
|
||||
try {
|
||||
const values = cleanValues(current.values);
|
||||
const command: FeatureCommand = {
|
||||
op: "add",
|
||||
spec: "workplane",
|
||||
name: current.name,
|
||||
values: {
|
||||
method: "offset",
|
||||
base: current.base,
|
||||
move: values.move,
|
||||
rx: values.rx,
|
||||
ry: values.ry,
|
||||
rz: values.rz,
|
||||
...(current.base === "face" && current.face ? { x_dir: current.face.frame.x_axis } : {}),
|
||||
},
|
||||
...(current.base === "face" && current.face ? { selections: { face: [pickedPayload(current.face.item)] } } : {}),
|
||||
};
|
||||
const result = await gui.run(command);
|
||||
assertCellRan(result);
|
||||
log.push("ok", `add ${result.name}`);
|
||||
setPlacing(null);
|
||||
setPicked([]);
|
||||
turnedTo.current = `stay:${result.name}`; // the camera stays where the person placed it from
|
||||
setActiveWorkplane(result.name);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setPlacing((p) => (p ? { ...p, error: message } : p));
|
||||
} finally {
|
||||
setGuiBusy(false);
|
||||
}
|
||||
}, [gui.run, log.push]);
|
||||
|
||||
// While placing: G move, R turn, Enter create, Esc cancel (not while typing in a field, except the fields' own Enter).
|
||||
useEffect(() => {
|
||||
if (!placing) return;
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
const typing = !!target?.closest("input, textarea, select, [contenteditable=true], .cm-editor");
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
setPlacing(null);
|
||||
} else if (event.key === "Enter" && !typing) {
|
||||
event.preventDefault();
|
||||
void createPlaced();
|
||||
} else if (!typing && (event.key === "g" || event.key === "r")) {
|
||||
event.preventDefault();
|
||||
setPlacing((p) => (p ? { ...p, mode: event.key === "g" ? "translate" : "rotate" } : p));
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [placing !== null, createPlaced]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// The camera turns to the active workplane (straight at it, the model in view) when its frame arrives or changes.
|
||||
const turnedTo = useRef<string | null>(null);
|
||||
const turnToWorkplane = useCallback((wp: WorkplaneFrame) => {
|
||||
@@ -732,31 +838,54 @@ export function App() {
|
||||
if (!wp || sketchingRef.current) return;
|
||||
const key = JSON.stringify(wp);
|
||||
if (turnedTo.current === key) return;
|
||||
const stay = turnedTo.current === `stay:${wp.name}`; // placed by hand, in this view: keep the view
|
||||
turnedTo.current = key;
|
||||
turnToWorkplane(wp);
|
||||
if (!stay) turnToWorkplane(wp);
|
||||
}, [workplanes, activeWorkplane, turnToWorkplane]);
|
||||
useEffect(() => {
|
||||
// a workplane that is gone (its cell deleted, another notebook) is no longer active
|
||||
if (activeWorkplane && workplanes.length && !workplanes.some((wp) => wp.name === activeWorkplane)) setActiveWorkplane(null);
|
||||
}, [workplanes, activeWorkplane]);
|
||||
|
||||
// 1..6 switch what a click picks (see MODES), unless a text field has the focus or a sketch is being drawn (its keys
|
||||
// are its tools and typed numbers).
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.repeat || event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (sketchingRef.current) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest("input, textarea, select, [contenteditable=true], .cm-editor, [role=dialog]")) return;
|
||||
const found = MODES.find((item) => item.key === event.key);
|
||||
if (!found) return;
|
||||
event.preventDefault();
|
||||
setSelectionMode(found.mode);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
|
||||
// Space: a workplane from the selection; with nothing selected, look at the active workplane again.
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key !== " " || event.repeat || event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (sketchingRef.current) return; // space pans the sketch view
|
||||
if (sketchingRef.current || placingRef.current) return; // space pans the sketch view
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest("input, textarea, select, button, [contenteditable=true], .cm-editor, [role=dialog]")) return;
|
||||
event.preventDefault();
|
||||
if (selectionRef.current.length) void workplaneFromSelection();
|
||||
else {
|
||||
if (event.shiftKey) {
|
||||
// Shift+Space: look straight at the active workplane again
|
||||
const wp = workplanesRef.current.find((item) => item.name === activeWorkplaneRef.current);
|
||||
if (wp) turnToWorkplane(wp);
|
||||
return;
|
||||
}
|
||||
const items = selectionRef.current;
|
||||
// one flat face, or nothing: place a workplane with the handles; the other picks name their constructor
|
||||
if (items.length === 0 || (items.length === 1 && items[0].kind === "face")) startPlacing();
|
||||
else void workplaneFromSelection();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [workplaneFromSelection, turnToWorkplane]);
|
||||
}, [workplaneFromSelection, turnToWorkplane, startPlacing]);
|
||||
|
||||
const handleEditFeatureRef = useRef<(feature: FeatureRow, spec: Spec) => void>(() => undefined);
|
||||
const editSelectedSketch = useCallback(() => {
|
||||
@@ -777,6 +906,15 @@ export function App() {
|
||||
() => [
|
||||
// The assembly layout is not a dialog: it is its own panel (registered below), so its spec is left out of the generic list.
|
||||
...commandsFromSpecs((gui.catalog?.specs ?? []).filter((spec) => spec.id !== "assembly" && spec.id !== "workplane"), openSpec, FEATURE_ICONS),
|
||||
{
|
||||
id: "workplane_place",
|
||||
label: "Workplane",
|
||||
group: "Datums",
|
||||
keywords: ["workplane", "datum", "plane", "offset", "rotate", "move", "space"],
|
||||
description: "Place a workplane with handles (Space): on the picked flat face, else on the active workplane, else on XY; move and turn it, then sketch on it.",
|
||||
icon: FEATURE_ICONS.workplane_from_selection,
|
||||
run: () => startPlacing(),
|
||||
},
|
||||
{
|
||||
id: "workplane_from_selection",
|
||||
label: "Workplane from selection",
|
||||
@@ -1046,7 +1184,7 @@ export function App() {
|
||||
<ResizablePanel defaultSize={55} minSize={30} className="min-w-0 overflow-hidden">
|
||||
<div className="flex h-full flex-col">
|
||||
<div inert={sketching} className={cn("flex h-9 shrink-0 items-center gap-1 border-b-2 border-border px-2", sketching && "opacity-40")}>
|
||||
{MODES.map(({ mode, label }) => (
|
||||
{MODES.map(({ mode, label, key }) => (
|
||||
<button
|
||||
key={mode}
|
||||
type="button"
|
||||
@@ -1057,8 +1195,10 @@ export function App() {
|
||||
: "border-transparent text-muted-foreground hover:border-input hover:text-foreground",
|
||||
)}
|
||||
onClick={() => setSelectionMode(mode)}
|
||||
title={`${label} (${key})`}
|
||||
>
|
||||
{label}
|
||||
<span className="ml-1 opacity-50">{key}</span>
|
||||
</button>
|
||||
))}
|
||||
<span className="flex-1" />
|
||||
@@ -1086,7 +1226,7 @@ export function App() {
|
||||
viewRef={viewRef}
|
||||
infos={sketchList}
|
||||
shapes={sketchShapes}
|
||||
hidden={hiddenSketches}
|
||||
hidden={shownSketches}
|
||||
editing={sketchSession?.mode === "edit" ? sketchSession.name : null}
|
||||
selected={pickedSketches}
|
||||
hover={hoverSketch}
|
||||
@@ -1096,7 +1236,34 @@ export function App() {
|
||||
onHover={setHoverSketch}
|
||||
/>
|
||||
{viewRef.current && workplanes.length > 0 && <WorkplanePatches view={viewRef.current} workplanes={workplanes} active={activeWorkplane} />}
|
||||
{!sketching && viewRef.current && <TagSplits view={viewRef.current} splits={tagSplits} sceneVersion={sceneVersion} />}
|
||||
{!sketching && !placing && viewRef.current && <TagSplits view={viewRef.current} splits={tagSplits} sceneVersion={sceneVersion} />}
|
||||
{placing && viewRef.current && placeBase && (
|
||||
<>
|
||||
<WorkplanePlacer
|
||||
view={viewRef.current}
|
||||
base={placeBase.frame}
|
||||
values={placing.values}
|
||||
mode={placing.mode}
|
||||
half={20}
|
||||
onChange={(values) => setPlacing((p) => (p ? { ...p, values } : p))}
|
||||
/>
|
||||
<WorkplanePlacePanel
|
||||
bases={placeBases}
|
||||
base={placeBase.value}
|
||||
values={placing.values}
|
||||
mode={placing.mode}
|
||||
name={placing.name}
|
||||
busy={guiBusy}
|
||||
error={placing.error}
|
||||
onBase={(base) => setPlacing((p) => (p ? { ...p, base } : p))}
|
||||
onMode={(mode) => setPlacing((p) => (p ? { ...p, mode } : p))}
|
||||
onValues={(values) => setPlacing((p) => (p ? { ...p, values } : p))}
|
||||
onName={(name) => setPlacing((p) => (p ? { ...p, name } : p))}
|
||||
onCreate={() => void createPlaced()}
|
||||
onCancel={() => setPlacing(null)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{!sketching && viewRef.current && gizmos.length > 0 && (
|
||||
<ConnectorGizmos view={viewRef.current} gizmos={gizmos} components={asm.doc.components} highlighted={gizmoHighlight} onPick={pickGizmo} armed={!!asm.target} />
|
||||
)}
|
||||
@@ -1142,6 +1309,7 @@ export function App() {
|
||||
onSelectionMode={setSelectionMode}
|
||||
onSubmit={submitFeature}
|
||||
onClose={closeDialog}
|
||||
view={viewRef.current}
|
||||
/>
|
||||
<LoadingMask active={loading !== null} message={loading ?? ""} theme={theme.resolved} />
|
||||
</div>
|
||||
|
||||
@@ -44,6 +44,8 @@ import {
|
||||
} from "@/lib/features";
|
||||
import type { SelectionItem } from "@/lib/selection";
|
||||
import type { SelectionMode } from "@/scene/Viewport";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
import { HolePlacer, type HoleDraft } from "@/components/HolePlacer";
|
||||
|
||||
/** The icon of each way a new solid meets the body (colour stays reserved for meaning, so the icons carry no ink). */
|
||||
const OPERATION_ICONS: Record<string, LucideIcon> = { join: SquarePlus, cut: Scissors, intersect: Combine, new: Box };
|
||||
@@ -71,6 +73,7 @@ export function FeatureDialog({
|
||||
onSelectionMode,
|
||||
onSubmit,
|
||||
onClose,
|
||||
view,
|
||||
}: {
|
||||
request: DialogRequest | null;
|
||||
state: FeatureState;
|
||||
@@ -80,6 +83,8 @@ export function FeatureDialog({
|
||||
/** Runs the command; rejects with the server's message, shown inline. */
|
||||
onSubmit: (command: FeatureCommand) => Promise<void>;
|
||||
onClose: () => void;
|
||||
/** The viewport, for the forms that place things in it with the pointer (a hole). */
|
||||
view?: SceneView | null;
|
||||
}) {
|
||||
return (
|
||||
<Dialog open={request !== null} modal={false} onOpenChange={(open) => !open && onClose()}>
|
||||
@@ -93,6 +98,7 @@ export function FeatureDialog({
|
||||
onSelectionMode={onSelectionMode}
|
||||
onSubmit={onSubmit}
|
||||
onClose={onClose}
|
||||
view={view ?? null}
|
||||
/>
|
||||
)}
|
||||
</Dialog>
|
||||
@@ -107,6 +113,7 @@ function FeatureForm({
|
||||
onSelectionMode,
|
||||
onSubmit,
|
||||
onClose,
|
||||
view,
|
||||
}: {
|
||||
request: DialogRequest;
|
||||
state: FeatureState;
|
||||
@@ -115,6 +122,7 @@ function FeatureForm({
|
||||
onSelectionMode: (mode: SelectionMode) => void;
|
||||
onSubmit: (command: FeatureCommand) => Promise<void>;
|
||||
onClose: () => void;
|
||||
view: SceneView | null;
|
||||
}) {
|
||||
const { spec, edit } = request;
|
||||
const editing = Boolean(edit);
|
||||
@@ -309,6 +317,30 @@ function FeatureForm({
|
||||
setServerError(null);
|
||||
};
|
||||
|
||||
// A hole is placed with the pointer: its ghost follows the model under the pointer, a click puts the start point there
|
||||
// (and, for "along the face's normal", the direction into the material).
|
||||
const number = (value: unknown, fallback: number) => (Number.isFinite(Number(value)) && value !== "" ? Number(value) : fallback);
|
||||
const position = Array.isArray(form.position) && form.position.length === 3 && form.position.every((v) => v !== "" && Number.isFinite(Number(v))) ? (form.position.map(Number) as Vec3) : null;
|
||||
const holeDraft: HoleDraft | null =
|
||||
spec.id === "hole"
|
||||
? {
|
||||
position,
|
||||
direction: String(form.direction ?? "-z"),
|
||||
vector: [number(form.dx, 0), number(form.dy, 0), number(form.dz, -1)],
|
||||
diameter: number(form.diameter, 6),
|
||||
depth: number(form.depth, 10),
|
||||
}
|
||||
: null;
|
||||
const placeHole = (point: Vec3, normal: Vec3) => {
|
||||
setForm((previous) => ({
|
||||
...previous,
|
||||
position: point.map((c) => String(round4(c))),
|
||||
...(previous.direction === "face" ? { dx: String(round4(-normal[0])), dy: String(round4(-normal[1])), dz: String(round4(-normal[2])) } : {}),
|
||||
}));
|
||||
setNote(`Start point placed at (${point.map((c) => round4(c)).join(", ")}).`);
|
||||
setServerError(null);
|
||||
};
|
||||
|
||||
// A hole opened from a selected face takes its start point and direction from it as soon as the face is described.
|
||||
const faceUsed = useRef(false);
|
||||
useEffect(() => {
|
||||
@@ -334,6 +366,7 @@ function FeatureForm({
|
||||
return (
|
||||
<DialogContent
|
||||
aria-describedby={undefined}
|
||||
data-hole-placer={holeDraft && view ? "on" : undefined}
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !(event.target instanceof HTMLTextAreaElement) && !(event.target instanceof HTMLButtonElement)) {
|
||||
@@ -404,6 +437,7 @@ function FeatureForm({
|
||||
{busy ? "working…" : editing ? "apply" : "add"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
{holeDraft && view && <HolePlacer view={view} draft={holeDraft} onPlace={placeHole} />}
|
||||
</DialogContent>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { drillDirection } from "./HolePlacer";
|
||||
|
||||
describe("the hole's drilling direction", () => {
|
||||
it("follows the surface into the material, an axis, or the vector", () => {
|
||||
expect(drillDirection({ direction: "face", vector: null }, [0, 0, 1])).toEqual([-0, -0, -1]);
|
||||
expect(drillDirection({ direction: "+x", vector: null }, [0, 0, 1])).toEqual([1, 0, 0]);
|
||||
expect(drillDirection({ direction: "vector", vector: [0, 3, 4] }, null)).toEqual([0, 0.6, 0.8]);
|
||||
// a placed hole of "face" off the model keeps the direction its form holds
|
||||
expect(drillDirection({ direction: "face", vector: [0, -2, 0] }, null)).toEqual([0, -1, 0]);
|
||||
expect(drillDirection({ direction: "vector", vector: [0, 0, 0] }, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
|
||||
import type { Vec3 } from "@/lib/sketch-plane";
|
||||
import { rayThrough } from "@/scene/camera-projection";
|
||||
import { OVERLAY_LAYER } from "@/scene/renderer/brep-renderer";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
const AXES: Record<string, Vec3> = { "+x": [1, 0, 0], "-x": [-1, 0, 0], "+y": [0, 1, 0], "-y": [0, -1, 0], "+z": [0, 0, 1], "-z": [0, 0, -1] };
|
||||
const PLACED = "#e4572e";
|
||||
const HOVER = "#f2a65a";
|
||||
|
||||
/** Where a hole goes, as its form says: the start point, how the direction is chosen ("face" follows the surface's
|
||||
* normal into the material), the vector for "face"/"vector", the diameter and the depth (mm). */
|
||||
export type HoleDraft = { position: Vec3 | null; direction: string; vector: Vec3 | null; diameter: number; depth: number };
|
||||
|
||||
/** The drilling direction of a draft at a surface point with outward normal `normal` (null when not on the model). */
|
||||
export function drillDirection(draft: Pick<HoleDraft, "direction" | "vector">, normal: Vec3 | null): Vec3 | null {
|
||||
if (draft.direction in AXES) return AXES[draft.direction];
|
||||
if (draft.direction === "face" && normal) return [-normal[0], -normal[1], -normal[2]];
|
||||
const v = draft.vector;
|
||||
const length = v ? Math.hypot(v[0], v[1], v[2]) : 0;
|
||||
return v && length > 1e-9 ? [v[0] / length, v[1] / length, v[2] / length] : null;
|
||||
}
|
||||
|
||||
/** A ghost of the hole: the cylinder it cuts and a ring where it starts, drawn through the model (world = CAD / 1000). */
|
||||
function ghost(color: string, opacity: number): THREE.Group {
|
||||
const group = new THREE.Group();
|
||||
const body = new THREE.Mesh(
|
||||
new THREE.CylinderGeometry(1, 1, 1, 40, 1, true).rotateX(Math.PI / 2).translate(0, 0, 0.5),
|
||||
new THREE.MeshBasicMaterial({ color, transparent: true, opacity, depthTest: false, depthWrite: false, side: THREE.DoubleSide }),
|
||||
);
|
||||
body.name = "body";
|
||||
const ring = new THREE.LineLoop(
|
||||
new THREE.BufferGeometry().setFromPoints(Array.from({ length: 48 }, (_, i) => new THREE.Vector3(Math.cos((i / 48) * Math.PI * 2), Math.sin((i / 48) * Math.PI * 2), 0))),
|
||||
new THREE.LineBasicMaterial({ color, depthTest: false }),
|
||||
);
|
||||
ring.name = "ring";
|
||||
group.add(body, ring);
|
||||
group.renderOrder = 20;
|
||||
group.traverse((o) => {
|
||||
o.layers.enable(OVERLAY_LAYER);
|
||||
o.renderOrder = 20;
|
||||
});
|
||||
group.visible = false;
|
||||
return group;
|
||||
}
|
||||
|
||||
/** Puts a ghost at `point` (mm), cutting along `direction`, `diameter` across and `depth` deep. */
|
||||
function place(object: THREE.Group, point: Vec3, direction: Vec3, diameter: number, depth: number): void {
|
||||
const r = Math.max(diameter, 0.01) / 2000;
|
||||
object.position.set(point[0] / 1000, point[1] / 1000, point[2] / 1000);
|
||||
object.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), new THREE.Vector3(...direction));
|
||||
object.getObjectByName("body")!.scale.set(r, r, Math.max(depth, 0.01) / 1000);
|
||||
object.getObjectByName("ring")!.scale.set(r, r, 1);
|
||||
object.visible = true;
|
||||
}
|
||||
|
||||
/** While a hole's form is open: a ghost of the hole follows the pointer over the model (its axis along the drilling
|
||||
* direction: the surface's normal there for "face"), and a click on the model places it, filling the start point (and
|
||||
* the direction, for "face"). The placed hole stays drawn while the form's numbers change. Display only: the point and
|
||||
* normal come from the drawn surface under the pointer; nothing is computed by the kernel. */
|
||||
export function HolePlacer({ view, draft, onPlace }: { view: SceneView; draft: HoleDraft; onPlace: (point: Vec3, normal: Vec3) => void }) {
|
||||
const draftRef = useRef(draft);
|
||||
draftRef.current = draft;
|
||||
const placeRef = useRef(onPlace);
|
||||
placeRef.current = onPlace;
|
||||
const placedRef = useRef<THREE.Group | null>(null);
|
||||
const placedNormal = useRef<Vec3 | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const { engine } = view;
|
||||
const hover = ghost(HOVER, 0.28);
|
||||
const placed = ghost(PLACED, 0.45);
|
||||
engine.threeScene.add(hover, placed);
|
||||
placedRef.current = placed;
|
||||
const raycaster = new THREE.Raycaster();
|
||||
const element = engine.domElement;
|
||||
const surfaceAt = (event: PointerEvent): { point: Vec3; normal: Vec3 } | null => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const ndc = new THREE.Vector2(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);
|
||||
rayThrough(raycaster, ndc, engine.camera);
|
||||
const hit = raycaster.intersectObjects(engine.modelRoot.children, true).find((h) => h.object instanceof THREE.Mesh && h.face && h.object.visible);
|
||||
if (!hit || !hit.face) return null;
|
||||
const normal = hit.face.normal.clone().transformDirection(hit.object.matrixWorld);
|
||||
// the side the camera looks at: a normal facing away is the triangle's back
|
||||
if (normal.dot(raycaster.ray.direction) > 0) normal.negate();
|
||||
return { point: [hit.point.x * 1000, hit.point.y * 1000, hit.point.z * 1000], normal: [normal.x, normal.y, normal.z] };
|
||||
};
|
||||
let down: { x: number; y: number } | null = null;
|
||||
const onMove = (event: PointerEvent) => {
|
||||
if (event.buttons !== 0) {
|
||||
hover.visible = false;
|
||||
return;
|
||||
}
|
||||
const at = surfaceAt(event);
|
||||
const direction = at && drillDirection(draftRef.current, at.normal);
|
||||
if (at && direction) place(hover, at.point, direction, draftRef.current.diameter, draftRef.current.depth);
|
||||
else hover.visible = false;
|
||||
element.style.cursor = at ? "crosshair" : "";
|
||||
engine.invalidate();
|
||||
};
|
||||
const onDown = (event: PointerEvent) => {
|
||||
down = event.button === 0 ? { x: event.clientX, y: event.clientY } : null;
|
||||
};
|
||||
const onUp = (event: PointerEvent) => {
|
||||
if (!down || Math.hypot(event.clientX - down.x, event.clientY - down.y) > 4) return;
|
||||
down = null;
|
||||
const at = surfaceAt(event);
|
||||
if (!at) return;
|
||||
placedNormal.current = at.normal;
|
||||
placeRef.current(at.point, at.normal);
|
||||
};
|
||||
const onLeave = () => {
|
||||
hover.visible = false;
|
||||
engine.invalidate();
|
||||
};
|
||||
element.addEventListener("pointermove", onMove);
|
||||
element.addEventListener("pointerdown", onDown);
|
||||
element.addEventListener("pointerup", onUp);
|
||||
element.addEventListener("pointerleave", onLeave);
|
||||
return () => {
|
||||
element.removeEventListener("pointermove", onMove);
|
||||
element.removeEventListener("pointerdown", onDown);
|
||||
element.removeEventListener("pointerup", onUp);
|
||||
element.removeEventListener("pointerleave", onLeave);
|
||||
element.style.cursor = "";
|
||||
for (const object of [hover, placed]) {
|
||||
object.removeFromParent();
|
||||
object.traverse((o) => {
|
||||
const mesh = o as THREE.Mesh;
|
||||
mesh.geometry?.dispose();
|
||||
(mesh.material as THREE.Material | undefined)?.dispose?.();
|
||||
});
|
||||
}
|
||||
placedRef.current = null;
|
||||
engine.invalidate();
|
||||
};
|
||||
}, [view]);
|
||||
|
||||
// The placed hole follows the form: its point, direction, diameter and depth.
|
||||
useEffect(() => {
|
||||
const placed = placedRef.current;
|
||||
if (!placed) return;
|
||||
const direction = draft.position && drillDirection(draft, placedNormal.current);
|
||||
if (draft.position && direction) place(placed, draft.position, direction, draft.diameter, draft.depth);
|
||||
else placed.visible = false;
|
||||
view.engine.invalidate();
|
||||
}, [draft, view]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import * as THREE from "three";
|
||||
import { TransformControls } from "three/addons/controls/TransformControls.js";
|
||||
import { Move3d, RotateCw } from "lucide-react";
|
||||
|
||||
import { patchCorners } from "@/lib/workplanes";
|
||||
import { placeValues, placedFrame, type PlaceFrame, type PlaceValues } from "@/lib/workplane-place";
|
||||
import { OVERLAY_LAYER } from "@/scene/renderer/brep-renderer";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
import type { Vec3 } from "@/lib/sketch-plane";
|
||||
|
||||
export type PlaceMode = "translate" | "rotate";
|
||||
|
||||
/** One base the placer offers: a name the cell writes (XY, a workplane variable, "face") and its frame in world mm. */
|
||||
export type PlaceBase = { value: string; label: string; frame: PlaceFrame };
|
||||
|
||||
const COLOR = "#2563eb";
|
||||
/** Default snapping while dragging (Shift drags freely): 1 mm, 5 degrees. */
|
||||
const SNAP = { move: 0.001, turn: THREE.MathUtils.degToRad(5) };
|
||||
|
||||
/** World (CAD mm, Z up) frame -> the pose of an object in the viewer's world (metres, the same axes). */
|
||||
function poseOf(frame: PlaceFrame): { position: THREE.Vector3; quaternion: THREE.Quaternion } {
|
||||
const basis = new THREE.Matrix4().makeBasis(new THREE.Vector3(...frame.x_axis), new THREE.Vector3(...frame.y_axis), new THREE.Vector3(...frame.normal));
|
||||
return { position: new THREE.Vector3(frame.origin[0] / 1000, frame.origin[1] / 1000, frame.origin[2] / 1000), quaternion: new THREE.Quaternion().setFromRotationMatrix(basis) };
|
||||
}
|
||||
|
||||
function frameOf(object: THREE.Object3D): PlaceFrame {
|
||||
const axis = (x: number, y: number, z: number): Vec3 => {
|
||||
const v = new THREE.Vector3(x, y, z).applyQuaternion(object.quaternion);
|
||||
return [v.x, v.y, v.z];
|
||||
};
|
||||
return {
|
||||
origin: [object.position.x * 1000, object.position.y * 1000, object.position.z * 1000],
|
||||
x_axis: axis(1, 0, 0),
|
||||
y_axis: axis(0, 1, 0),
|
||||
normal: axis(0, 0, 1),
|
||||
};
|
||||
}
|
||||
|
||||
/** The draft plane: a square patch in the frame's XY with its outline and a normal tick, drawn over the model. */
|
||||
function draftPatch(half: number): THREE.Group {
|
||||
const group = new THREE.Group();
|
||||
const frame: PlaceFrame = { origin: [0, 0, 0], x_axis: [1, 0, 0], y_axis: [0, 1, 0], normal: [0, 0, 1] };
|
||||
const corners = patchCorners(frame, half / 1000).map((c) => new THREE.Vector3(...c));
|
||||
group.add(
|
||||
new THREE.Mesh(
|
||||
new THREE.BufferGeometry().setFromPoints([corners[0], corners[1], corners[2], corners[0], corners[2], corners[3]]),
|
||||
new THREE.MeshBasicMaterial({ color: COLOR, transparent: true, opacity: 0.18, side: THREE.DoubleSide, depthWrite: false }),
|
||||
),
|
||||
);
|
||||
group.add(new THREE.Line(new THREE.BufferGeometry().setFromPoints([...corners, corners[0]]), new THREE.LineBasicMaterial({ color: COLOR })));
|
||||
group.add(new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3(0, 0, half / 2000)]), new THREE.LineBasicMaterial({ color: COLOR })));
|
||||
return group;
|
||||
}
|
||||
|
||||
/** Places a new workplane with handles: the draft plane sits on `base` moved and turned by `values`; dragging the move
|
||||
* arrows or the turn rings changes the values (snapped to 1 mm / 5 degrees, Shift for free), typing them moves the
|
||||
* handles. Nothing is computed from the model: the frame is the base's and the SDK's own formula (lib/workplane-place). */
|
||||
export function WorkplanePlacer({
|
||||
view,
|
||||
base,
|
||||
values,
|
||||
mode,
|
||||
half,
|
||||
onChange,
|
||||
}: {
|
||||
view: SceneView;
|
||||
base: PlaceFrame;
|
||||
values: PlaceValues;
|
||||
mode: PlaceMode;
|
||||
/** Half the patch's side, mm. */
|
||||
half: number;
|
||||
onChange: (values: PlaceValues) => void;
|
||||
}) {
|
||||
const targetRef = useRef<THREE.Group | null>(null);
|
||||
const controlsRef = useRef<TransformControls | null>(null);
|
||||
const dragging = useRef(false);
|
||||
const changeRef = useRef(onChange);
|
||||
changeRef.current = onChange;
|
||||
const baseRef = useRef(base);
|
||||
baseRef.current = base;
|
||||
|
||||
// The draft and its handles, for the life of the placer.
|
||||
useEffect(() => {
|
||||
const { engine } = view;
|
||||
const target = new THREE.Group();
|
||||
target.add(draftPatch(half));
|
||||
target.traverse((o) => o.layers.enable(OVERLAY_LAYER));
|
||||
engine.threeScene.add(target);
|
||||
const controls = new TransformControls(engine.camera, engine.domElement);
|
||||
controls.setSpace("local");
|
||||
controls.setTranslationSnap(SNAP.move);
|
||||
controls.setRotationSnap(SNAP.turn);
|
||||
controls.attach(target);
|
||||
const helper = controls.getHelper();
|
||||
helper.traverse((o) => o.layers.enable(OVERLAY_LAYER));
|
||||
engine.threeScene.add(helper);
|
||||
const onRender = () => engine.invalidate();
|
||||
const onDrag = (event: { value: unknown }) => {
|
||||
dragging.current = Boolean(event.value);
|
||||
engine.controls.enabled = !dragging.current;
|
||||
};
|
||||
const onObject = () => changeRef.current(placeValues(baseRef.current, frameOf(target)));
|
||||
controls.addEventListener("change", onRender);
|
||||
controls.addEventListener("dragging-changed", onDrag);
|
||||
controls.addEventListener("objectChange", onObject);
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Shift") return;
|
||||
const free = event.type === "keydown";
|
||||
controls.setTranslationSnap(free ? null : SNAP.move);
|
||||
controls.setRotationSnap(free ? null : SNAP.turn);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
window.addEventListener("keyup", onKey);
|
||||
targetRef.current = target;
|
||||
controlsRef.current = controls;
|
||||
engine.invalidate();
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
window.removeEventListener("keyup", onKey);
|
||||
controls.removeEventListener("change", onRender);
|
||||
controls.removeEventListener("dragging-changed", onDrag);
|
||||
controls.removeEventListener("objectChange", onObject);
|
||||
controls.detach();
|
||||
helper.removeFromParent();
|
||||
controls.dispose();
|
||||
target.removeFromParent();
|
||||
target.traverse((o) => {
|
||||
const mesh = o as THREE.Mesh;
|
||||
mesh.geometry?.dispose();
|
||||
(mesh.material as THREE.Material | undefined)?.dispose?.();
|
||||
});
|
||||
engine.controls.enabled = true;
|
||||
engine.invalidate();
|
||||
targetRef.current = null;
|
||||
controlsRef.current = null;
|
||||
};
|
||||
}, [view, half]);
|
||||
|
||||
useEffect(() => {
|
||||
controlsRef.current?.setMode(mode);
|
||||
view.engine.invalidate();
|
||||
}, [mode, view]);
|
||||
|
||||
// Typed values (or a new base) move the draft; a drag in progress is the source of the values, not their target.
|
||||
useEffect(() => {
|
||||
const target = targetRef.current;
|
||||
if (!target || dragging.current) return;
|
||||
const pose = poseOf(placedFrame(base, values));
|
||||
target.position.copy(pose.position);
|
||||
target.quaternion.copy(pose.quaternion);
|
||||
target.updateMatrixWorld(true);
|
||||
view.engine.invalidate();
|
||||
}, [base, values, view, half]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The placer's panel: the base, move or turn, the six numbers, create and cancel. */
|
||||
export function WorkplanePlacePanel({
|
||||
bases,
|
||||
base,
|
||||
values,
|
||||
mode,
|
||||
name,
|
||||
busy,
|
||||
error,
|
||||
onBase,
|
||||
onMode,
|
||||
onValues,
|
||||
onName,
|
||||
onCreate,
|
||||
onCancel,
|
||||
}: {
|
||||
bases: PlaceBase[];
|
||||
base: string;
|
||||
values: PlaceValues;
|
||||
mode: PlaceMode;
|
||||
name: string;
|
||||
busy: boolean;
|
||||
error: string | null;
|
||||
onBase: (value: string) => void;
|
||||
onMode: (mode: PlaceMode) => void;
|
||||
onValues: (values: PlaceValues) => void;
|
||||
onName: (name: string) => void;
|
||||
onCreate: () => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<Record<string, string>>({});
|
||||
const fields: { key: string; label: string; get: (v: PlaceValues) => number; set: (v: PlaceValues, n: number) => PlaceValues }[] = [
|
||||
{ key: "dx", label: "x", get: (v) => v.move[0], set: (v, n) => ({ ...v, move: [n, v.move[1], v.move[2]] }) },
|
||||
{ key: "dy", label: "y", get: (v) => v.move[1], set: (v, n) => ({ ...v, move: [v.move[0], n, v.move[2]] }) },
|
||||
{ key: "dz", label: "n", get: (v) => v.move[2], set: (v, n) => ({ ...v, move: [v.move[0], v.move[1], n] }) },
|
||||
{ key: "rx", label: "∠x", get: (v) => v.rx, set: (v, n) => ({ ...v, rx: n }) },
|
||||
{ key: "ry", label: "∠y", get: (v) => v.ry, set: (v, n) => ({ ...v, ry: n }) },
|
||||
{ key: "rz", label: "∠n", get: (v) => v.rz, set: (v, n) => ({ ...v, rz: n }) },
|
||||
];
|
||||
const commit = (key: string, text: string) => {
|
||||
const field = fields.find((f) => f.key === key)!;
|
||||
const number = Number(text);
|
||||
setDraft((d) => {
|
||||
const { [key]: _, ...rest } = d;
|
||||
return rest;
|
||||
});
|
||||
if (Number.isFinite(number)) onValues(field.set(values, number));
|
||||
};
|
||||
return (
|
||||
<div className="pointer-events-auto absolute left-3 top-3 z-30 flex max-w-[min(440px,90%)] flex-col gap-2 border-2 border-primary bg-popover px-3 py-2 text-[11px] shadow-[4px_4px_0_var(--shadow-hard)]" data-testid="workplane-placer">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold">Workplane</span>
|
||||
<input
|
||||
id="workplane-place-name"
|
||||
aria-label="name"
|
||||
className="w-20 border border-input bg-background px-1 font-mono"
|
||||
value={name}
|
||||
onChange={(event) => onName(event.target.value)}
|
||||
/>
|
||||
<span className="text-muted-foreground">on</span>
|
||||
<select id="workplane-place-base" aria-label="base" className="border border-input bg-background px-1" value={base} onChange={(event) => onBase(event.target.value)}>
|
||||
{bases.map((item) => (
|
||||
<option key={item.value} value={item.value}>
|
||||
{item.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="flex border border-input">
|
||||
<button type="button" title="Move (G)" className={`flex items-center gap-1 px-1.5 ${mode === "translate" ? "bg-primary text-primary-foreground" : ""}`} onClick={() => onMode("translate")}>
|
||||
<Move3d className="size-3" /> move
|
||||
</button>
|
||||
<button type="button" title="Turn (R)" className={`flex items-center gap-1 px-1.5 ${mode === "rotate" ? "bg-primary text-primary-foreground" : ""}`} onClick={() => onMode("rotate")}>
|
||||
<RotateCw className="size-3" /> turn
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{fields.map((field) => (
|
||||
<label key={field.key} className="flex items-center gap-0.5">
|
||||
<span className="text-muted-foreground">{field.label}</span>
|
||||
<input
|
||||
id={`workplane-place-${field.key}`}
|
||||
className="w-14 border border-input bg-background px-1 text-right font-mono tabular-nums"
|
||||
value={draft[field.key] ?? String(+field.get(values).toFixed(3))}
|
||||
onChange={(event) => setDraft((d) => ({ ...d, [field.key]: event.target.value }))}
|
||||
onBlur={(event) => commit(field.key, event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
commit(field.key, (event.target as HTMLInputElement).value);
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button type="button" disabled={busy} className="border-2 border-primary bg-primary px-2 py-0.5 font-semibold text-primary-foreground disabled:opacity-50" onClick={onCreate}>
|
||||
Create (Enter)
|
||||
</button>
|
||||
<button type="button" className="border border-border px-2 py-0.5 hover:bg-accent" onClick={onCancel}>
|
||||
Cancel (Esc)
|
||||
</button>
|
||||
<span className="text-muted-foreground">drag the arrows to move, the rings to turn · Shift: no snapping</span>
|
||||
</div>
|
||||
{error && (
|
||||
<div role="alert" className="text-fail">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,13 +8,6 @@ export const FEATURE_ICONS: Record<string, LucideIcon> = {
|
||||
cylinder: Cylinder,
|
||||
sphere: Globe,
|
||||
cone: Triangle,
|
||||
extrude_rect: Square,
|
||||
extrude_circle: Circle,
|
||||
extrude_polygon: Layers,
|
||||
revolve: RotateCw,
|
||||
loft_circles: Layers,
|
||||
loft_rects: Layers,
|
||||
sweep_circle: Spline,
|
||||
cut: Scissors,
|
||||
union: Combine,
|
||||
intersect: Combine,
|
||||
|
||||
@@ -117,7 +117,15 @@ export function SketchDrawer({ editor, plane, wide }: { editor: SketchEditor; pl
|
||||
</ul>
|
||||
<div className={HEAD}>profile</div>
|
||||
<div className="px-2 py-1.5 text-[11px] text-muted-foreground" data-testid="profile-info">
|
||||
{loops.length === 0 ? (
|
||||
{doc.output === "wire" ? (
|
||||
editor.wire ? (
|
||||
<>
|
||||
wire of profile <span className="text-name">{editor.wire.index}</span> ({editor.wire.closed ? "closed loop" : "open chain"}: {editor.wire.entities.join(", ")}). Choose another at the top, or click inside a loop.
|
||||
</>
|
||||
) : (
|
||||
"Draw a chain of lines, arcs or splines, or a closed loop: the wire is made of one."
|
||||
)
|
||||
) : loops.length === 0 ? (
|
||||
"Close a loop of lines, or draw a circle."
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -406,7 +406,12 @@ function SketchEditorView({
|
||||
if (nameError) return nameError;
|
||||
if (editor.error) return editor.error;
|
||||
if (!editor.fresh) return "solving the sketch…";
|
||||
if (editor.loops.length === 0) {
|
||||
if (editor.doc.output === "wire") {
|
||||
if (!editor.wire) {
|
||||
const why = editor.result?.unusable?.[0];
|
||||
return why ? `no profile for the wire: ${why}` : "draw a chain of lines, arcs or splines (or a closed loop): the wire needs a profile";
|
||||
}
|
||||
} else if (editor.loops.length === 0) {
|
||||
const why = editor.result?.unusable?.[0];
|
||||
return why ? `no closed profile: ${why}` : "close a loop of lines or draw a circle: the face needs a profile";
|
||||
}
|
||||
@@ -462,10 +467,11 @@ function SketchEditorView({
|
||||
/>
|
||||
<span className="whitespace-nowrap text-[10px] uppercase tracking-[0.08em] text-muted-foreground">on {planeLabel(plane)}</span>
|
||||
<StatusBadge editor={editor} compact />
|
||||
<OutputChoice editor={editor} />
|
||||
<Button type="button" size="sm" variant={editing ? "default" : "outline"} className="h-7 gap-1 px-2" data-testid="sketch-finish" aria-label="Finish the sketch" title="Finish: add the sketch to the notebook" disabled={busy} onClick={() => void finish()}>
|
||||
<Check /> {busy ? "working…" : "finish"}
|
||||
</Button>
|
||||
{!editing && (
|
||||
{!editing && editor.doc.output !== "wire" && (
|
||||
<Button type="button" size="sm" className="h-7 gap-1 px-2" data-testid="sketch-finish-extrude" aria-label="Finish the sketch and extrude it" title="Finish, then extrude the sketch (the most common next step)" disabled={busy} onClick={() => void finish(true)}>
|
||||
<Rocket /> finish and extrude
|
||||
</Button>
|
||||
@@ -509,3 +515,38 @@ function SketchEditorView({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Face or wire: what the sketch becomes, and for a wire which profile (a closed loop or an open chain, as the SDK lists them;
|
||||
* a click inside a loop picks it too). */
|
||||
function OutputChoice({ editor }: { editor: ReturnType<typeof useSketchEditor> }) {
|
||||
const wire = editor.doc.output === "wire";
|
||||
const tab = "h-7 px-2 text-[10px] font-bold uppercase tracking-[0.08em] aria-pressed:bg-primary aria-pressed:text-primary-foreground hover:bg-accent aria-pressed:hover:bg-primary";
|
||||
return (
|
||||
<span className="flex items-center gap-1" data-testid="sketch-output">
|
||||
<span className="flex border-2 border-input" role="group" aria-label="What the sketch makes">
|
||||
<button type="button" className={tab} aria-pressed={!wire} data-output="face" title="Face (closed profile): what extrude, revolve and cut take" onClick={() => editor.setOutput("face")}>
|
||||
face
|
||||
</button>
|
||||
<button type="button" className={tab} aria-pressed={wire} data-output="wire" title="Wire (path / profile curve): an open chain or a closed loop, for a sweep path or a loft section" onClick={() => editor.setOutput("wire")}>
|
||||
wire
|
||||
</button>
|
||||
</span>
|
||||
{wire && editor.wires.length > 0 && (
|
||||
<select
|
||||
aria-label="Profile of the wire"
|
||||
data-testid="sketch-wire-profile"
|
||||
className="h-7 max-w-44 border-2 border-input bg-background px-1 text-[11px]"
|
||||
value={editor.wire?.key ?? ""}
|
||||
onChange={(event) => editor.setWireKey(event.target.value)}
|
||||
onKeyDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
{editor.wires.map((w) => (
|
||||
<option key={w.key} value={w.key}>
|
||||
{w.index}: {w.closed ? "loop" : "chain"} {w.entities.join(", ")}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { splinePath,
|
||||
import { planeToWorld, rayPlane, type PlaneSpec } from "@/lib/sketch-plane";
|
||||
import { cameraSignature, planeToScreen, scaleAt, screenRay, screenToPlane, type Viewer } from "@/lib/sketch-view";
|
||||
import { CORNER_WORD, isProjected } from "@/lib/sketch-edit";
|
||||
import { bezierPath, isAnchorSpline, penPoles } from "@/lib/sketch-anchors";
|
||||
import type { PointerInfo, SketchEditor } from "@/lib/useSketchEditor";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
@@ -218,6 +219,8 @@ export function SketchOverlay({
|
||||
// Fillet and chamfer: the corner under the cursor (or the one being valued) shows its point and both lines.
|
||||
const corner = editor.cornerBox?.corner ?? editor.cornerHover;
|
||||
const cornerLines = new Set<string>(corner ? [corner.a, corner.b] : editor.pendingLine ? [editor.pendingLine] : []);
|
||||
// A wire sketch: the entities of the chosen profile are drawn as the wire.
|
||||
const wireIds = new Set(editor.wire?.entities ?? []);
|
||||
const strokeOf = (id: string, construct?: boolean) => {
|
||||
if (editor.flash.has(id)) return NAME;
|
||||
if (cutting && hover?.id === id) return FAIL;
|
||||
@@ -227,6 +230,7 @@ export function SketchOverlay({
|
||||
if (selection.includes(id)) return FOCUS;
|
||||
if (hover?.id === id) return FOCUS;
|
||||
if (construct) return MUTED;
|
||||
if (wireIds.has(id)) return NAME;
|
||||
return solved ? PASS : INK;
|
||||
};
|
||||
|
||||
@@ -320,14 +324,33 @@ export function SketchOverlay({
|
||||
const cur: P = [cursor.x, cursor.y];
|
||||
if (draft.tool === "line") return both(line(spotPos(draft.from), cur));
|
||||
if (draft.tool === "spline") {
|
||||
// the control polygon so far, to the cursor; the curve is the SDK's once it is made (Enter)
|
||||
const poles = [...draft.points.map(spotPos), cur];
|
||||
// the pen path so far and on to the cursor (while a press pulls out handles, the cursor is the handle's tip); the curve
|
||||
// is the SDK's once the path is made
|
||||
const anchors = draft.points.map(spotPos);
|
||||
const pressing = editor.pressingPen();
|
||||
const at = pressing ? anchors : [...anchors, cur];
|
||||
const handles = pressing ? draft.handles : [...draft.handles, null];
|
||||
const path = at.length > 1 ? bezierPath(penPoles(at, handles, false)) : [];
|
||||
return (
|
||||
<>
|
||||
{both(polyline(poles), { opacity: 0.7 })}
|
||||
{poles.slice(0, -1).map((p, i) => {
|
||||
{path.length > 1 && both(polyline(path))}
|
||||
{draft.handles.map((h, i) => {
|
||||
if (!h) return null;
|
||||
const a = anchors[i];
|
||||
const ends: P[] = [[a[0] - h[0], a[1] - h[1]], [a[0] + h[0], a[1] + h[1]]];
|
||||
return (
|
||||
<g key={`handle${i}`} fill="none">
|
||||
<path d={polyline([ends[0], a, ends[1]])} stroke={FOCUS} strokeWidth={1} opacity={0.8} />
|
||||
{ends.map((e, j) => {
|
||||
const s = project(e[0], e[1]);
|
||||
return s ? <rect key={j} x={s[0] - 3} y={s[1] - 3} width={6} height={6} transform={`rotate(45 ${s[0]} ${s[1]})`} fill={HALO} stroke={FOCUS} strokeWidth={1.4} /> : null;
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{anchors.map((p, i) => {
|
||||
const s = project(p[0], p[1]);
|
||||
return s ? <rect key={`pole${i}`} x={s[0] - 3.5} y={s[1] - 3.5} width={7} height={7} fill={HALO} stroke={FOCUS} strokeWidth={1.6} /> : null;
|
||||
return s ? <circle key={`anchor${i}`} cx={s[0]} cy={s[1]} r={4} fill={HALO} stroke={FOCUS} strokeWidth={1.8} /> : null;
|
||||
})}
|
||||
</>
|
||||
);
|
||||
@@ -546,8 +569,9 @@ export function SketchOverlay({
|
||||
</text>
|
||||
)}
|
||||
{loops.map((loop) => {
|
||||
const isOuter = loop.key === choice.outer;
|
||||
const isInner = choice.inner.includes(loop.key);
|
||||
const wireMode = doc.output === "wire"; // a wire sketch fills the loop it makes the wire of, and has no holes
|
||||
const isOuter = wireMode ? loop.key === editor.wire?.key : loop.key === choice.outer;
|
||||
const isInner = !wireMode && choice.inner.includes(loop.key);
|
||||
return (
|
||||
<path
|
||||
key={loop.key}
|
||||
@@ -563,16 +587,21 @@ export function SketchOverlay({
|
||||
})}
|
||||
{doc.entities.map((e) => {
|
||||
if (e.kind !== "bspline") return null;
|
||||
const active = selection.includes(e.id) || hover?.id === e.id;
|
||||
const poles = (e.control_points ?? []).map((id) => pts.get(id)).filter((p): p is P => Boolean(p));
|
||||
const anchored = isAnchorSpline(e);
|
||||
const ids = e.control_points ?? [];
|
||||
const showing = anchored && ids.some((id) => editor.shown.has(id));
|
||||
const active = selection.includes(e.id) || hover?.id === e.id || showing;
|
||||
const poles = ids.map((id) => pts.get(id)).filter((p): p is P => Boolean(p));
|
||||
const comb = result?.curves?.[e.id];
|
||||
// the control polygon always (its points are the handles); the curvature comb while the spline is picked
|
||||
// the longest tooth is a quarter of the spline's extent, whatever its curvature
|
||||
// A spline in anchor form shows the handles of its anchors while it is picked (anchor to handle, each side); another
|
||||
// B-spline its control polygon always (its points are what moves it). The curvature comb shows while it is picked;
|
||||
// the longest tooth is a quarter of the spline's extent, whatever its curvature.
|
||||
const arms = showing && poles.length === ids.length ? ids.map((_, i) => i).filter((i) => i % 3 !== 0).map((i) => polyline([poles[i % 3 === 1 ? i - 1 : i + 1], poles[i]])).join(" ") : "";
|
||||
const scale = comb ? (0.25 * Math.max(...poles.map((p) => Math.hypot(p[0] - poles[0][0], p[1] - poles[0][1])), 1)) / Math.max(...comb.curvatures, 1e-9) : 0;
|
||||
const tips = comb ? comb.points.map((p, i): P => [p[0] - comb.normals[i][0] * comb.curvatures[i] * scale, p[1] - comb.normals[i][1] * comb.curvatures[i] * scale]) : [];
|
||||
return (
|
||||
<g key={`poles-${e.id}`} fill="none" pointerEvents="none" data-control-polygon={e.id}>
|
||||
<path d={polyline(poles)} stroke={MUTED} strokeWidth={1} strokeDasharray="3 3" opacity={active ? 0.9 : 0.5} />
|
||||
<g key={`poles-${e.id}`} fill="none" pointerEvents="none" data-control-polygon={anchored ? undefined : e.id} data-handles={showing ? e.id : undefined}>
|
||||
{anchored ? arms && <path d={arms} stroke={FOCUS} strokeWidth={1.2} opacity={0.85} /> : <path d={polyline(poles)} stroke={MUTED} strokeWidth={1} strokeDasharray="3 3" opacity={active ? 0.9 : 0.5} />}
|
||||
{active && comb && (
|
||||
<g data-curvature-comb={e.id}>
|
||||
<path d={comb.points.map((p, i) => polyline([p, tips[i]])).join(" ")} stroke={NAME} strokeWidth={1} opacity={0.75} />
|
||||
@@ -585,17 +614,18 @@ export function SketchOverlay({
|
||||
{doc.entities.map((e) => {
|
||||
const d = entityPath(e);
|
||||
if (!d) return null;
|
||||
const picked = selection.includes(e.id) || hover?.id === e.id || editor.flash.has(e.id) || cornerLines.has(e.id);
|
||||
const picked = selection.includes(e.id) || hover?.id === e.id || editor.flash.has(e.id) || cornerLines.has(e.id) || wireIds.has(e.id);
|
||||
const projected = isProjected(e.id); // fixed reference copies of another sketch: muted, dotted
|
||||
const dash = projected ? "1.5 4" : e.construction ? "6 4" : undefined;
|
||||
return (
|
||||
<g key={e.id} fill="none" strokeLinecap="round" strokeLinejoin="round" data-entity={e.id} data-projected={projected || undefined} data-flash={editor.flash.has(e.id) || undefined}>
|
||||
<g key={e.id} fill="none" strokeLinecap="round" strokeLinejoin="round" data-entity={e.id} data-projected={projected || undefined} data-flash={editor.flash.has(e.id) || undefined} data-wire={wireIds.has(e.id) || undefined}>
|
||||
<path d={d} stroke={HALO} strokeWidth={picked ? 6.5 : 5} opacity={0.85} strokeDasharray={dash} />
|
||||
<path d={d} stroke={strokeOf(e.id, e.construction)} strokeWidth={picked ? 3 : projected ? 2.6 : 2.2} strokeDasharray={dash} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{doc.points.map((p) => {
|
||||
if (editor.hidden.has(p.id)) return null; // the handle of a spline that is not picked
|
||||
const at = pts.get(p.id) ?? [p.x, p.y];
|
||||
const s = project(at[0], at[1]);
|
||||
if (!s) return null;
|
||||
@@ -603,6 +633,11 @@ export function SketchOverlay({
|
||||
const picked = selection.includes(p.id) || hover?.id === p.id;
|
||||
const projected = isProjected(p.id);
|
||||
const color = editor.flash.has(p.id) ? NAME : editor.failing.has(p.id) ? FAIL : editor.highlighted.has(p.id) ? NAME : picked || corner?.point === p.id ? FOCUS : projected ? MUTED : fixed || solved ? PASS : INK;
|
||||
if (editor.shown.has(p.id)) {
|
||||
// a handle: a small hollow diamond, filled while picked
|
||||
const r = picked ? 5 : 4;
|
||||
return <rect key={p.id} x={s[0] - r} y={s[1] - r} width={2 * r} height={2 * r} transform={`rotate(45 ${s[0]} ${s[1]})`} fill={picked ? FOCUS : HALO} stroke={fixed ? PASS : FOCUS} strokeWidth={1.6} data-point={p.id} data-handle />;
|
||||
}
|
||||
if (projected) {
|
||||
return <rect key={p.id} x={s[0] - 4} y={s[1] - 4} width={8} height={8} transform={`rotate(45 ${s[0]} ${s[1]})`} fill={HALO} stroke={color} strokeWidth={2} data-point={p.id} data-projected />;
|
||||
}
|
||||
@@ -641,6 +676,26 @@ export function SketchOverlay({
|
||||
</button>
|
||||
);
|
||||
})()}
|
||||
{editor.convertTarget && (() => {
|
||||
// a B-spline with control points: one click writes it in anchor form (the SDK keeps the curve)
|
||||
const e = doc.entities.find((item) => item.id === editor.convertTarget);
|
||||
const end = pts.get(e?.end ?? "");
|
||||
const s = end ? project(end[0], end[1]) : null;
|
||||
if (!s) return null;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="convert-spline"
|
||||
title="Write this B-spline as anchors with a handle on each side, keeping its shape (SDK convert_spline_to_anchors_rsketch)"
|
||||
className="absolute z-20 border-2 border-primary bg-popover px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em] shadow-[3px_3px_0_var(--shadow-hard)] hover:bg-accent"
|
||||
style={{ left: Math.min(Math.max(s[0] + 14, 4), size.w - 170), top: Math.min(Math.max(s[1] - 34, 4), size.h - 30) }}
|
||||
onPointerDown={(ev) => ev.stopPropagation()}
|
||||
onClick={() => editor.convertSpline(editor.convertTarget!)}
|
||||
>
|
||||
convert to anchors (K)
|
||||
</button>
|
||||
);
|
||||
})()}
|
||||
{cornerBoxNode}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -9,7 +9,7 @@ export const TOOLS: { id: Tool; label: string; key: string; icon: typeof Slash }
|
||||
{ id: "line", label: "Line (chained; Esc ends)", key: "L", icon: Slash },
|
||||
{ id: "circle", label: "Circle: centre, then radius", key: "C", icon: Circle },
|
||||
{ id: "arc", label: "Arc: centre, start, end (counter-clockwise)", key: "A", icon: Spline },
|
||||
{ id: "spline", label: "B-spline: click its control points; Enter makes it, a click on the first point closes it (SDK add_bspline_rsketch)", key: "B", icon: Waves },
|
||||
{ id: "spline", label: "Spline (pen): click anchors, press and drag for handles; Enter makes it, a click on the first anchor closes it (SDK add_bspline_rsketch, anchor form)", key: "B", icon: Waves },
|
||||
{ id: "delete", label: "Delete", key: "D", icon: Trash2 },
|
||||
{ id: "trim", label: "Trim: cut an entity back to its neighbours (SDK trim_rsketch)", key: "T", icon: Scissors },
|
||||
{ id: "extend", label: "Extend: grow a line's end to the next entity (SDK extend_rsketch)", key: "E", icon: UnfoldHorizontal },
|
||||
|
||||
@@ -9,7 +9,7 @@ const commands = [
|
||||
make("fillet", "Fillet", "Features", ["round"], "Round the picked edges."),
|
||||
make("chamfer", "Chamfer", "Features", ["bevel"], "Bevel the picked edges."),
|
||||
make("linear_pattern", "Linear pattern", "Pattern", ["array"], "Copies along a direction"),
|
||||
make("loft_rects", "Loft rectangles", "Profiles", [], "A solid between rectangles"),
|
||||
make("op.loft_rsolid", "Loft → solid", "Solids", [], "A solid through profiles"),
|
||||
];
|
||||
|
||||
describe("searchCommands", () => {
|
||||
@@ -33,7 +33,7 @@ describe("searchCommands", () => {
|
||||
});
|
||||
|
||||
describe("registry helpers", () => {
|
||||
it("lists groups in the order of the data", () => expect(commandGroups(commands)).toEqual(["Primitives", "Features", "Pattern", "Profiles"]));
|
||||
it("lists groups in the order of the data", () => expect(commandGroups(commands)).toEqual(["Primitives", "Features", "Pattern", "Solids"]));
|
||||
it("keeps recents unique, newest first, bounded", () => {
|
||||
expect(pushRecent(["a", "b"], "b")).toEqual(["b", "a"]);
|
||||
expect(pushRecent(Array.from({ length: 12 }, (_, i) => `x${i}`), "n")).toHaveLength(12);
|
||||
|
||||
@@ -223,13 +223,6 @@ const SYNONYMS: Record<string, string[]> = {
|
||||
cylinder: ["rod", "pin", "tube", "round"],
|
||||
sphere: ["ball", "globe"],
|
||||
cone: ["frustum", "taper", "countersink"],
|
||||
extrude_rect: ["pad", "boss", "prism", "square"],
|
||||
extrude_circle: ["pad", "boss", "disc", "round"],
|
||||
extrude_polygon: ["pad", "boss", "sketch", "outline"],
|
||||
revolve: ["lathe", "spin", "turn"],
|
||||
loft_circles: ["blend", "transition"],
|
||||
loft_rects: ["blend", "transition"],
|
||||
sweep_circle: ["pipe", "rail", "path", "tube"],
|
||||
cut: ["subtract", "remove", "difference", "pocket"],
|
||||
union: ["join", "merge", "add", "combine", "fuse"],
|
||||
intersect: ["common", "overlap", "keep"],
|
||||
|
||||
@@ -617,9 +617,6 @@ export function holeFromFace(item: { properties: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
const NAME_BASE: Record<string, string> = {
|
||||
extrude_rect: "block",
|
||||
extrude_circle: "disc",
|
||||
extrude_polygon: "profile_solid",
|
||||
extrude_sketch: "extrusion",
|
||||
revolve_sketch: "revolution",
|
||||
cut_sketch: "pocket",
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { emptyDoc, normalizeDoc, wireProfiles, type SketchDoc, type SolveResult } from "@/lib/sketch";
|
||||
import { addPenSpline, anchorRoles, bezierPath, handlePoints, isAnchorSpline, isSmooth, mirrorHandle, penPoles, shownHandles, smoothAnchors } from "@/lib/sketch-anchors";
|
||||
import { convertSplineRequest, insertAnchorRequest, removeAnchorRequest } from "@/lib/sketch-edit";
|
||||
|
||||
const opts = { auto: false, construction: false };
|
||||
const at = (spot: { x: number; y: number }): [number, number] => [spot.x, spot.y];
|
||||
|
||||
describe("the pen tool makes B-splines in anchor form", () => {
|
||||
it("three clicks: anchors with a handle on each side, knots 0..n, inner multiplicities 3", () => {
|
||||
const made = addPenSpline(emptyDoc(), [{ spot: { x: 0, y: 0 } }, { spot: { x: 10, y: 10 } }, { spot: { x: 20, y: 0 } }], false, opts, at)!;
|
||||
const spline = made.doc.entities[0];
|
||||
expect(spline).toMatchObject({ kind: "bspline", degree: 3, knots: [0, 1, 2], multiplicities: [4, 3, 4] });
|
||||
expect(spline.control_points).toHaveLength(7);
|
||||
expect(spline.start).toBe(spline.control_points![0]);
|
||||
expect(spline.end).toBe(spline.control_points![6]);
|
||||
expect(isAnchorSpline(spline)).toBe(true);
|
||||
// the middle anchor is smooth: its handles lie on one line through it (Catmull-Rom tangent, a sixth of the neighbours' span)
|
||||
const p = new Map(made.doc.points.map((q) => [q.id, [q.x, q.y] as [number, number]]));
|
||||
const [, , inH, mid, outH] = spline.control_points!.map((id) => p.get(id)!);
|
||||
expect(mid).toEqual([10, 10]);
|
||||
expect(inH).toEqual([10 - 20 / 6, 10].map((v) => Math.round(v * 1e4) / 1e4));
|
||||
expect(isSmooth(mid, inH, outH)).toBe(true);
|
||||
});
|
||||
|
||||
it("a dragged anchor has the symmetric handles of the drag; a closed path returns to its first anchor", () => {
|
||||
const poles = penPoles([[0, 0], [10, 0]], [[2, 3], null], false);
|
||||
expect(poles[1]).toEqual([2, 3]);
|
||||
const made = addPenSpline(emptyDoc(), [{ spot: { x: 0, y: 0 }, handle: [0, 4] }, { spot: { x: 10, y: 0 } }, { spot: { x: 5, y: 8 } }], true, opts, at)!;
|
||||
const spline = made.doc.entities[0];
|
||||
const ids = spline.control_points!;
|
||||
expect(ids).toHaveLength(10); // three spans
|
||||
expect(ids[0]).toBe(ids[9]);
|
||||
expect(spline.multiplicities).toEqual([4, 3, 3, 4]);
|
||||
const p = new Map(made.doc.points.map((q) => [q.id, [q.x, q.y]]));
|
||||
expect(p.get(ids[1])).toEqual([0, 4]); // the out-handle of the first anchor
|
||||
expect(p.get(ids[8])).toEqual([0, -4]); // and its in-handle, at the end of the closing span
|
||||
expect(addPenSpline(emptyDoc(), [{ spot: { x: 0, y: 0 } }], false, opts, at)).toBeNull();
|
||||
});
|
||||
|
||||
it("the drawn path passes through the anchors", () => {
|
||||
const path = bezierPath([[0, 0], [0, 5], [10, 5], [10, 0], [10, -5], [20, -5], [20, 0]], 8);
|
||||
expect(path[0]).toEqual([0, 0]);
|
||||
expect(path[8]).toEqual([10, 0]);
|
||||
expect(path[16]).toEqual([20, 0]);
|
||||
});
|
||||
});
|
||||
|
||||
function twoSpans(): SketchDoc {
|
||||
return addPenSpline(emptyDoc(), [{ spot: { x: 0, y: 0 } }, { spot: { x: 10, y: 10 } }, { spot: { x: 20, y: 0 } }], false, opts, at)!.doc;
|
||||
}
|
||||
|
||||
describe("anchors and handles of a spline", () => {
|
||||
it("each point knows its role; only the picked spline shows its handles", () => {
|
||||
const doc = twoSpans();
|
||||
const ids = doc.entities[0].control_points!;
|
||||
const roles = anchorRoles(doc);
|
||||
expect(roles.get(ids[3])).toMatchObject({ kind: "anchor", handles: [ids[2], ids[4]], end: false });
|
||||
expect(roles.get(ids[0])).toMatchObject({ kind: "anchor", handles: [ids[1]], end: true });
|
||||
expect(roles.get(ids[2])).toMatchObject({ kind: "handle", anchor: ids[3], other: ids[4] });
|
||||
expect(roles.get(ids[1])).toMatchObject({ kind: "handle", anchor: ids[0], other: undefined });
|
||||
expect([...handlePoints(roles)].sort()).toEqual([ids[1], ids[2], ids[4], ids[5]].sort());
|
||||
expect(shownHandles(doc, []).size).toBe(0);
|
||||
expect(shownHandles(doc, [doc.entities[0].id]).size).toBe(4);
|
||||
expect(shownHandles(doc, [ids[3]]).size).toBe(4); // an anchor of it
|
||||
});
|
||||
|
||||
it("a control-point B-spline (an old file, or a single span with uniform knots) is told apart", () => {
|
||||
expect(isAnchorSpline({ id: "s", kind: "bspline", degree: 3, control_points: ["a", "b", "c", "d"] })).toBe(true);
|
||||
expect(isAnchorSpline({ id: "s", kind: "bspline", degree: 3, control_points: ["a", "b", "c", "d", "e"] })).toBe(false);
|
||||
expect(isAnchorSpline({ id: "s", kind: "bspline", degree: 2, control_points: ["a", "b", "c"] })).toBe(false);
|
||||
expect(isAnchorSpline({ id: "s", kind: "bspline", degree: 3, control_points: Array(7).fill("p"), knots: [0, 0.5, 1], multiplicities: [4, 3, 4] })).toBe(true);
|
||||
expect(isAnchorSpline({ id: "s", kind: "bspline", degree: 3, control_points: Array(7).fill("p"), knots: [0, 0.3, 0.6, 1], multiplicities: [4, 1, 2, 4] })).toBe(false);
|
||||
});
|
||||
|
||||
it("dragging a handle of a smooth anchor turns the opposite handle, which keeps its own length", () => {
|
||||
expect(mirrorHandle([0, 0], [3, 4], 10)).toEqual([-6, -8]);
|
||||
expect(mirrorHandle([0, 0], [0, 0], 10)).toBeNull();
|
||||
expect(isSmooth([0, 0], [-1, 0], [5, 0])).toBe(true);
|
||||
expect(isSmooth([0, 0], [-1, 0], [5, 1])).toBe(false);
|
||||
});
|
||||
|
||||
it("S smooths a corner: both handles on one line, each keeping its length", () => {
|
||||
const doc = twoSpans();
|
||||
const ids = doc.entities[0].control_points!;
|
||||
const pts = new Map(doc.points.map((p) => [p.id, [p.x, p.y] as [number, number]]));
|
||||
pts.set(ids[2], [10, 15]); // a corner: the in-handle straight above the anchor
|
||||
pts.set(ids[4], [15, 10]); // the out-handle to the right
|
||||
const moved = smoothAnchors(doc, [ids[3]], pts);
|
||||
expect(isSmooth([10, 10], moved[ids[2]], moved[ids[4]])).toBe(true);
|
||||
expect(Math.hypot(moved[ids[2]][0] - 10, moved[ids[2]][1] - 10)).toBeCloseTo(5, 3);
|
||||
expect(smoothAnchors(doc, [ids[0]], pts)).toEqual({}); // an end anchor has one handle
|
||||
});
|
||||
});
|
||||
|
||||
describe("anchor edits are SDK requests; a wire sketch chooses any profile", () => {
|
||||
it("requests name the spline and the place or the anchor", () => {
|
||||
const doc = twoSpans();
|
||||
expect(insertAnchorRequest(doc, "s1", [4, 5])).toEqual({ sketch: doc, op: "insert_spline_anchor", args: { spline: "s1", at: [4, 5] } });
|
||||
expect(removeAnchorRequest(doc, "s1", "p4").args).toEqual({ spline: "s1", anchor: "p4" });
|
||||
expect(convertSplineRequest(doc, "s1").op).toBe("convert_spline_to_anchors");
|
||||
});
|
||||
|
||||
it("the output is kept only when it is a wire; open chains are wire profiles", () => {
|
||||
expect(normalizeDoc({ output: "wire" }).output).toBe("wire");
|
||||
expect("output" in normalizeDoc({ output: "face" })).toBe(false);
|
||||
const solve = { profiles: [{ index: 0, id: "l0", kind: "edge_chain", closed: false, entity_ids: ["l1", "l0"], reversed: [false, false] }] } as unknown as SolveResult;
|
||||
expect(wireProfiles(solve)).toEqual([{ index: 0, key: "l0+l1", closed: false, entities: ["l1", "l0"] }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
/** B-splines in anchor form, as a pen tool draws and edits them. A spline in anchor form is the SDK's cubic B-spline whose
|
||||
* inner knots have multiplicity 3: control points [A0, out0, in1, A1, out1, in2, A2, ...], every span a cubic Bezier from one
|
||||
* anchor (on the curve) to the next, each anchor with an in-handle and an out-handle. Anchors and handles are plain sketch
|
||||
* points, so moving them is document editing; inserting and removing an anchor are SDK edits (`insert_spline_anchor_rsketch`,
|
||||
* `remove_spline_anchor_rsketch`, see sketch-edit.ts). This file reads the structure, builds a drawn path and keeps a smooth
|
||||
* anchor smooth while one of its handles is dragged. A B-spline in another form (control points, an old file) has no anchors
|
||||
* here: it shows its control polygon and offers `convert_spline_to_anchors_rsketch`. */
|
||||
|
||||
import { ensurePoint, nextId, type DrawOptions, type SEntity, type SketchDoc, type Spot } from "@/lib/sketch";
|
||||
|
||||
type P = [number, number];
|
||||
|
||||
/** Is the B-spline in anchor form (degree 3, clamped, every inner knot of multiplicity 3)? */
|
||||
export function isAnchorSpline(e: SEntity): boolean {
|
||||
if (e.kind !== "bspline" || e.degree !== 3) return false;
|
||||
const poles = e.control_points ?? [];
|
||||
const mults = e.multiplicities;
|
||||
if (!mults) return poles.length === 4; // one span: the uniform knots the document leaves out
|
||||
if (mults.length < 2 || mults[0] !== 4 || mults[mults.length - 1] !== 4 || mults.slice(1, -1).some((m) => m !== 3)) return false;
|
||||
return poles.length === 3 * (mults.length - 1) + 1;
|
||||
}
|
||||
|
||||
/** Where a point sits in an anchor-form spline: an anchor (with its handles) or a handle (with its anchor and the opposite
|
||||
* handle of that anchor). `end` marks the first and last anchor (they have one handle, unless the spline is closed). */
|
||||
export type AnchorRole = { spline: string; kind: "anchor" | "handle"; index: number; anchor: string; handles: string[]; other?: string; end: boolean };
|
||||
|
||||
/** The role of every point of every anchor-form spline, by point id (a point two splines share keeps the first role). */
|
||||
export function anchorRoles(doc: SketchDoc): Map<string, AnchorRole> {
|
||||
const out = new Map<string, AnchorRole>();
|
||||
for (const e of doc.entities) {
|
||||
if (!isAnchorSpline(e)) continue;
|
||||
const poles = e.control_points!;
|
||||
const last = poles.length - 1;
|
||||
const closed = poles[0] === poles[last];
|
||||
const handlesOf = (i: number): string[] => {
|
||||
const list: string[] = [];
|
||||
if (i > 0) list.push(poles[i - 1]);
|
||||
else if (closed) list.push(poles[last - 1]);
|
||||
if (i < last) list.push(poles[i + 1]);
|
||||
else if (closed) list.push(poles[1]);
|
||||
return list;
|
||||
};
|
||||
for (let i = 0; i <= last; i += 3) {
|
||||
if (!out.has(poles[i])) out.set(poles[i], { spline: e.id, kind: "anchor", index: i, anchor: poles[i], handles: handlesOf(i), end: !closed && (i === 0 || i === last) });
|
||||
}
|
||||
for (let i = 0; i <= last; i++) {
|
||||
if (i % 3 === 0 || out.has(poles[i])) continue;
|
||||
const anchorIndex = i % 3 === 1 ? i - 1 : i + 1;
|
||||
const sibling = i % 3 === 1 ? (anchorIndex > 0 ? anchorIndex - 1 : closed ? last - 1 : -1) : anchorIndex < last ? anchorIndex + 1 : closed ? 1 : -1;
|
||||
out.set(poles[i], { spline: e.id, kind: "handle", index: i, anchor: poles[anchorIndex], handles: [], other: sibling >= 0 ? poles[sibling] : undefined, end: false });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The handles to show: those of the anchor-form splines that are picked (the spline itself, or one of its points). */
|
||||
export function shownHandles(doc: SketchDoc, selection: readonly string[], roles: Map<string, AnchorRole> = anchorRoles(doc)): Set<string> {
|
||||
const active = new Set<string>();
|
||||
for (const id of selection) {
|
||||
const role = roles.get(id);
|
||||
if (role) active.add(role.spline);
|
||||
else if (doc.entities.some((e) => e.id === id && isAnchorSpline(e))) active.add(id);
|
||||
}
|
||||
const out = new Set<string>();
|
||||
for (const [id, role] of roles) if (role.kind === "handle" && active.has(role.spline)) out.add(id);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Every handle point of every anchor-form spline (hidden ones are not picked or snapped to). */
|
||||
export function handlePoints(roles: Map<string, AnchorRole>): Set<string> {
|
||||
return new Set([...roles].filter(([, r]) => r.kind === "handle").map(([id]) => id));
|
||||
}
|
||||
|
||||
// -- the drawn path -------------------------------------------------------------------------------------------------------
|
||||
|
||||
/** Points along a chain of cubic Bezier spans given by their control points [A0, out0, in1, A1, ...]. */
|
||||
export function bezierPath(poles: readonly P[], steps = 24): P[] {
|
||||
const out: P[] = [];
|
||||
for (let s = 0; s + 3 < poles.length; s += 3) {
|
||||
const [p0, p1, p2, p3] = [poles[s], poles[s + 1], poles[s + 2], poles[s + 3]];
|
||||
for (let k = s === 0 ? 0 : 1; k <= steps; k++) {
|
||||
const t = k / steps;
|
||||
const a = (1 - t) ** 3;
|
||||
const b = 3 * (1 - t) ** 2 * t;
|
||||
const c = 3 * (1 - t) * t * t;
|
||||
const d = t ** 3;
|
||||
out.push([a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// -- the pen tool ---------------------------------------------------------------------------------------------------------
|
||||
|
||||
/** An anchor of the pen draft: where it is and, when the click was dragged, its out-handle as an offset (the in-handle is the
|
||||
* mirror image). Without a drag the handles follow the neighbours (a smooth curve through the clicks). */
|
||||
export type PenNode = { spot: Spot; handle?: P | null };
|
||||
|
||||
/** The control points of a pen path through `at` (the anchors' positions): a node's own handle when it has one, else a third
|
||||
* of the way towards its neighbours along the line from the previous to the next anchor (Catmull-Rom tangents). */
|
||||
export function penPoles(at: readonly P[], handles: readonly (P | null | undefined)[], closed: boolean): P[] {
|
||||
const n = at.length;
|
||||
const tangent = (i: number): P => {
|
||||
const own = handles[i];
|
||||
if (own) return own;
|
||||
const prev = i > 0 ? at[i - 1] : closed ? at[n - 1] : at[i];
|
||||
const next = i < n - 1 ? at[i + 1] : closed ? at[0] : at[i];
|
||||
return [(next[0] - prev[0]) / 6, (next[1] - prev[1]) / 6];
|
||||
};
|
||||
const poles: P[] = [];
|
||||
const spans = closed ? n : n - 1;
|
||||
for (let s = 0; s < spans; s++) {
|
||||
const a = at[s];
|
||||
const b = at[(s + 1) % n];
|
||||
const ta = tangent(s);
|
||||
const tb = tangent((s + 1) % n);
|
||||
if (s === 0) poles.push(a);
|
||||
poles.push([a[0] + ta[0], a[1] + ta[1]], [b[0] - tb[0], b[1] - tb[1]], b);
|
||||
}
|
||||
return poles;
|
||||
}
|
||||
|
||||
const round = (v: number) => Math.round(v * 1e4) / 1e4;
|
||||
|
||||
/** The anchor-form B-spline of a pen draft: a point per anchor (existing points are reused) and per handle, knots 0..n with
|
||||
* the inner ones of multiplicity 3. `closed`: the last span returns to the first anchor. */
|
||||
export function addPenSpline(doc: SketchDoc, nodes: readonly PenNode[], closed: boolean, opts: DrawOptions, at: (spot: Spot) => P): { doc: SketchDoc; id: string } | null {
|
||||
if (nodes.length < 2) return null;
|
||||
const positions = nodes.map((node) => at(node.spot));
|
||||
const poles = penPoles(positions, nodes.map((node) => node.handle), closed);
|
||||
let next = doc;
|
||||
const anchors: string[] = [];
|
||||
for (const node of nodes) {
|
||||
const made = ensurePoint(next, node.spot);
|
||||
next = made.doc;
|
||||
anchors.push(made.id);
|
||||
}
|
||||
if (new Set(anchors).size !== anchors.length) return null; // two clicks on one point
|
||||
const ids: string[] = [];
|
||||
for (let i = 0; i < poles.length; i++) {
|
||||
if (i % 3 === 0) {
|
||||
ids.push(anchors[(i / 3) % anchors.length]);
|
||||
continue;
|
||||
}
|
||||
const id = nextId("p", next);
|
||||
next = { ...next, points: [...next.points, { id, x: round(poles[i][0]), y: round(poles[i][1]) }] };
|
||||
ids.push(id);
|
||||
}
|
||||
const spans = (ids.length - 1) / 3;
|
||||
const id = nextId("s", next);
|
||||
const entity: SEntity = {
|
||||
id,
|
||||
kind: "bspline",
|
||||
start: ids[0],
|
||||
end: ids[ids.length - 1],
|
||||
control_points: ids,
|
||||
degree: 3,
|
||||
knots: Array.from({ length: spans + 1 }, (_, i) => i),
|
||||
multiplicities: Array.from({ length: spans + 1 }, (_, i) => (i === 0 || i === spans ? 4 : 3)),
|
||||
construction: opts.construction,
|
||||
};
|
||||
return { doc: { ...next, entities: [...next.entities, entity] }, id };
|
||||
}
|
||||
|
||||
// -- smooth and corner anchors ----------------------------------------------------------------------------------------------
|
||||
|
||||
/** Do the two handles of an anchor point in opposite directions (within `deg` degrees)? A zero-length handle counts as smooth. */
|
||||
export function isSmooth(anchor: P, a: P, b: P, deg = 2): boolean {
|
||||
const ax = a[0] - anchor[0];
|
||||
const ay = a[1] - anchor[1];
|
||||
const bx = b[0] - anchor[0];
|
||||
const by = b[1] - anchor[1];
|
||||
const la = Math.hypot(ax, ay);
|
||||
const lb = Math.hypot(bx, by);
|
||||
if (la < 1e-9 || lb < 1e-9) return true;
|
||||
return (ax * bx + ay * by) / (la * lb) <= -Math.cos((deg * Math.PI) / 180);
|
||||
}
|
||||
|
||||
/** Where the opposite handle goes when `handle` is dragged at a smooth anchor: on the other side of the anchor, keeping its own
|
||||
* length (so the two sides keep their own pull). Null when the dragged handle sits on the anchor (no direction). */
|
||||
export function mirrorHandle(anchor: P, handle: P, length: number): P | null {
|
||||
const dx = handle[0] - anchor[0];
|
||||
const dy = handle[1] - anchor[1];
|
||||
const l = Math.hypot(dx, dy);
|
||||
if (l < 1e-9) return null;
|
||||
return [anchor[0] - (dx / l) * length, anchor[1] - (dy / l) * length];
|
||||
}
|
||||
|
||||
/** Make anchors smooth: each one's two handles turn to the mean direction (opposite each other), keeping their lengths. Returns
|
||||
* the new positions of the handles that turn (sketch coordinates). */
|
||||
export function smoothAnchors(doc: SketchDoc, anchors: readonly string[], pts: ReadonlyMap<string, P>, roles: Map<string, AnchorRole> = anchorRoles(doc)): Record<string, P> {
|
||||
const out: Record<string, P> = {};
|
||||
for (const id of anchors) {
|
||||
const role = roles.get(id);
|
||||
if (!role || role.kind !== "anchor" || role.handles.length !== 2) continue;
|
||||
const at = pts.get(id);
|
||||
const a = pts.get(role.handles[0]);
|
||||
const b = pts.get(role.handles[1]);
|
||||
if (!at || !a || !b) continue;
|
||||
const la = Math.hypot(a[0] - at[0], a[1] - at[1]);
|
||||
const lb = Math.hypot(b[0] - at[0], b[1] - at[1]);
|
||||
if (la < 1e-9 || lb < 1e-9) continue;
|
||||
// the direction from the in-handle through the anchor to the out-handle, averaged over both sides
|
||||
let dx = (at[0] - a[0]) / la + (b[0] - at[0]) / lb;
|
||||
let dy = (at[1] - a[1]) / la + (b[1] - at[1]) / lb;
|
||||
const l = Math.hypot(dx, dy);
|
||||
if (l < 1e-9) continue; // the handles lie on top of each other: no direction to agree on
|
||||
dx /= l;
|
||||
dy /= l;
|
||||
out[role.handles[0]] = [round(at[0] - dx * la), round(at[1] - dy * la)];
|
||||
out[role.handles[1]] = [round(at[0] + dx * lb), round(at[1] + dy * lb)];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
import { entityMap, normalizeDoc, type Choice, type Loop, type SketchDoc } from "@/lib/sketch";
|
||||
import type { FeatureRow } from "@/lib/features";
|
||||
|
||||
export type EditOp = "trim" | "extend" | "fillet_corner" | "chamfer_corner" | "project";
|
||||
export type EditOp = "trim" | "extend" | "fillet_corner" | "chamfer_corner" | "project" | "insert_spline_anchor" | "remove_spline_anchor" | "convert_spline_to_anchors";
|
||||
export type End = "start" | "end";
|
||||
|
||||
export type TrimArgs = { entity: string; at: [number, number] };
|
||||
@@ -14,7 +14,10 @@ export type ExtendArgs = { entity: string; end: End };
|
||||
export type FilletArgs = { a: string; b: string; radius: number };
|
||||
export type ChamferArgs = { a: string; b: string; distance: number };
|
||||
export type ProjectArgs = { from_sketch: string };
|
||||
export type EditArgs = TrimArgs | ExtendArgs | FilletArgs | ChamferArgs | ProjectArgs;
|
||||
export type InsertAnchorArgs = { spline: string; at: [number, number] };
|
||||
export type RemoveAnchorArgs = { spline: string; anchor: string };
|
||||
export type ConvertSplineArgs = { spline: string };
|
||||
export type EditArgs = TrimArgs | ExtendArgs | FilletArgs | ChamferArgs | ProjectArgs | InsertAnchorArgs | RemoveAnchorArgs | ConvertSplineArgs;
|
||||
|
||||
/** The server's answer to a sketch edit (the fields the editor uses). */
|
||||
export type EditResponse = {
|
||||
@@ -52,6 +55,17 @@ export function extendRequest(doc: SketchDoc, pts: ReadonlyMap<string, [number,
|
||||
return end ? { sketch: doc, op: "extend", args: { entity, end } } : null;
|
||||
}
|
||||
|
||||
// -- anchors of a B-spline (insert_spline_anchor / remove_spline_anchor / convert_spline_to_anchors) ----------------------
|
||||
|
||||
/** Insert an anchor where the click is on an anchor-form spline: the SDK splits the span there, the curve stays. */
|
||||
export const insertAnchorRequest = (doc: SketchDoc, spline: string, at: readonly [number, number]): EditRequest => ({ sketch: doc, op: "insert_spline_anchor", args: { spline, at: [at[0], at[1]] } });
|
||||
|
||||
/** Remove an inner anchor (and its handles) of an anchor-form spline: the SDK merges the two spans beside it. */
|
||||
export const removeAnchorRequest = (doc: SketchDoc, spline: string, anchor: string): EditRequest => ({ sketch: doc, op: "remove_spline_anchor", args: { spline, anchor } });
|
||||
|
||||
/** Write a control-point B-spline in anchor form (the SDK keeps the curve). */
|
||||
export const convertSplineRequest = (doc: SketchDoc, spline: string): EditRequest => ({ sketch: doc, op: "convert_spline_to_anchors", args: { spline } });
|
||||
|
||||
// -- corners (fillet_corner / chamfer_corner) ---------------------------------------------------------------------------
|
||||
|
||||
/** A corner: a point shared by exactly two lines (`a` and `b` are the line ids). */
|
||||
|
||||
@@ -39,8 +39,13 @@ export type SketchDoc = {
|
||||
profile: number;
|
||||
inner: number[];
|
||||
fully_constrained: boolean;
|
||||
/** What the sketch cell makes of its profile: a face (the default, left out) or a wire (a closed loop or an open chain:
|
||||
* a sweep path, a loft section). */
|
||||
output?: SketchOutput;
|
||||
};
|
||||
|
||||
export type SketchOutput = "face" | "wire";
|
||||
|
||||
export type Diagnostic = { constraint_id: string | null; severity: string; code: string; message: string; residual: number | null };
|
||||
/** One profile of the SDK's ``inspect_sketch_rsketchprofiles``: a free circle, or a loop / chain of edges in walking order. */
|
||||
export type ServerProfile = { index: number; id: string; kind: string; closed: boolean; entity_ids: string[]; reversed: boolean[] };
|
||||
@@ -115,9 +120,18 @@ export function normalizeDoc(raw: unknown): SketchDoc {
|
||||
profile: Number.isInteger(source.profile) && (source.profile as number) >= 0 ? (source.profile as number) : 0,
|
||||
inner: list<number>(source.inner).filter((i) => Number.isInteger(i) && i >= 0),
|
||||
fully_constrained: Boolean(source.fully_constrained),
|
||||
...(source.output === "wire" ? { output: "wire" as const } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** A profile the SDK offers, as a wire can be made of it: closed loops and open chains alike, identified across edits by the
|
||||
* sorted ids of its entities (the same key a loop has). */
|
||||
export type WireProfile = { index: number; key: string; closed: boolean; entities: string[] };
|
||||
|
||||
export function wireProfiles(solve: SolveResult | null): WireProfile[] {
|
||||
return (solve?.profiles ?? []).filter((p) => p.entity_ids.length > 0).map((p) => ({ index: p.index, key: [...p.entity_ids].sort().join("+"), closed: p.closed, entities: p.entity_ids }));
|
||||
}
|
||||
|
||||
/** The JSON the server takes (a plain deep copy; the round trip normalizeDoc(docToJson(d)) is the identity). */
|
||||
export function docToJson(doc: SketchDoc): SketchDoc {
|
||||
return JSON.parse(JSON.stringify(doc)) as SketchDoc;
|
||||
@@ -671,11 +685,13 @@ export function entityDistance(doc: SketchDoc, e: SEntity, pos: readonly [number
|
||||
|
||||
export type Hit = { kind: "point" | "entity"; id: string };
|
||||
|
||||
/** What is under a position: points first, then the nearest entity within `tol` (world units). */
|
||||
export function hitTest(doc: SketchDoc, solve: SolveResult | null, pos: readonly [number, number], tol: number): Hit | null {
|
||||
/** What is under a position: points first (except those in `skip`: handles that are not shown), then the nearest entity
|
||||
* within `tol` (world units). */
|
||||
export function hitTest(doc: SketchDoc, solve: SolveResult | null, pos: readonly [number, number], tol: number, skip?: ReadonlySet<string>): Hit | null {
|
||||
const pts = solvedPoints(doc, solve);
|
||||
let best: { id: string; d: number } | null = null;
|
||||
for (const [id, p] of pts) {
|
||||
if (skip?.has(id)) continue;
|
||||
const d = Math.hypot(p[0] - pos[0], p[1] - pos[1]);
|
||||
if (d <= tol && (!best || d < best.d)) best = { id, d };
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
LatestSolver,
|
||||
addArc,
|
||||
addSpline,
|
||||
addCircle,
|
||||
addConstraint,
|
||||
addLine,
|
||||
@@ -43,8 +42,10 @@ import {
|
||||
type Hit,
|
||||
type SConstraint,
|
||||
type SketchDoc,
|
||||
type SketchOutput,
|
||||
type SolveResult,
|
||||
type Spot,
|
||||
wireProfiles,
|
||||
} from "@/lib/sketch";
|
||||
import {
|
||||
applyEdit,
|
||||
@@ -62,17 +63,20 @@ import {
|
||||
pushHistory,
|
||||
remapChoice,
|
||||
trimRequest,
|
||||
convertSplineRequest,
|
||||
insertAnchorRequest,
|
||||
removeAnchorRequest,
|
||||
type Corner,
|
||||
type CornerOp,
|
||||
type EditRequest,
|
||||
type End,
|
||||
} from "@/lib/sketch-edit";
|
||||
import { typedFields, typedTarget, type TypedDims } from "@/lib/sketch-typed";
|
||||
import { addPenSpline, anchorRoles, handlePoints, isAnchorSpline, isSmooth, mirrorHandle, shownHandles, smoothAnchors } from "@/lib/sketch-anchors";
|
||||
|
||||
/** How near the pointer (screen pixels) must be to a point or a curve to snap to it or pick it. */
|
||||
const PICK_PX = 16;
|
||||
const DRAW_TOOLS = new Set(["point", "line", "circle", "arc", "spline"]);
|
||||
const FIRST = "\u0000first"; // a spline's closing click: "the first control point"
|
||||
|
||||
export type Tool = "select" | "point" | "line" | "circle" | "arc" | "spline" | "delete" | "trim" | "extend" | "fillet" | "chamfer";
|
||||
/** The corner value box (fillet radius / chamfer distance) open at a corner. */
|
||||
@@ -80,8 +84,20 @@ export type CornerBox = { op: CornerOp; corner: Corner; text: string; bad: boole
|
||||
/** What the last SDK edit (trim, extend) said: its notes, or the error (which names ids). Shown in the status area. */
|
||||
export type EditNote = { tone: "ok" | "fail"; text: string };
|
||||
const EDIT_TOOLS: ReadonlySet<Tool> = new Set<Tool>(["trim", "extend", "fillet", "chamfer"]);
|
||||
export type Draft = { tool: "line"; from: Spot } | { tool: "circle"; center: Spot } | { tool: "arc"; center: Spot; start?: Spot } | { tool: "spline"; points: Spot[] } | null;
|
||||
export type Drag = { ids: string[]; origin: Record<string, [number, number]>; start: [number, number]; positions: Record<string, [number, number]>; releasing?: boolean };
|
||||
/** The spline draft is a pen path: its anchors and, for each, the out-handle a drag pulled out (an offset; null: none). */
|
||||
export type SplineDraft = { tool: "spline"; points: Spot[]; handles: ([number, number] | null)[] };
|
||||
export type Draft = { tool: "line"; from: Spot } | { tool: "circle"; center: Spot } | { tool: "arc"; center: Spot; start?: Spot } | SplineDraft | null;
|
||||
/** A drag of points. `lead` is the point that snaps (an anchor; its handles follow it); `mirror` keeps a smooth anchor smooth
|
||||
* while one of its handles is dragged: the opposite handle turns with it and keeps its own length. */
|
||||
export type Drag = {
|
||||
ids: string[];
|
||||
origin: Record<string, [number, number]>;
|
||||
start: [number, number];
|
||||
positions: Record<string, [number, number]>;
|
||||
releasing?: boolean;
|
||||
lead?: string;
|
||||
mirror?: { other: string; anchor: [number, number]; length: number };
|
||||
};
|
||||
export type ValueBox = { kind: ConstraintKind; targets: string[]; constraintId?: string; text: string; bad: boolean };
|
||||
|
||||
/** One pointer event in the sketch's terms: its screen position (px, local to the overlay), the plane position under
|
||||
@@ -127,6 +143,11 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
const history = useRef<SketchDoc[]>([]);
|
||||
const future = useRef<SketchDoc[]>([]);
|
||||
const press = useRef<{ hit: Hit; sx: number; sy: number; world: [number, number]; shift: boolean; wasSelected: boolean } | null>(null);
|
||||
/** The press of the pen tool: the anchor it placed (or the first one, when it closes the path), where it is, and where the
|
||||
* press began on screen (a drag from there pulls out the anchor's handles). */
|
||||
const pen = useRef<{ index: number; at: [number, number]; sx: number; sy: number; closing: boolean } | null>(null);
|
||||
/** The last click of the select tool (a second one at the same place soon after is a double-click). */
|
||||
const lastClick = useRef<{ t: number; sx: number; sy: number } | null>(null);
|
||||
const choiceReady = useRef(initial.points.length === 0);
|
||||
|
||||
// -- document changes (history) --------------------------------------------------------------------------------------
|
||||
@@ -219,23 +240,58 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [loopKey, result === null]);
|
||||
useEffect(() => {
|
||||
if (drag || !result) return;
|
||||
const outer = loops.find((l) => l.key === choice.outer);
|
||||
if (drag || !result || docRef.current.output === "wire") return;
|
||||
const { profile, inner } = choiceToIndices(choice, loops);
|
||||
const d = docRef.current;
|
||||
if (d.profile !== profile || d.inner.length !== inner.length || d.inner.some((v, i) => v !== inner[i])) commit({ ...d, profile, inner }, false);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [choice, loopKey, drag, doc.profile, doc.inner]);
|
||||
}, [choice, loopKey, drag, doc.profile, doc.inner, doc.output]);
|
||||
|
||||
// A wire is made of one profile, a closed loop or an open chain, followed across edits by its key like a loop. Unchosen,
|
||||
// it is the first open chain (a path is what a wire is usually for), else the first profile.
|
||||
const wires = useMemo(() => wireProfiles(result), [result]);
|
||||
const wireList = wires.map((w) => `${w.key}:${w.index}`).join("|");
|
||||
const [wireKey, setWireKey] = useState<string | null>(null);
|
||||
const wireReady = useRef(false);
|
||||
useEffect(() => {
|
||||
if (drag || !result || doc.output !== "wire") return;
|
||||
let key = wireKey;
|
||||
if (!wireReady.current) {
|
||||
wireReady.current = true;
|
||||
key = wires.find((w) => w.index === docRef.current.profile)?.key ?? null;
|
||||
}
|
||||
if (!key || !wires.some((w) => w.key === key)) key = (wires.find((w) => !w.closed) ?? wires[0])?.key ?? null;
|
||||
if (key !== wireKey) setWireKey(key);
|
||||
const index = wires.find((w) => w.key === key)?.index ?? 0;
|
||||
const d = docRef.current;
|
||||
if (d.profile !== index || d.inner.length) commit({ ...d, profile: index, inner: [] }, false);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [wireList, doc.output, drag, wireKey, doc.profile]);
|
||||
const wire = doc.output === "wire" ? (wires.find((w) => w.key === wireKey) ?? null) : null;
|
||||
/** Face or wire: what the sketch cell makes (switching back to a face picks the chosen loop again). */
|
||||
const setOutput = useCallback((output: SketchOutput) => {
|
||||
const d = docRef.current;
|
||||
if ((d.output ?? "face") === output) return;
|
||||
const { output: _old, ...rest } = d;
|
||||
commit(output === "wire" ? { ...rest, output: "wire" } : rest);
|
||||
}, [commit]);
|
||||
|
||||
// -- anchors and handles of B-splines in anchor form ---------------------------------------------------------------------
|
||||
const roles = useMemo(() => anchorRoles(doc), [doc]);
|
||||
/** The handles drawn and picked: those of the anchor-form splines in the selection; the others are hidden. */
|
||||
const shown = useMemo(() => shownHandles(doc, selection, roles), [doc, selection, roles]);
|
||||
const hidden = useMemo(() => new Set([...handlePoints(roles)].filter((id) => !shown.has(id))), [roles, shown]);
|
||||
|
||||
// -- snapping -----------------------------------------------------------------------------------------------------------------
|
||||
/** Where curves of the sketch cross and no point is yet (the SDK's answer for the last solve): shown, and snapped to. */
|
||||
const crossings = useMemo(() => (result?.crossings ?? []).map((c) => c.at), [result]);
|
||||
const snapTargets = useMemo(() => {
|
||||
const all = new Map(pts);
|
||||
for (const id of handlePoints(roles)) all.delete(id); // a handle is not a place to draw to
|
||||
modelPoints.forEach((p, i) => all.set(`m:${i}`, p));
|
||||
crossings.forEach((p, i) => all.set(`x:${i}`, p));
|
||||
return all;
|
||||
}, [pts, modelPoints, crossings]);
|
||||
}, [pts, modelPoints, crossings, roles]);
|
||||
|
||||
const spotAt = useCallback(
|
||||
(world: [number, number], info: Pick<PointerInfo, "scale" | "alt">): Spot => {
|
||||
@@ -282,13 +338,6 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
setBox(null);
|
||||
}, [box, commit]);
|
||||
|
||||
const deleteSelection = useCallback(() => {
|
||||
if (!selection.length) return;
|
||||
commit(removeItems(docRef.current, selection));
|
||||
setSelection([]);
|
||||
setHover(null);
|
||||
}, [selection, commit]);
|
||||
|
||||
const toggleConstruction = useCallback(() => {
|
||||
const entities = selection.filter((id) => entityMap(docRef.current).has(id));
|
||||
if (entities.length) {
|
||||
@@ -318,7 +367,7 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
/** Send one edit to the server (which runs the SDK function) and adopt the document it returns: undoable as one step,
|
||||
* re-solved by the live solve, the created entities flashed. A failure is shown, never swallowed. */
|
||||
const runEdit = useCallback(
|
||||
async (request: EditRequest) => {
|
||||
async (request: EditRequest, select?: (next: SketchDoc, created: string[]) => string[]) => {
|
||||
setEditBusy(true);
|
||||
setEditNote(null);
|
||||
try {
|
||||
@@ -328,7 +377,7 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
// the live solve writes the indices back.
|
||||
setChoice(remapChoice(loopsRef.current, choiceRef.current, findLoops(next, resultRef.current)));
|
||||
commit(next);
|
||||
setSelection([]);
|
||||
setSelection(select ? select(next, created) : []);
|
||||
setHover(null);
|
||||
setHoverEnd(null);
|
||||
setCornerHover(null);
|
||||
@@ -355,6 +404,67 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
);
|
||||
useEffect(() => () => void (flashTimer.current !== null && window.clearTimeout(flashTimer.current)), []);
|
||||
|
||||
/** Delete items. The anchor of a spline in anchor form is not deleted with its spline: the SDK removes it and merges the
|
||||
* spans beside it (one edit per anchor). An end anchor or a handle stays, with a word on what to do instead. */
|
||||
const deleteItems = useCallback(
|
||||
async (ids: readonly string[]) => {
|
||||
const now = anchorRoles(docRef.current);
|
||||
const anchors = ids.filter((id) => now.get(id)?.kind === "anchor" && !now.get(id)?.end);
|
||||
const kept = ids.filter((id) => now.has(id) && !anchors.includes(id));
|
||||
const rest = ids.filter((id) => !now.has(id));
|
||||
if (rest.length) commit(removeItems(docRef.current, rest));
|
||||
setSelection([]);
|
||||
setHover(null);
|
||||
if (kept.length) {
|
||||
const role = now.get(kept[0])!;
|
||||
setEditNote({
|
||||
tone: "fail",
|
||||
text:
|
||||
role.kind === "handle"
|
||||
? `${kept[0]} is a handle of ${role.spline}: a handle is not deleted (drag it, or remove its anchor ${role.anchor})`
|
||||
: `${kept[0]} is an end of ${role.spline}: an end anchor cannot be removed (trim the spline, or select the curve to delete it)`,
|
||||
});
|
||||
}
|
||||
for (const id of anchors) {
|
||||
const role = anchorRoles(docRef.current).get(id);
|
||||
if (role?.kind === "anchor") await runEdit(removeAnchorRequest(docRef.current, role.spline, id), () => [role.spline]);
|
||||
}
|
||||
},
|
||||
[commit, runEdit],
|
||||
);
|
||||
const deleteSelection = useCallback(() => {
|
||||
if (selection.length) void deleteItems(selection);
|
||||
}, [selection, deleteItems]);
|
||||
|
||||
/** Insert an anchor on an anchor-form spline where it was clicked (the SDK splits the span; the curve stays): the new anchor
|
||||
* is selected, so its handles show. */
|
||||
const insertAnchor = useCallback(
|
||||
(spline: string, at: [number, number]) =>
|
||||
void runEdit(insertAnchorRequest(docRef.current, spline, at), (next, created) => {
|
||||
const made = anchorRoles(next);
|
||||
const anchor = created.find((id) => made.get(id)?.kind === "anchor");
|
||||
return anchor ? [anchor] : [spline];
|
||||
}),
|
||||
[runEdit],
|
||||
);
|
||||
/** The selected B-spline that has control points rather than anchors (the one a convert would change), or null. */
|
||||
const convertTarget = useMemo(() => {
|
||||
const picked = doc.entities.filter((e) => e.kind === "bspline" && selection.includes(e.id));
|
||||
return picked.length === 1 && !isAnchorSpline(picked[0]) ? picked[0].id : null;
|
||||
}, [doc.entities, selection]);
|
||||
const convertSpline = useCallback((spline: string) => void runEdit(convertSplineRequest(docRef.current, spline), () => [spline]), [runEdit]);
|
||||
/** S: the selected anchors become smooth (their two handles turn into one line, each keeping its length). */
|
||||
const smoothSelection = useCallback(() => {
|
||||
const anchors = selection.filter((id) => roles.get(id)?.kind === "anchor");
|
||||
const moved = smoothAnchors(docRef.current, anchors, ptsRef.current, roles);
|
||||
if (!Object.keys(moved).length) {
|
||||
setEditNote({ tone: "fail", text: "smooth: select an anchor that has two handles (click a spline drawn with the spline tool, then one of its anchors)" });
|
||||
return;
|
||||
}
|
||||
const d = docRef.current;
|
||||
commit({ ...d, points: d.points.map((p) => (moved[p.id] ? { ...p, x: moved[p.id][0], y: moved[p.id][1] } : p)) });
|
||||
}, [selection, roles, commit]);
|
||||
|
||||
/** Open the value box of a corner (fillet radius / chamfer distance) with the offered default. */
|
||||
const openCorner = useCallback((op: CornerOp, corner: Corner) => {
|
||||
const value = defaultCornerValue(docRef.current, ptsRef.current, corner);
|
||||
@@ -431,19 +541,17 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
return;
|
||||
}
|
||||
if (tool === "spline") {
|
||||
const points = draft?.tool === "spline" ? draft.points : [];
|
||||
const path: SplineDraft = draft?.tool === "spline" ? draft : { tool: "spline", points: [], handles: [] };
|
||||
const near = (a: Spot) => (a.pointId !== undefined && a.pointId === spot.pointId) || Math.hypot(a.x - spot.x, a.y - spot.y) <= pickTolerance.current;
|
||||
if (points.length >= 3 && near(points[0])) {
|
||||
// back on the first control point: a closed spline (it starts and ends on one point)
|
||||
const first = points[0];
|
||||
finishSpline([...points, first.pointId ? first : { ...first, pointId: FIRST }]);
|
||||
if (path.points.length >= 2 && near(path.points[0])) {
|
||||
finishSpline(path, true); // back on the first anchor: a closed path (it starts and ends on one point)
|
||||
return;
|
||||
}
|
||||
if (points.length >= 2 && near(points[points.length - 1])) {
|
||||
finishSpline(points); // the last point clicked again (a double click): done
|
||||
if (path.points.length >= 2 && near(path.points[path.points.length - 1])) {
|
||||
finishSpline(path, false); // the last anchor clicked again (a double click): done
|
||||
return;
|
||||
}
|
||||
setDraft({ tool: "spline", points: [...points, spot] });
|
||||
setDraft({ tool: "spline", points: [...path.points, spot], handles: [...path.handles, null] });
|
||||
return;
|
||||
}
|
||||
if (tool === "arc") {
|
||||
@@ -466,15 +574,11 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
}
|
||||
}
|
||||
};
|
||||
/** Make the B-spline of the clicked control points (Enter, or a click back on the first point closes it). */
|
||||
const finishSpline = (points: Spot[]): void => {
|
||||
/** Make the anchor-form B-spline of the pen path (Enter, a second click on the last anchor; `closed`: back on the first). */
|
||||
const finishSpline = (path: SplineDraft, closed: boolean): void => {
|
||||
setDraft(null);
|
||||
// a closing click names the first spot with FIRST: it becomes that spot's point once the first point exists
|
||||
let doc = docRef.current;
|
||||
const first = ensurePoint(doc, points[0]);
|
||||
doc = first.doc;
|
||||
const spots = points.map((spot, i) => (i === 0 ? { ...spot, pointId: first.id } : spot.pointId === FIRST ? { ...spot, pointId: first.id } : spot));
|
||||
const made = addSpline(doc, spots, { auto, construction });
|
||||
const at = (spot: Spot): [number, number] => (spot.pointId ? (ptsRef.current.get(spot.pointId) ?? [spot.x, spot.y]) : [spot.x, spot.y]);
|
||||
const made = addPenSpline(docRef.current, path.points.map((spot, i) => ({ spot, handle: path.handles[i] })), closed, { auto, construction }, at);
|
||||
if (made) commit(made.doc);
|
||||
};
|
||||
/** Snap distance of the last press (sketch units): how near a click must be to a draft's point to mean it. */
|
||||
@@ -529,7 +633,7 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
if (tool === "fillet" || tool === "chamfer") {
|
||||
if (editBusy || cornerBox) return "handled";
|
||||
const op: CornerOp = tool === "fillet" ? "fillet_corner" : "chamfer_corner";
|
||||
const hit = hitTest(d, result, world, tol);
|
||||
const hit = hitTest(d, result, world, tol, hidden);
|
||||
if (!hit) return "handled";
|
||||
if (hit.kind === "point") {
|
||||
const corner = cornerAt(d, hit.id);
|
||||
@@ -556,12 +660,21 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
return "handled";
|
||||
}
|
||||
if (tool === "select" || tool === "delete") {
|
||||
const hit = hitTest(d, result, world, tol);
|
||||
const hit = hitTest(d, result, world, tol, hidden);
|
||||
if (tool === "delete") {
|
||||
if (hit) {
|
||||
commit(removeItems(d, [hit.id]));
|
||||
setHover(null);
|
||||
}
|
||||
if (hit) void deleteItems([hit.id]);
|
||||
return "handled";
|
||||
}
|
||||
// A double-click on a B-spline adds an anchor there (a spline with control points says how to get anchors).
|
||||
const now = performance.now();
|
||||
const before = lastClick.current;
|
||||
lastClick.current = { t: now, sx: info.sx, sy: info.sy };
|
||||
const spline = hit?.kind === "entity" ? d.entities.find((e) => e.id === hit.id && e.kind === "bspline") : undefined;
|
||||
if (spline && before && now - before.t < 400 && Math.hypot(info.sx - before.sx, info.sy - before.sy) < 6) {
|
||||
lastClick.current = null;
|
||||
if (editBusy) return "handled";
|
||||
if (isAnchorSpline(spline)) insertAnchor(spline.id, world);
|
||||
else setEditNote({ tone: "fail", text: `${spline.id} has control points, not anchors: convert it first (K, or the button by the curve; the shape stays)` });
|
||||
return "handled";
|
||||
}
|
||||
if (hit) {
|
||||
@@ -572,6 +685,11 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
return "press";
|
||||
}
|
||||
const loop = loopAt(loops, world);
|
||||
if (loop && d.output === "wire") {
|
||||
setWireKey(loop.key); // a closed loop as the wire
|
||||
setSelection([]);
|
||||
return "handled";
|
||||
}
|
||||
if (loop) {
|
||||
setChoice((c) => pickLoop(c, loop.key, shiftKey));
|
||||
if (!shiftKey) setSelection([]);
|
||||
@@ -580,6 +698,27 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
if (!shiftKey) setSelection([]);
|
||||
return "handled";
|
||||
}
|
||||
if (tool === "spline") {
|
||||
// The pen: a press places an anchor (or finishes / closes the path, as a click does); a drag from it pulls out handles.
|
||||
const spot = spotAt(world, info);
|
||||
const current = draftRef.current;
|
||||
const path: SplineDraft = current?.tool === "spline" ? current : { tool: "spline", points: [], handles: [] };
|
||||
const near = (a: Spot) => (a.pointId !== undefined && a.pointId === spot.pointId) || Math.hypot(a.x - spot.x, a.y - spot.y) <= tol;
|
||||
const at = (a: Spot): [number, number] => (a.pointId ? (pts.get(a.pointId) ?? [a.x, a.y]) : [a.x, a.y]);
|
||||
if (path.points.length >= 2 && near(path.points[0])) {
|
||||
pen.current = { index: 0, at: at(path.points[0]), sx: info.sx, sy: info.sy, closing: true };
|
||||
return "press";
|
||||
}
|
||||
if (path.points.length >= 2 && near(path.points[path.points.length - 1])) {
|
||||
finishSpline(path, false);
|
||||
return "handled";
|
||||
}
|
||||
const next: SplineDraft = { tool: "spline", points: [...path.points, spot], handles: [...path.handles, null] };
|
||||
draftRef.current = next; // a drag may move before the next render
|
||||
setDraft(next);
|
||||
pen.current = { index: path.points.length, at: at(spot), sx: info.sx, sy: info.sy, closing: false };
|
||||
return "press";
|
||||
}
|
||||
place(spotAt(world, info));
|
||||
return "handled";
|
||||
};
|
||||
@@ -595,19 +734,41 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
const p = press.current;
|
||||
if (Math.hypot(info.sx - p.sx, info.sy - p.sy) > 4 && !p.shift) {
|
||||
const d = docRef.current;
|
||||
const ids = dragPoints(d, p.hit.id);
|
||||
let ids = dragPoints(d, p.hit.id);
|
||||
const role = p.hit.kind === "point" ? roles.get(p.hit.id) : undefined;
|
||||
let lead: string | undefined;
|
||||
let mirror: Drag["mirror"];
|
||||
if (role?.kind === "anchor") {
|
||||
// an anchor carries its handles (a fixed handle stays)
|
||||
ids = [p.hit.id, ...role.handles.filter((h) => !isFixed(d, h))];
|
||||
lead = p.hit.id;
|
||||
} else if (role?.kind === "handle" && role.other && !isFixed(d, role.other)) {
|
||||
// a handle of a smooth anchor turns the opposite handle with it
|
||||
const a = pts.get(role.anchor);
|
||||
const h = pts.get(p.hit.id);
|
||||
const o = pts.get(role.other);
|
||||
if (a && h && o && isSmooth(a, h, o)) mirror = { other: role.other, anchor: a, length: Math.hypot(o[0] - a[0], o[1] - a[1]) };
|
||||
}
|
||||
if (ids.length && !ids.some((id) => isFixed(d, id))) {
|
||||
const origin: Record<string, [number, number]> = {};
|
||||
for (const id of ids) origin[id] = pts.get(id) ?? [0, 0];
|
||||
setDrag({ ids, origin, start: p.world, positions: origin });
|
||||
setDrag({ ids, origin, start: p.world, positions: origin, lead, mirror });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (drag && !drag.releasing) {
|
||||
const positions: Record<string, [number, number]> = {};
|
||||
if (drag.ids.length === 1) {
|
||||
if (drag.ids.length === 1 || drag.lead) {
|
||||
// the lead point snaps; the points it carries move by as much
|
||||
const lead = drag.lead ?? drag.ids[0];
|
||||
const s = snap(world, snapTargets, { grid: snapOn && !info.alt ? gridStep(info.scale) : null, tol: snapOn ? tol : 0, skip: new Set(drag.ids) });
|
||||
positions[drag.ids[0]] = [s.x, s.y];
|
||||
positions[lead] = [s.x, s.y];
|
||||
const dx = s.x - drag.origin[lead][0];
|
||||
const dy = s.y - drag.origin[lead][1];
|
||||
for (const id of drag.ids) if (id !== lead) positions[id] = [drag.origin[id][0] + dx, drag.origin[id][1] + dy];
|
||||
// Alt while dragging a handle breaks the anchor into a corner: the opposite handle stays where it was
|
||||
const turned = drag.mirror && !info.alt ? mirrorHandle(drag.mirror.anchor, positions[lead], drag.mirror.length) : null;
|
||||
if (drag.mirror && turned) positions[drag.mirror.other] = turned;
|
||||
} else {
|
||||
const dx = world[0] - drag.start[0];
|
||||
const dy = world[1] - drag.start[1];
|
||||
@@ -616,11 +777,23 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
setDrag({ ...drag, positions });
|
||||
return;
|
||||
}
|
||||
const path = draftRef.current;
|
||||
if (pen.current && path?.tool === "spline") {
|
||||
// pulling out the handles of the anchor just placed (or of the first anchor, when the press closes the path)
|
||||
const p = pen.current;
|
||||
if (Math.hypot(info.sx - p.sx, info.sy - p.sy) > 4) {
|
||||
const handles = [...path.handles];
|
||||
handles[p.index] = [world[0] - p.at[0], world[1] - p.at[1]];
|
||||
const next: SplineDraft = { ...path, handles };
|
||||
draftRef.current = next;
|
||||
setDraft(next);
|
||||
}
|
||||
}
|
||||
if (tool === "select") {
|
||||
setHover(hitTest(docRef.current, result, world, tol));
|
||||
setHover(hitTest(docRef.current, result, world, tol, hidden));
|
||||
setCursor({ x: world[0], y: world[1] });
|
||||
} else if (tool === "fillet" || tool === "chamfer") {
|
||||
const hit = cornerBox ? null : hitTest(docRef.current, result, world, tol);
|
||||
const hit = cornerBox ? null : hitTest(docRef.current, result, world, tol, hidden);
|
||||
setHover(hit);
|
||||
if (hit?.kind === "point") setCornerHover(cornerAt(docRef.current, hit.id));
|
||||
else if (hit && pendingLine && hit.id !== pendingLine) setCornerHover(cornerOfLines(docRef.current, pendingLine, hit.id));
|
||||
@@ -640,6 +813,12 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
const pointerUp = async () => {
|
||||
const p = press.current;
|
||||
press.current = null;
|
||||
const penPress = pen.current;
|
||||
pen.current = null;
|
||||
if (penPress?.closing && draftRef.current?.tool === "spline") {
|
||||
finishSpline(draftRef.current, true);
|
||||
return;
|
||||
}
|
||||
if (drag && !drag.releasing) {
|
||||
// Final solve with the temporary fixes, then drop them and keep the solved coordinates.
|
||||
setDrag({ ...drag, releasing: true });
|
||||
@@ -673,10 +852,14 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
if ((/^[0-9.\-=]$/.test(event.key) || event.key === "Tab") && DRAW_TOOLS.has(tool) && openEntry(event.key === "Tab" ? undefined : event.key)) return "handled";
|
||||
const shortcuts: Record<string, Tool> = { v: "select", p: "point", l: "line", c: "circle", a: "arc", b: "spline", d: "delete", t: "trim", e: "extend", r: "fillet", h: "chamfer" };
|
||||
if (k === "enter" && draft?.tool === "spline") {
|
||||
if (draft.points.length >= 2) finishSpline(draft.points);
|
||||
if (draft.points.length >= 2) finishSpline(draft, false);
|
||||
return "handled";
|
||||
}
|
||||
if (shortcuts[k]) chooseTool(shortcuts[k]);
|
||||
if (k === "s" && tool === "select") smoothSelection();
|
||||
else if (k === "k" && tool === "select") {
|
||||
if (convertTarget) convertSpline(convertTarget);
|
||||
else setEditNote({ tone: "fail", text: "convert: select one B-spline that has control points (a spline drawn with the spline tool already has anchors)" });
|
||||
} else if (shortcuts[k]) chooseTool(shortcuts[k]);
|
||||
else if (k === "j") openProject();
|
||||
else if (k === "x") toggleConstruction();
|
||||
else if (k === "delete" || k === "backspace") deleteSelection();
|
||||
@@ -732,13 +915,19 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
const typed = DRAW_TOOLS.has(tool) ? " Or type numbers (Tab between fields, Enter places)." : "";
|
||||
const hint =
|
||||
(tool === "select"
|
||||
? "Click or shift-click to select; drag a point or a line to move it; click inside a loop for the profile, shift-click for a hole."
|
||||
? shown.size
|
||||
? "Drag an anchor (its handles follow) or a handle (its length is that side's pull); a smooth anchor keeps its handles in line: hold Alt while dragging for a corner, S smooths it again. Double-click the curve to add an anchor; Delete removes the selected anchor."
|
||||
: convertTarget
|
||||
? `${convertTarget} has control points, not anchors: K (or the button by the curve) converts it, keeping its shape.`
|
||||
: "Click or shift-click to select; drag a point or a line to move it; click inside a loop for the profile, shift-click for a hole. Click a spline to show its handles."
|
||||
: tool === "line"
|
||||
? draft ? "Click the next point; clicking an existing point ends the chain; Esc ends." : "Click the first point."
|
||||
: tool === "circle"
|
||||
? draft ? "Click a point on the circle." : "Click the centre."
|
||||
: tool === "spline"
|
||||
? draft ? "Click the next control point. Finish: Enter, or click the last point again (double-click); click the first point to close it. Esc drops it." : "Click the first control point."
|
||||
? draft
|
||||
? "Click the next anchor; press and drag to pull out its handles. Finish: Enter, the last anchor again (double-click) or the button; the first anchor closes it. Esc drops it."
|
||||
: "Click the first anchor; press and drag to pull out its handles (a click alone makes a smooth curve through the anchors)."
|
||||
: tool === "arc"
|
||||
? draft ? (draft.tool === "arc" && draft.start ? "Click the end (counter-clockwise from start)." : "Click the start point (sets the radius).") : "Click the centre."
|
||||
: tool === "delete"
|
||||
@@ -756,7 +945,9 @@ export function useSketchEditor(initial: SketchDoc, modelPoints: readonly [numbe
|
||||
return {
|
||||
cornerHover, pendingLine, cornerBox, setCornerBox, submitCorner, projectOpen, setProjectOpen, openProject, projectSketch, projectFrom,
|
||||
doc, commit, undo, redo, edits, editNote, editBusy, flash, hoverEnd, runEdit, tool, chooseTool, selection, highlight, setHighlight, draft, cursor, hover, drag, box, setBox, result, error, auto, setAuto, snapOn,
|
||||
setSnapOn, construction, choice, pts, loops, applicable, blamed, fresh, crossings, finishSplineDraft: () => draft?.tool === "spline" && draft.points.length >= 2 && finishSpline(draft.points), entry, setEntry, entryFields, submitEntry, failing, highlighted, fixedPoints, solved, badge, diagnostics, outer, hint, extents,
|
||||
setSnapOn, construction, choice, pts, loops, applicable, blamed, fresh, crossings, finishSplineDraft: () => draft?.tool === "spline" && draft.points.length >= 2 && finishSpline(draft, false), entry,
|
||||
wires, wire, setWireKey, setOutput,
|
||||
roles, shown, hidden, convertTarget, convertSpline, insertAnchor, smoothSelection, pressingPen: () => pen.current !== null, setEntry, entryFields, submitEntry, failing, highlighted, fixedPoints, solved, badge, diagnostics, outer, hint, extents,
|
||||
openBox, applyConstraint, submitBox, deleteSelection, toggleConstruction, pointerDown, pointerMove, pointerUp, pointerLeave, key,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { NAMED_FRAMES, faceFrame, placeValues, placedFrame, type PlaceFrame } from "./workplane-place";
|
||||
|
||||
const close = (a: readonly number[], b: readonly number[]) => a.forEach((v, i) => expect(v).toBeCloseTo(b[i], 9));
|
||||
|
||||
describe("placing a workplane", () => {
|
||||
it("moves along the base's own axes and turns about them, as the SDK does", () => {
|
||||
// the SDK's test: XY moved 20 up and turned 90 about x, then 5 along its normal and 90 about its normal
|
||||
const tilted = placedFrame(NAMED_FRAMES.XY, { move: [0, 0, 20], rx: 90, ry: 0, rz: 0 });
|
||||
close(tilted.origin, [0, 0, 20]);
|
||||
close(tilted.normal, [0, -1, 0]);
|
||||
const lid = placedFrame(tilted, { move: [0, 0, 5], rx: 0, ry: 0, rz: 90 });
|
||||
close(lid.origin, [0, -5, 20]);
|
||||
close(lid.x_axis, [0, 0, 1]);
|
||||
close(NAMED_FRAMES.XZ.normal, [0, -1, 0]);
|
||||
});
|
||||
|
||||
it("reads back the values that place a frame", () => {
|
||||
const base: PlaceFrame = placedFrame(NAMED_FRAMES.YZ, { move: [3, -2, 7], rx: 10, ry: -25, rz: 40 });
|
||||
for (const values of [
|
||||
{ move: [1, 2, 3], rx: 30, ry: 20, rz: -50 },
|
||||
{ move: [0, 0, -12.5], rx: -170, ry: 45, rz: 5 },
|
||||
{ move: [0, 0, 0], rx: 0, ry: 0, rz: 0 },
|
||||
] as const) {
|
||||
const back = placeValues(base, placedFrame(base, { ...values, move: [...values.move] }));
|
||||
close(back.move, values.move);
|
||||
close([back.rx, back.ry, back.rz], [values.rx, values.ry, values.rz]);
|
||||
}
|
||||
});
|
||||
|
||||
it("takes a face's connector frame, its outward normal and x axis", () => {
|
||||
const frame = faceFrame({ connector_frame: { origin: [1, 2, 3], x_axis: [1, 0, 0], y_axis: [0, -1, 0], z_axis: [0, 0, -1] } });
|
||||
expect(frame).not.toBeNull();
|
||||
close(frame!.normal, [0, 0, -1]);
|
||||
close(frame!.y_axis, [0, -1, 0]);
|
||||
expect(faceFrame({})).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/** Placing a workplane by hand: a base frame (XY / XZ / YZ, a workplane of the notebook, a picked face), the offset along
|
||||
* the base's own axes and three turns about them, as `make_workplane_offset_rworkplane` takes them. The handles in the
|
||||
* viewport move a frame; this module turns a frame into those numbers and back, with the SDK's formula, so what is shown
|
||||
* is what the cell makes. Pure: no React, no three.js. */
|
||||
|
||||
import { add, cross, dot, scale, unit, vec3, type Vec3 } from "@/lib/sketch-plane";
|
||||
|
||||
/** A frame in world mm: an origin and three orthonormal axes (normal = x cross y). */
|
||||
export type PlaceFrame = { origin: Vec3; x_axis: Vec3; y_axis: Vec3; normal: Vec3 };
|
||||
|
||||
/** What the cell writes: `offset=(move)`, `rx`, `ry`, `rz` (degrees). */
|
||||
export type PlaceValues = { move: Vec3; rx: number; ry: number; rz: number };
|
||||
|
||||
export const ZERO_PLACE: PlaceValues = { move: [0, 0, 0], rx: 0, ry: 0, rz: 0 };
|
||||
|
||||
/** The named planes as sketches (and the SDK's base_plane) read them. */
|
||||
export const NAMED_FRAMES: Record<"XY" | "XZ" | "YZ", PlaceFrame> = {
|
||||
XY: { origin: [0, 0, 0], x_axis: [1, 0, 0], y_axis: [0, 1, 0], normal: [0, 0, 1] },
|
||||
XZ: { origin: [0, 0, 0], x_axis: [1, 0, 0], y_axis: [0, 0, 1], normal: [0, -1, 0] },
|
||||
YZ: { origin: [0, 0, 0], x_axis: [0, 1, 0], y_axis: [0, 0, 1], normal: [1, 0, 0] },
|
||||
};
|
||||
|
||||
const RAD = Math.PI / 180;
|
||||
type M3 = [Vec3, Vec3, Vec3]; // rows
|
||||
|
||||
const mul = (a: M3, b: M3): M3 =>
|
||||
a.map((row) => [0, 1, 2].map((j) => row[0] * b[0][j] + row[1] * b[1][j] + row[2] * b[2][j])) as M3;
|
||||
const rx = (t: number): M3 => [[1, 0, 0], [0, Math.cos(t), -Math.sin(t)], [0, Math.sin(t), Math.cos(t)]];
|
||||
const ry = (t: number): M3 => [[Math.cos(t), 0, Math.sin(t)], [0, 1, 0], [-Math.sin(t), 0, Math.cos(t)]];
|
||||
const rz = (t: number): M3 => [[Math.cos(t), -Math.sin(t), 0], [Math.sin(t), Math.cos(t), 0], [0, 0, 1]];
|
||||
const column = (m: M3, j: number): Vec3 => [m[0][j], m[1][j], m[2][j]];
|
||||
|
||||
/** The frame `values` place on `base`: the origin moved along the base's x, y and normal, the axes turned about the
|
||||
* base's x, then the y that left, then the z (R = Rx Ry Rz in the base's frame), as the SDK does. */
|
||||
export function placedFrame(base: PlaceFrame, values: PlaceValues): PlaceFrame {
|
||||
const [dx, dy, dz] = values.move;
|
||||
const origin = add(base.origin, add(scale(base.x_axis, dx), add(scale(base.y_axis, dy), scale(base.normal, dz))));
|
||||
const local = mul(mul(rx(values.rx * RAD), ry(values.ry * RAD)), rz(values.rz * RAD));
|
||||
const world = (v: Vec3): Vec3 => add(scale(base.x_axis, v[0]), add(scale(base.y_axis, v[1]), scale(base.normal, v[2])));
|
||||
return { origin, x_axis: world(column(local, 0)), y_axis: world(column(local, 1)), normal: world(column(local, 2)) };
|
||||
}
|
||||
|
||||
const round = (value: number, step: number) => Math.round(value / step) * step + 0; // + 0: no -0
|
||||
|
||||
/** The values that place `frame` on `base` (the inverse of placedFrame); offsets to 0.001 mm, turns to 0.001 degree. */
|
||||
export function placeValues(base: PlaceFrame, frame: PlaceFrame): PlaceValues {
|
||||
const d: Vec3 = [frame.origin[0] - base.origin[0], frame.origin[1] - base.origin[1], frame.origin[2] - base.origin[2]];
|
||||
const move: Vec3 = [dot(d, base.x_axis), dot(d, base.y_axis), dot(d, base.normal)].map((v) => round(v, 0.001)) as Vec3;
|
||||
// M = B^T R: the new axes in the base's coordinates (columns), = Rx(a) Ry(b) Rz(c)
|
||||
const inBase = (v: Vec3): Vec3 => [dot(v, base.x_axis), dot(v, base.y_axis), dot(v, base.normal)];
|
||||
const x = inBase(frame.x_axis);
|
||||
const y = inBase(frame.y_axis);
|
||||
const z = inBase(frame.normal);
|
||||
const m13 = Math.max(-1, Math.min(1, z[0]));
|
||||
const b = Math.asin(m13);
|
||||
let a: number;
|
||||
let c: number;
|
||||
if (Math.abs(m13) < 0.9999999) {
|
||||
a = Math.atan2(-z[1], z[2]);
|
||||
c = Math.atan2(-y[0], x[0]);
|
||||
} else {
|
||||
a = Math.atan2(y[2], y[1]);
|
||||
c = 0;
|
||||
}
|
||||
return { move, rx: round(a / RAD, 0.001), ry: round(b / RAD, 0.001), rz: round(c / RAD, 0.001) };
|
||||
}
|
||||
|
||||
/** A frame from a picked planar face's connector frame (entity info `properties.connector_frame`: its centroid, outward
|
||||
* normal and an x axis); null for anything else. The cell passes that x axis as `x_dir`, so the plane made matches. */
|
||||
export function faceFrame(properties: Record<string, unknown> | null | undefined): PlaceFrame | null {
|
||||
const raw = properties?.connector_frame as Record<string, unknown> | undefined;
|
||||
const origin = vec3(raw?.origin);
|
||||
const x = vec3(raw?.x_axis) && unit(vec3(raw?.x_axis)!);
|
||||
const z = vec3(raw?.z_axis) && unit(vec3(raw?.z_axis)!);
|
||||
if (!origin || !x || !z) return null;
|
||||
return { origin, x_axis: x, y_axis: cross(z, x), normal: z };
|
||||
}
|
||||
|
||||
/** The values a cell can be given for a place: rounded, no -0. */
|
||||
export function cleanValues(values: PlaceValues): PlaceValues {
|
||||
return {
|
||||
move: values.move.map((v) => round(v, 0.001)) as Vec3,
|
||||
rx: round(values.rx, 0.001),
|
||||
ry: round(values.ry, 0.001),
|
||||
rz: round(values.rz, 0.001),
|
||||
};
|
||||
}
|
||||
@@ -628,6 +628,11 @@ void bind_entity_operators(py::module_& m) {
|
||||
py::arg("center"), py::kw_only(), py::arg("construction") = false);
|
||||
m.def("trim_rsketch", &trim_rsketch, py::arg("sketch"), py::arg("entity"), py::arg("at"), py::kw_only(),
|
||||
py::arg("against") = py::none());
|
||||
m.def("insert_spline_anchor_rsketch", &insert_spline_anchor_rsketch, py::arg("sketch"), py::arg("spline"),
|
||||
py::arg("at"));
|
||||
m.def("remove_spline_anchor_rsketch", &remove_spline_anchor_rsketch, py::arg("sketch"), py::arg("spline"),
|
||||
py::arg("anchor"));
|
||||
m.def("convert_spline_to_anchors_rsketch", &convert_spline_to_anchors_rsketch, py::arg("sketch"), py::arg("spline"));
|
||||
m.def(
|
||||
"extend_rsketch",
|
||||
[](const Sketch& sketch, const SketchTarget& entity, const Choice<EndTag>& end,
|
||||
|
||||
@@ -171,6 +171,27 @@ Sketch trim_rsketch(const Sketch& sketch, const SketchTarget& entity, const Sket
|
||||
Sketch extend_rsketch(const Sketch& sketch, const SketchTarget& entity, const std::string& end,
|
||||
const std::optional<SketchTarget>& to = std::nullopt);
|
||||
|
||||
// A B-spline in anchor form -- cubic, inner knots of multiplicity 3, every control point a sketch point -- is a chain
|
||||
// of Bezier spans: control points [A0, out0, in1, A1, out1, in2, A2, ...], anchors on the curve with an in- and an
|
||||
// out-handle each (a pen tool's curve). These three edit that structure on the solved geometry.
|
||||
//
|
||||
// Insert an anchor at the curve point nearest `at` without changing the curve (de Casteljau split of that span): the
|
||||
// span's two handles get shorter (they keep their ids; a dimension or fix on them is dropped) and the new anchor and
|
||||
// its two handles are new points p<n>. Refused at an existing anchor and for a B-spline that is not in anchor form.
|
||||
Sketch insert_spline_anchor_rsketch(const Sketch& sketch, const SketchTarget& spline, const SketchPosition& at);
|
||||
|
||||
// Remove the inner anchor `anchor` (a point id) and its two handles: the spans on either side become one, whose outer
|
||||
// handles keep their ids and directions and get the lengths that fit the old curve best (a handle a constraint or
|
||||
// another entity holds keeps its place). The removed points go unless another entity uses them, and constraints on the
|
||||
// removed points go with them. An end anchor cannot be removed.
|
||||
Sketch remove_spline_anchor_rsketch(const Sketch& sketch, const SketchTarget& spline, const SketchTarget& anchor);
|
||||
|
||||
// Write an open B-spline in anchor form: exactly (same curve) for degree <= 3 without weights, else approximated
|
||||
// within 1e-4. The end points keep their ids, inner control points that do not move keep theirs, the others are new
|
||||
// points p<n>; control points no entity uses any more go, with their constraints. A spline already in anchor form is
|
||||
// left as it is.
|
||||
Sketch convert_spline_to_anchors_rsketch(const Sketch& sketch, const SketchTarget& spline);
|
||||
|
||||
// Round the corner where the lines `a` and `b` meet (they must share an end point) with an arc of `radius`. The sketch
|
||||
// is solved first. Both lines are shortened to the tangent points; the arc runs counter-clockwise from its start to
|
||||
// its end around its centre and is tied to each line with a tangent constraint (at_b = the arc end that touches the
|
||||
|
||||
@@ -150,6 +150,7 @@ class Sketch {
|
||||
friend class SketchEditor; // trim / extend rewrite the document in src/sketch/edit.cpp
|
||||
friend class SketchCorner; // fillet / chamfer of a corner (src/sketch/corner.cpp)
|
||||
friend class SketchProjection; // project_rsketch (src/sketch/project.cpp)
|
||||
friend class SketchAnchors; // insert / remove a B-spline anchor (src/sketch/anchors.cpp)
|
||||
void add_entity(SketchEntity entity);
|
||||
SketchPoint2 entity_xy(const std::string& point_id) const;
|
||||
|
||||
|
||||
@@ -40,6 +40,9 @@ std::string entity_type_of(std::string_view op) {
|
||||
"fillet_corner_rsketch",
|
||||
"chamfer_corner_rsketch",
|
||||
"project_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"make_wire_from_sketch_rwire",
|
||||
"make_face_from_sketch_rface",
|
||||
"make_constrain_coincident_rsketch",
|
||||
@@ -176,9 +179,11 @@ std::vector<std::string> node_labels_for_op(std::string_view op) {
|
||||
{"add_line_rsketch", {"line", "sketch"}},
|
||||
{"add_point_rsketch", {"point", "sketch"}},
|
||||
{"chamfer_corner_rsketch", {"edit", "sketch"}},
|
||||
{"convert_spline_to_anchors_rsketch", {"edit", "sketch"}},
|
||||
{"extend_rsketch", {"edit", "sketch"}},
|
||||
{"fill_holes_rshell", {"derived", "shell", "surface"}},
|
||||
{"fillet_corner_rsketch", {"edit", "sketch"}},
|
||||
{"insert_spline_anchor_rsketch", {"edit", "sketch"}},
|
||||
{"fit_point_grid_rface", {"face", "primitive", "surface"}},
|
||||
{"make_2d_cut_rface", {"derived", "face"}},
|
||||
{"make_2d_intersect_rface", {"derived", "face"}},
|
||||
@@ -221,6 +226,7 @@ std::vector<std::string> node_labels_for_op(std::string_view op) {
|
||||
{"make_wire_from_sketch_rwire", {"derived", "sketch", "wire"}},
|
||||
{"sew_faces_rshell", {"derived", "shell", "surface"}},
|
||||
{"project_rsketch", {"edit", "sketch"}},
|
||||
{"remove_spline_anchor_rsketch", {"edit", "sketch"}},
|
||||
{"trim_rsketch", {"edit", "sketch"}},
|
||||
{"trim_surface_rface", {"derived", "face", "surface", "trimmed"}},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,614 @@
|
||||
// insert_spline_anchor_rsketch, remove_spline_anchor_rsketch and convert_spline_to_anchors_rsketch: edit a B-spline in
|
||||
// its anchor form.
|
||||
//
|
||||
// The anchor form is how a pen tool draws a curve: anchors on the curve, each with an in-handle and an out-handle. It
|
||||
// is a cubic B-spline whose control points are [A0, out0, in1, A1, out1, in2, A2, ...] and whose inner knots have
|
||||
// multiplicity 3 (clamped ends, unit weights): every span is a cubic Bezier from one anchor to the next, and the sketch
|
||||
// solver moves every control point of such a spline (solver/model.cpp, is_bezier_chain). Moving an anchor or a handle
|
||||
// is moving a point; these operations change the structure. Like trim and extend they work on the solved geometry.
|
||||
//
|
||||
// Inserting splits the span under `at` with de Casteljau's construction at the parameter of the nearest curve point, so
|
||||
// the curve does not change: the two handles of that span get shorter (they keep their ids) and the new anchor gets new
|
||||
// points for itself and its two handles. Removing merges the two spans beside an anchor into one: the outer handles
|
||||
// keep their directions and get the lengths that fit the old two-span curve best (least squares on samples), so a
|
||||
// removal undoes an insertion exactly. Converting writes an open, non-periodic B-spline in this form: exactly for
|
||||
// degree <= 3 without weights (degree elevation and knot insertion), else as an approximation.
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
#include <Geom2dConvert_ApproxCurve.hxx>
|
||||
#include <Geom2d_BSplineCurve.hxx>
|
||||
|
||||
#include "edit_curves.hpp"
|
||||
#include "finalize.hpp"
|
||||
#include "scad/core/error.hpp"
|
||||
#include "scad/sketch/operators.hpp"
|
||||
|
||||
namespace scad {
|
||||
|
||||
namespace {
|
||||
|
||||
using sketch_detail::finalize_sketch_object;
|
||||
using sketch_detail::Spline2;
|
||||
using SplineHandle = opencascade::handle<Geom2d_BSplineCurve>;
|
||||
using Pt = SketchPoint2;
|
||||
|
||||
// Two positions closer than this (sketch units) are the same place.
|
||||
constexpr double kTol = 1e-6;
|
||||
// How closely convert_spline_to_anchors_rsketch follows a curve it cannot write exactly (sketch units).
|
||||
constexpr double kApproxTol = 1e-4;
|
||||
// A merged handle is never shorter than this share of its old length: a fit that wants it reversed keeps it pointing
|
||||
// the way it did (the tangent at the neighbouring anchor stays).
|
||||
constexpr double kShortestHandle = 0.05;
|
||||
constexpr int kFitSamples = 64;
|
||||
|
||||
std::string id_of(const SketchTarget& target) {
|
||||
return target.is_ref() ? target.ref().entity_id : target.path();
|
||||
}
|
||||
|
||||
std::string number_text(double value) {
|
||||
char buffer[32];
|
||||
std::snprintf(buffer, sizeof buffer, "%.6g", value);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
Pt lerp(const Pt& a, const Pt& b, double t) {
|
||||
return {a.first + (b.first - a.first) * t, a.second + (b.second - a.second) * t};
|
||||
}
|
||||
|
||||
double distance(const Pt& a, const Pt& b) {
|
||||
return std::hypot(a.first - b.first, a.second - b.second);
|
||||
}
|
||||
|
||||
bool unit_weights(const SketchBSpline& spline) {
|
||||
if (!spline.weights)
|
||||
return true;
|
||||
return std::all_of(spline.weights->begin(), spline.weights->end(),
|
||||
[](double w) { return std::abs(w - 1.0) <= 1e-12; });
|
||||
}
|
||||
|
||||
// The anchor form (see the top of the file), every control point being a sketch point.
|
||||
bool anchor_form(const SketchBSpline& spline) {
|
||||
if (spline.periodic || spline.degree != 3 || !unit_weights(spline))
|
||||
return false;
|
||||
const std::vector<int>& mult = spline.multiplicities;
|
||||
if (mult.size() < 2 || mult.front() != 4 || mult.back() != 4)
|
||||
return false;
|
||||
for (std::size_t i = 1; i + 1 < mult.size(); ++i)
|
||||
if (mult[i] != 3)
|
||||
return false;
|
||||
if (spline.poles.size() != 3 * (mult.size() - 1) + 1)
|
||||
return false;
|
||||
return std::all_of(spline.poles.begin(), spline.poles.end(), [](const SketchPole& pole) { return pole.is_point(); });
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// The editor of a B-spline's anchors: a solved working copy of the sketch and the ids that are taken. A friend of
|
||||
// Sketch (it rewrites the document, which the functional API of Sketch cannot do).
|
||||
class SketchAnchors {
|
||||
public:
|
||||
explicit SketchAnchors(const Sketch& source) : work_(source.clone(false)) {
|
||||
SketchSolveRequest request; // strict: a conflicting sketch has no geometry to edit
|
||||
const SketchSolveResult solved = work_.solve(request);
|
||||
for (const auto& [id, point] : solved.solved_points)
|
||||
if (work_.entities_.contains(id))
|
||||
points_[id] = point;
|
||||
for (auto& [id, entity] : work_.entities_) {
|
||||
taken_.insert(id);
|
||||
if (entity.kind == kPointKind) {
|
||||
const Pt p = points_.at(id);
|
||||
entity.data.set("x", Value(p.first));
|
||||
entity.data.set("y", Value(p.second));
|
||||
} else if (entity.kind == kCircleKind) {
|
||||
entity.data.set("radius", Value(solved.solved_scalars.at("circle:" + id + ":radius")));
|
||||
} else if (entity.kind == kBSplineKind) {
|
||||
std::vector<Pt>& poles = poles_[id];
|
||||
const std::size_t count = entity.data.find("control_points")->as_array().size();
|
||||
for (std::size_t i = 0; i < count; ++i)
|
||||
poles.push_back(solved.solved_points.at("bspline:" + id + ":pole:" + std::to_string(i)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Sketch insert(const SketchTarget& spline_target, const SketchPosition& at) {
|
||||
const SketchEntity subject = anchor_spline(spline_target);
|
||||
const SketchBSpline definition = subject.bspline();
|
||||
const std::vector<Pt>& poles = poles_.at(subject.id);
|
||||
std::vector<std::string> ids = pole_ids(definition);
|
||||
const Pt click = position_of(at);
|
||||
Spline2 shape;
|
||||
shape.poles = poles;
|
||||
shape.knots = definition.knots;
|
||||
shape.multiplicities = definition.multiplicities;
|
||||
const double u = sketch_detail::nearest_parameter(sketch_detail::make_spline2(shape), click);
|
||||
const std::vector<double>& knots = definition.knots;
|
||||
std::size_t span = 0;
|
||||
while (span + 2 < knots.size() && u >= knots[span + 1])
|
||||
++span;
|
||||
const double t = (u - knots[span]) / (knots[span + 1] - knots[span]);
|
||||
const std::size_t first = 3 * span;
|
||||
const Pt& p0 = poles[first];
|
||||
const Pt& p1 = poles[first + 1];
|
||||
const Pt& p2 = poles[first + 2];
|
||||
const Pt& p3 = poles[first + 3];
|
||||
// de Casteljau: the span from p0 to p3 is the span p0 a d m followed by the span m e c p3
|
||||
const Pt a = lerp(p0, p1, t);
|
||||
const Pt b = lerp(p1, p2, t);
|
||||
const Pt c = lerp(p2, p3, t);
|
||||
const Pt d = lerp(a, b, t);
|
||||
const Pt e = lerp(b, c, t);
|
||||
const Pt m = lerp(d, e, t);
|
||||
if (distance(m, p0) < kTol || distance(m, p3) < kTol)
|
||||
throw ValueError("'" + subject.id + "' already has an anchor there ('" +
|
||||
ids[distance(m, p0) < kTol ? first : first + 3] + "'): pick a place between two anchors");
|
||||
|
||||
std::vector<SketchEntity> made;
|
||||
// The span's handles get shorter. A handle another entity or another pole shares cannot move without moving that
|
||||
// too: the spline takes a new point there instead.
|
||||
const auto shorten = [&](std::size_t index, const Pt& to) {
|
||||
if (shared(ids[index], subject, ids))
|
||||
ids[index] = new_point(to, made);
|
||||
else
|
||||
move_point(ids[index], to);
|
||||
};
|
||||
shorten(first + 1, a);
|
||||
shorten(first + 2, c);
|
||||
const std::string in = new_point(d, made);
|
||||
const std::string anchor = new_point(m, made);
|
||||
const std::string out = new_point(e, made);
|
||||
ids.insert(ids.begin() + static_cast<std::ptrdiff_t>(first + 2), {in, anchor, out});
|
||||
std::vector<double> new_knots = knots;
|
||||
std::vector<int> mults = definition.multiplicities;
|
||||
new_knots.insert(new_knots.begin() + static_cast<std::ptrdiff_t>(span + 1), u);
|
||||
mults.insert(mults.begin() + static_cast<std::ptrdiff_t>(span + 1), 3);
|
||||
write(subject, ids, new_knots, mults, made);
|
||||
notes_.push_back("anchor '" + anchor + "' (handles '" + in + "' and '" + out + "') inserted in '" + subject.id +
|
||||
"' between '" + ids[first] + "' and '" + ids[first + 6] + "'");
|
||||
return finish("insert_spline_anchor_rsketch");
|
||||
}
|
||||
|
||||
Sketch remove(const SketchTarget& spline_target, const SketchTarget& anchor_target) {
|
||||
const SketchEntity subject = anchor_spline(spline_target);
|
||||
const SketchBSpline definition = subject.bspline();
|
||||
const std::vector<Pt>& poles = poles_.at(subject.id);
|
||||
std::vector<std::string> ids = pole_ids(definition);
|
||||
const std::string anchor = id_of(anchor_target);
|
||||
const std::size_t last = ids.size() - 1;
|
||||
std::size_t j = 0;
|
||||
for (std::size_t i = 3; i < last; i += 3)
|
||||
if (ids[i] == anchor)
|
||||
j = i;
|
||||
if (j == 0) {
|
||||
if (anchor == ids.front() || anchor == ids.back())
|
||||
throw ValueError("'" + anchor + "' is an end of '" + subject.id +
|
||||
"': an end anchor cannot be removed (trim the spline, or delete it)");
|
||||
for (std::size_t i = 0; i <= last; ++i)
|
||||
if (i % 3 != 0 && ids[i] == anchor)
|
||||
throw ValueError("'" + anchor + "' is a handle of '" + subject.id +
|
||||
"', not an anchor: remove an anchor (a point on the curve)");
|
||||
std::string inner;
|
||||
for (std::size_t i = 3; i < last; i += 3)
|
||||
inner += (inner.empty() ? "'" : ", '") + ids[i] + "'";
|
||||
throw ValueError("'" + anchor + "' is not an anchor of '" + subject.id + "'" +
|
||||
(inner.empty() ? std::string(": it has only its two end anchors")
|
||||
: " (the anchors that can be removed: " + inner + ")"));
|
||||
}
|
||||
const std::size_t span = j / 3; // the spans span - 1 and span become one
|
||||
const std::vector<double>& knots = definition.knots;
|
||||
const Pt& a0 = poles[j - 3];
|
||||
const Pt& a3 = poles[j + 3];
|
||||
const Pt d0{poles[j - 2].first - a0.first, poles[j - 2].second - a0.second};
|
||||
const Pt d1{poles[j + 2].first - a3.first, poles[j + 2].second - a3.second};
|
||||
// The handles' new lengths (as multiples of the old ones): least squares between the merged span and samples of the
|
||||
// two spans, over the same parameter range. A zero-length handle, or one something else holds, stays as it is.
|
||||
Spline2 shape;
|
||||
shape.poles = poles;
|
||||
shape.knots = knots;
|
||||
shape.multiplicities = definition.multiplicities;
|
||||
const SplineHandle curve = sketch_detail::make_spline2(shape);
|
||||
const bool free0 = std::hypot(d0.first, d0.second) > kTol && !held(ids[j - 2], subject, ids);
|
||||
const bool free1 = std::hypot(d1.first, d1.second) > kTol && !held(ids[j + 2], subject, ids);
|
||||
double m11 = 0.0, m12 = 0.0, m22 = 0.0, v1 = 0.0, v2 = 0.0;
|
||||
for (int i = 0; i <= kFitSamples; ++i) {
|
||||
const double t = static_cast<double>(i) / kFitSamples;
|
||||
const Pt s = sketch_detail::value_at(curve, knots[span - 1] + t * (knots[span + 1] - knots[span - 1]));
|
||||
const double b0 = (1 - t) * (1 - t) * (1 - t);
|
||||
const double b1 = 3 * (1 - t) * (1 - t) * t;
|
||||
const double b2 = 3 * (1 - t) * t * t;
|
||||
const double b3 = t * t * t;
|
||||
const Pt r{s.first - a0.first * (b0 + b1) - a3.first * (b2 + b3),
|
||||
s.second - a0.second * (b0 + b1) - a3.second * (b2 + b3)};
|
||||
const double dot01 = d0.first * d1.first + d0.second * d1.second;
|
||||
m11 += b1 * b1 * (d0.first * d0.first + d0.second * d0.second);
|
||||
m12 += b1 * b2 * dot01;
|
||||
m22 += b2 * b2 * (d1.first * d1.first + d1.second * d1.second);
|
||||
v1 += b1 * (d0.first * r.first + d0.second * r.second);
|
||||
v2 += b2 * (d1.first * r.first + d1.second * r.second);
|
||||
}
|
||||
double alpha = 1.0;
|
||||
double beta = 1.0;
|
||||
const auto fit_alpha = [&] { alpha = std::max((v1 - m12 * beta) / m11, kShortestHandle); };
|
||||
const auto fit_beta = [&] { beta = std::max((v2 - m12 * alpha) / m22, kShortestHandle); };
|
||||
const double det = m11 * m22 - m12 * m12;
|
||||
if (free0 && free1 && std::abs(det) > 1e-12 * std::max(m11 * m22, 1e-300)) {
|
||||
alpha = (v1 * m22 - v2 * m12) / det;
|
||||
beta = (m11 * v2 - m12 * v1) / det;
|
||||
if (alpha < kShortestHandle) {
|
||||
alpha = kShortestHandle;
|
||||
fit_beta();
|
||||
} else if (beta < kShortestHandle) {
|
||||
beta = kShortestHandle;
|
||||
fit_alpha();
|
||||
}
|
||||
} else {
|
||||
if (free0)
|
||||
fit_alpha();
|
||||
if (free1)
|
||||
fit_beta();
|
||||
}
|
||||
if (free0)
|
||||
move_point(ids[j - 2], {a0.first + alpha * d0.first, a0.second + alpha * d0.second});
|
||||
if (free1)
|
||||
move_point(ids[j + 2], {a3.first + beta * d1.first, a3.second + beta * d1.second});
|
||||
|
||||
const std::vector<std::string> gone{ids[j - 1], ids[j], ids[j + 1]};
|
||||
ids.erase(ids.begin() + static_cast<std::ptrdiff_t>(j - 1), ids.begin() + static_cast<std::ptrdiff_t>(j + 2));
|
||||
std::vector<double> new_knots = knots;
|
||||
std::vector<int> mults = definition.multiplicities;
|
||||
new_knots.erase(new_knots.begin() + static_cast<std::ptrdiff_t>(span));
|
||||
mults.erase(mults.begin() + static_cast<std::ptrdiff_t>(span));
|
||||
write(subject, ids, new_knots, mults, {});
|
||||
drop_unused(gone, subject);
|
||||
return finish("remove_spline_anchor_rsketch");
|
||||
}
|
||||
|
||||
Sketch convert(const SketchTarget& spline_target) {
|
||||
const SketchEntity subject = spline_entity(spline_target);
|
||||
const SketchBSpline definition = subject.bspline();
|
||||
if (anchor_form(definition)) {
|
||||
notes_.push_back("'" + subject.id + "' is already in anchor form: nothing changed");
|
||||
return finish("convert_spline_to_anchors_rsketch");
|
||||
}
|
||||
if (definition.periodic)
|
||||
throw ValueError("'" + subject.id +
|
||||
"' is periodic: only an open B-spline (or one that starts and ends on one point) has an "
|
||||
"anchor form");
|
||||
Spline2 shape;
|
||||
shape.degree = definition.degree;
|
||||
shape.poles = poles_.at(subject.id);
|
||||
shape.knots = definition.knots;
|
||||
shape.multiplicities = definition.multiplicities;
|
||||
if (!unit_weights(definition))
|
||||
shape.weights = *definition.weights;
|
||||
SplineHandle curve = sketch_detail::make_spline2(shape);
|
||||
if (curve->Degree() > 3 || curve->IsRational()) {
|
||||
Geom2dConvert_ApproxCurve approx(curve, kApproxTol, GeomAbs_C1, 400, 3);
|
||||
if (!approx.HasResult())
|
||||
throw ValueError("'" + subject.id + "' could not be approximated by cubic spans within " +
|
||||
number_text(kApproxTol));
|
||||
curve = approx.Curve();
|
||||
notes_.push_back(
|
||||
"'" + subject.id + "' (" +
|
||||
(definition.degree > 3 ? "degree " + std::to_string(definition.degree) : std::string("rational")) +
|
||||
") has no exact anchor form: it was approximated (largest deviation " + number_text(approx.MaxError()) + ")");
|
||||
}
|
||||
if (curve->Degree() < 3)
|
||||
curve->IncreaseDegree(3);
|
||||
for (int i = 2; i < curve->NbKnots(); ++i)
|
||||
curve->IncreaseMultiplicity(i, 3);
|
||||
const Spline2 result = sketch_detail::spline2_of(curve);
|
||||
|
||||
// The ends keep their points; an inner control point that did not move keeps its id, the others are new points.
|
||||
std::vector<std::string> originals = pole_ids(definition);
|
||||
std::set<std::string> reused;
|
||||
std::vector<SketchEntity> made;
|
||||
std::vector<std::string> ids;
|
||||
const std::string start = subject.point_id("start");
|
||||
const std::string end = subject.point_id("end");
|
||||
for (std::size_t i = 0; i < result.poles.size(); ++i) {
|
||||
if (i == 0 || i + 1 == result.poles.size()) {
|
||||
ids.push_back(i == 0 ? start : end);
|
||||
continue;
|
||||
}
|
||||
std::string id;
|
||||
for (const std::string& candidate : originals)
|
||||
if (!candidate.empty() && candidate != start && candidate != end && reused.count(candidate) == 0 &&
|
||||
distance(points_.at(candidate), result.poles[i]) < kTol) {
|
||||
id = candidate;
|
||||
break;
|
||||
}
|
||||
if (id.empty())
|
||||
id = new_point(result.poles[i], made);
|
||||
reused.insert(id);
|
||||
ids.push_back(id);
|
||||
}
|
||||
write(subject, ids, result.knots, result.multiplicities, made);
|
||||
drop_unused(originals, subject);
|
||||
return finish("convert_spline_to_anchors_rsketch");
|
||||
}
|
||||
|
||||
private:
|
||||
SketchEntity spline_entity(const SketchTarget& target) const {
|
||||
const std::string id = id_of(target);
|
||||
const SketchEntity* entity = work_.entities_.find(id);
|
||||
if (entity == nullptr)
|
||||
throw ValueError("there is no entity '" + id + "' in the sketch");
|
||||
if (entity->kind != kBSplineKind)
|
||||
throw ValueError("'" + id + "' is a " + entity->kind + ", not a B-spline");
|
||||
return *entity;
|
||||
}
|
||||
|
||||
SketchEntity anchor_spline(const SketchTarget& target) const {
|
||||
SketchEntity entity = spline_entity(target);
|
||||
if (!anchor_form(entity.bspline()))
|
||||
throw ValueError("'" + entity.id +
|
||||
"' is not in anchor form (a cubic B-spline of Bezier spans: inner knots of multiplicity 3, "
|
||||
"every control point a sketch point): convert it first with "
|
||||
"convert_spline_to_anchors_rsketch");
|
||||
return entity;
|
||||
}
|
||||
|
||||
// The point id of every control point ("" for a literal pole).
|
||||
static std::vector<std::string> pole_ids(const SketchBSpline& spline) {
|
||||
std::vector<std::string> out;
|
||||
for (const SketchPole& pole : spline.poles)
|
||||
out.push_back(pole.point_id);
|
||||
return out;
|
||||
}
|
||||
|
||||
Pt position_of(const SketchPosition& at) const {
|
||||
if (!at.is_point()) {
|
||||
const Pt xy = at.xy();
|
||||
if (!std::isfinite(xy.first) || !std::isfinite(xy.second))
|
||||
throw ValueError("at must be a finite point (x, y) in sketch coordinates");
|
||||
return xy;
|
||||
}
|
||||
const std::string id = id_of(at.point());
|
||||
const SketchEntity* point = work_.entities_.find(id);
|
||||
if (point == nullptr || point->kind != kPointKind)
|
||||
throw ValueError("'" + id + "' is not a point of the sketch: 'at' is a point id or (x, y)");
|
||||
return points_.at(id);
|
||||
}
|
||||
|
||||
bool used_by_other(const std::string& point, const SketchEntity& subject) const {
|
||||
for (const auto& [id, entity] : work_.entities_) {
|
||||
if (id == subject.id || entity.kind == kPointKind)
|
||||
continue;
|
||||
for (const char* role : {"start", "end", "center", "major", "minor"})
|
||||
if (const Value* value = entity.data.find(role);
|
||||
value != nullptr && value->is_string() && value->as_string() == point)
|
||||
return true;
|
||||
if (entity.kind == kBSplineKind)
|
||||
for (const SketchPole& pole : entity.bspline().poles)
|
||||
if (pole.point_id == point)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Another entity uses the point, or it is more than one pole of this spline.
|
||||
bool shared(const std::string& point, const SketchEntity& subject, const std::vector<std::string>& ids) const {
|
||||
return used_by_other(point, subject) || std::count(ids.begin(), ids.end(), point) > 1;
|
||||
}
|
||||
|
||||
// As shared, or a constraint names the point: it is not ours to move.
|
||||
bool held(const std::string& point, const SketchEntity& subject, const std::vector<std::string>& ids) const {
|
||||
if (shared(point, subject, ids))
|
||||
return true;
|
||||
return std::any_of(work_.constraints_.begin(), work_.constraints_.end(),
|
||||
[&](const SketchConstraint& constraint) { return names(constraint, point); });
|
||||
}
|
||||
|
||||
// Whether a constraint names the point (by its id, or as <entity>.start|end|...).
|
||||
bool names(const SketchConstraint& constraint, const std::string& point) const {
|
||||
for (const SketchRef& target : constraint.targets) {
|
||||
if (target.entity_id == point)
|
||||
return true;
|
||||
if (target.kind != kPointKind || target.subentity == "geometry")
|
||||
continue;
|
||||
const SketchEntity* entity = work_.entities_.find(target.entity_id);
|
||||
if (entity != nullptr && entity->kind != kPointKind)
|
||||
if (const Value* value = entity->data.find(target.subentity);
|
||||
value != nullptr && value->is_string() && value->as_string() == point)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string new_point(const Pt& at, std::vector<SketchEntity>& made) {
|
||||
SketchEntity point;
|
||||
for (int n = 1;; ++n) {
|
||||
point.id = "p" + std::to_string(n);
|
||||
if (taken_.insert(point.id).second)
|
||||
break;
|
||||
}
|
||||
point.kind = std::string(kPointKind);
|
||||
point.data.set("x", Value(at.first));
|
||||
point.data.set("y", Value(at.second));
|
||||
points_[point.id] = at;
|
||||
made.push_back(point);
|
||||
return point.id;
|
||||
}
|
||||
|
||||
// Move a control point the edit reshapes: a dimension or fix on it no longer holds and is dropped.
|
||||
void move_point(const std::string& id, const Pt& to) {
|
||||
SketchEntity& point = work_.entities_.at(id);
|
||||
point.data.set("x", Value(to.first));
|
||||
point.data.set("y", Value(to.second));
|
||||
point.scalars.erase("x"); // the position now comes from the edit, not from a parameter
|
||||
point.scalars.erase("y");
|
||||
points_[id] = to;
|
||||
drop_constraints({id}, "moved");
|
||||
}
|
||||
|
||||
// Remove the constraints that name one of `points`, each with a note.
|
||||
void drop_constraints(const std::set<std::string>& points, const char* why) {
|
||||
std::vector<SketchConstraint> kept;
|
||||
for (SketchConstraint& constraint : work_.constraints_) {
|
||||
const auto named = std::find_if(points.begin(), points.end(),
|
||||
[&](const std::string& point) { return names(constraint, point); });
|
||||
if (named == points.end()) {
|
||||
kept.push_back(std::move(constraint));
|
||||
continue;
|
||||
}
|
||||
notes_.push_back("constraint '" + constraint.id + "' (" + constraint.kind + ") on point '" + *named +
|
||||
"', which " + why + ", was dropped");
|
||||
}
|
||||
work_.constraints_ = std::move(kept);
|
||||
}
|
||||
|
||||
// Give the spline the control points `ids` and the knots; the new points go just before it.
|
||||
void write(const SketchEntity& subject, const std::vector<std::string>& ids, const std::vector<double>& knots,
|
||||
const std::vector<int>& mults, const std::vector<SketchEntity>& made) {
|
||||
SketchEntity& entity = work_.entities_.at(subject.id);
|
||||
Value::Array poles;
|
||||
for (const std::string& id : ids) {
|
||||
Value pole = Value::object();
|
||||
pole.set("point_id", id);
|
||||
poles.push_back(std::move(pole));
|
||||
}
|
||||
entity.data.set("control_points", Value(std::move(poles)));
|
||||
entity.data.set("degree", 3);
|
||||
Value::Array knot_values;
|
||||
for (const double knot : knots)
|
||||
knot_values.emplace_back(knot);
|
||||
entity.data.set("knots", Value(std::move(knot_values)));
|
||||
Value::Array mult_values;
|
||||
for (const int mult : mults)
|
||||
mult_values.emplace_back(mult);
|
||||
entity.data.set("multiplicities", Value(std::move(mult_values)));
|
||||
entity.data.set("weights", Value());
|
||||
entity.data.set("periodic", false);
|
||||
if (made.empty())
|
||||
return;
|
||||
OrderedMap<SketchEntity> rebuilt;
|
||||
for (auto& [id, item] : work_.entities_) {
|
||||
if (id == subject.id)
|
||||
for (const SketchEntity& point : made)
|
||||
rebuilt.set(point.id, point);
|
||||
rebuilt.set(id, std::move(item));
|
||||
}
|
||||
work_.entities_ = std::move(rebuilt);
|
||||
}
|
||||
|
||||
// The points of `candidates` that no entity uses any more go, with the constraints that name them.
|
||||
void drop_unused(const std::vector<std::string>& candidates, const SketchEntity& subject) {
|
||||
const SketchBSpline now = work_.entities_.at(subject.id).bspline();
|
||||
std::set<std::string> gone;
|
||||
for (const std::string& id : candidates) {
|
||||
if (id.empty() || !work_.entities_.contains(id) || used_by_other(id, subject) ||
|
||||
std::any_of(now.poles.begin(), now.poles.end(), [&](const SketchPole& pole) { return pole.point_id == id; }))
|
||||
continue;
|
||||
gone.insert(id);
|
||||
}
|
||||
if (gone.empty())
|
||||
return;
|
||||
drop_constraints(gone, "is no longer on the spline");
|
||||
OrderedMap<SketchEntity> pruned;
|
||||
for (auto& [id, entity] : work_.entities_)
|
||||
if (gone.count(id) == 0)
|
||||
pruned.set(id, std::move(entity));
|
||||
work_.entities_ = std::move(pruned);
|
||||
}
|
||||
|
||||
Sketch finish(const char* operation) {
|
||||
Value notes = Value(Value::Array{});
|
||||
for (const std::string& note : notes_)
|
||||
notes.as_array().emplace_back(note);
|
||||
Value edit = Value::object();
|
||||
edit.set("operation", operation);
|
||||
edit.set("notes", notes);
|
||||
work_.metadata().set("last_edit", edit);
|
||||
work_.clear_solve_result();
|
||||
return std::move(work_);
|
||||
}
|
||||
|
||||
Sketch work_;
|
||||
std::map<std::string, Pt, std::less<>> points_;
|
||||
std::map<std::string, std::vector<Pt>, std::less<>> poles_; // B-splines: the solved control points
|
||||
std::set<std::string> taken_;
|
||||
std::vector<std::string> notes_;
|
||||
};
|
||||
|
||||
// ---- the operators
|
||||
// ------------------------------------------------------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
Value position_param(const SketchPosition& at) {
|
||||
if (at.is_point())
|
||||
return Value(id_of(at.point()));
|
||||
return Value(Value::Array{Value(at.xy().first), Value(at.xy().second)});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Sketch insert_spline_anchor_rsketch(const Sketch& sketch, const SketchTarget& spline, const SketchPosition& at) {
|
||||
static const ErrorSpec kSpec{
|
||||
"insert_spline_anchor_rsketch",
|
||||
"Failed to insert an anchor into the sketch B-spline.",
|
||||
{"The spline id does not exist or is not a B-spline.",
|
||||
"The B-spline is not in anchor form (cubic Bezier spans: inner knots of multiplicity 3).",
|
||||
"'at' is not a finite point (x, y) or the id of a point of the sketch.",
|
||||
"The nearest place on the curve already is an anchor.",
|
||||
"The sketch constraints are conflicting, so there is no geometry to edit."},
|
||||
{"Pass the id of a B-spline and a point (x, y) on or near the curve, between two anchors.",
|
||||
"Convert a control-point B-spline first with convert_spline_to_anchors_rsketch.",
|
||||
"Inspect the sketch with inspect_sketch_rsketchresult(..., strict=False) and fix the constraints first."}};
|
||||
return guarded(kSpec, [&] {
|
||||
Sketch updated = SketchAnchors(sketch).insert(spline, at);
|
||||
Value params = Value::object();
|
||||
params.set("sketch_id", updated.sketch_id());
|
||||
params.set("spline", id_of(spline));
|
||||
params.set("at", position_param(at));
|
||||
finalize_sketch_object("insert_spline_anchor_rsketch", std::move(params), {}, updated, &sketch);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
Sketch remove_spline_anchor_rsketch(const Sketch& sketch, const SketchTarget& spline, const SketchTarget& anchor) {
|
||||
static const ErrorSpec kSpec{
|
||||
"remove_spline_anchor_rsketch",
|
||||
"Failed to remove an anchor from the sketch B-spline.",
|
||||
{"The spline id does not exist or is not a B-spline.",
|
||||
"The B-spline is not in anchor form (cubic Bezier spans: inner knots of multiplicity 3).",
|
||||
"The anchor is an end of the spline, a handle, or not a point of the spline.",
|
||||
"The sketch constraints are conflicting, so there is no geometry to edit."},
|
||||
{"Pass the id of a B-spline and the point id of one of its inner anchors.",
|
||||
"Convert a control-point B-spline first with convert_spline_to_anchors_rsketch.",
|
||||
"Inspect the sketch with inspect_sketch_rsketchresult(..., strict=False) and fix the constraints first."}};
|
||||
return guarded(kSpec, [&] {
|
||||
Sketch updated = SketchAnchors(sketch).remove(spline, anchor);
|
||||
Value params = Value::object();
|
||||
params.set("sketch_id", updated.sketch_id());
|
||||
params.set("spline", id_of(spline));
|
||||
params.set("anchor", id_of(anchor));
|
||||
finalize_sketch_object("remove_spline_anchor_rsketch", std::move(params), {}, updated, &sketch);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
Sketch convert_spline_to_anchors_rsketch(const Sketch& sketch, const SketchTarget& spline) {
|
||||
static const ErrorSpec kSpec{
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"Failed to convert the sketch B-spline to anchor form.",
|
||||
{"The spline id does not exist or is not a B-spline.", "The B-spline is periodic.",
|
||||
"The sketch constraints are conflicting, so there is no geometry to convert."},
|
||||
{"Pass the id of an open B-spline (or one that starts and ends on one point).",
|
||||
"Inspect the sketch with inspect_sketch_rsketchresult(..., strict=False) and fix the constraints first."}};
|
||||
return guarded(kSpec, [&] {
|
||||
Sketch updated = SketchAnchors(sketch).convert(spline);
|
||||
Value params = Value::object();
|
||||
params.set("sketch_id", updated.sketch_id());
|
||||
params.set("spline", id_of(spline));
|
||||
finalize_sketch_object("convert_spline_to_anchors_rsketch", std::move(params), {}, updated, &sketch);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace scad
|
||||
@@ -0,0 +1,165 @@
|
||||
// insert_spline_anchor_rsketch, remove_spline_anchor_rsketch and convert_spline_to_anchors_rsketch: the curve stays
|
||||
// where it was, the anchors and handles keep their ids, the refusals name the ids.
|
||||
#include "doctest.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Geom2d_BSplineCurve.hxx>
|
||||
#include <TColStd_Array1OfInteger.hxx>
|
||||
#include <TColStd_Array1OfReal.hxx>
|
||||
#include <TColgp_Array1OfPnt2d.hxx>
|
||||
|
||||
#include "scad/core/error.hpp"
|
||||
#include "scad/sketch/operators.hpp"
|
||||
|
||||
using namespace scad;
|
||||
|
||||
namespace {
|
||||
|
||||
// One anchor-form span from a0 to a1 with the handles h0 and h1.
|
||||
Sketch one_span() {
|
||||
Sketch s = make_sketch_rsketch("anchors");
|
||||
s = add_point_rsketch(s, "a0", 0, 0);
|
||||
s = add_point_rsketch(s, "h0", 10, 10);
|
||||
s = add_point_rsketch(s, "h1", 20, 10);
|
||||
s = add_point_rsketch(s, "a1", 30, 0);
|
||||
return add_bspline_rsketch(s, "s1", "a0", "a1", {"a0", "h0", "h1", "a1"}, 3);
|
||||
}
|
||||
|
||||
std::vector<std::string> pole_ids(const Sketch& s) {
|
||||
std::vector<std::string> out;
|
||||
for (const SketchPole& pole : s.entities().at("s1").bspline().poles)
|
||||
out.push_back(pole.point_id);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Points along the spline s1 of the sketch (its own seeds, which an edit leaves solved).
|
||||
std::vector<gp_Pnt2d> samples(const Sketch& s, int count = 40) {
|
||||
const SketchBSpline spline = s.entities().at("s1").bspline();
|
||||
TColgp_Array1OfPnt2d poles(1, static_cast<int>(spline.poles.size()));
|
||||
for (std::size_t i = 0; i < spline.poles.size(); ++i) {
|
||||
const SketchEntity& point = s.entities().at(spline.poles[i].point_id);
|
||||
poles.SetValue(static_cast<int>(i) + 1, gp_Pnt2d(point.number("x"), point.number("y")));
|
||||
}
|
||||
TColStd_Array1OfReal knots(1, static_cast<int>(spline.knots.size()));
|
||||
TColStd_Array1OfInteger mults(1, static_cast<int>(spline.knots.size()));
|
||||
for (std::size_t i = 0; i < spline.knots.size(); ++i) {
|
||||
knots.SetValue(static_cast<int>(i) + 1, spline.knots[i]);
|
||||
mults.SetValue(static_cast<int>(i) + 1, spline.multiplicities[i]);
|
||||
}
|
||||
const opencascade::handle<Geom2d_BSplineCurve> curve = new Geom2d_BSplineCurve(poles, knots, mults, spline.degree);
|
||||
std::vector<gp_Pnt2d> out;
|
||||
for (int i = 0; i <= count; ++i)
|
||||
out.push_back(
|
||||
curve->Value(curve->FirstParameter() + (curve->LastParameter() - curve->FirstParameter()) * i / count));
|
||||
return out;
|
||||
}
|
||||
|
||||
double gap(const std::vector<gp_Pnt2d>& a, const std::vector<gp_Pnt2d>& b) {
|
||||
double worst = 0.0;
|
||||
for (std::size_t i = 0; i < a.size(); ++i)
|
||||
worst = std::max(worst, a[i].Distance(b[i]));
|
||||
return worst;
|
||||
}
|
||||
|
||||
std::string failure_text(const std::function<void()>& call) {
|
||||
try {
|
||||
call();
|
||||
} catch (const Error& e) {
|
||||
return e.guidance().technical_details;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("insert anchor: the curve does not change, the span's handles keep their ids, three new points") {
|
||||
const Sketch before = one_span();
|
||||
const Sketch after = insert_spline_anchor_rsketch(before, "s1", SketchPosition(12.0, 8.0));
|
||||
CHECK(pole_ids(after) == std::vector<std::string>{"a0", "h0", "p1", "p2", "p3", "h1", "a1"});
|
||||
const SketchBSpline spline = after.entities().at("s1").bspline();
|
||||
CHECK(spline.multiplicities == std::vector<int>{4, 3, 4});
|
||||
CHECK(gap(samples(before), samples(after)) < 1e-9);
|
||||
// the new anchor is on the curve and its handles are on one line with it (the curve is smooth there)
|
||||
const auto xy = [&](const char* id) {
|
||||
return gp_Pnt2d(after.entities().at(id).number("x"), after.entities().at(id).number("y"));
|
||||
};
|
||||
const gp_Vec2d in(xy("p2"), xy("p1"));
|
||||
const gp_Vec2d out(xy("p2"), xy("p3"));
|
||||
CHECK(std::abs(in.Crossed(out)) < 1e-9 * in.Magnitude() * out.Magnitude());
|
||||
}
|
||||
|
||||
TEST_CASE("remove anchor: undoes an insert; the outer handles keep their ids and directions") {
|
||||
const Sketch before = one_span();
|
||||
const Sketch split = insert_spline_anchor_rsketch(before, "s1", SketchPosition(20.0, 7.0));
|
||||
const Sketch merged = remove_spline_anchor_rsketch(split, "s1", "p2");
|
||||
CHECK(pole_ids(merged) == std::vector<std::string>{"a0", "h0", "h1", "a1"});
|
||||
CHECK(gap(samples(before), samples(merged)) < 1e-7);
|
||||
CHECK_FALSE(merged.entities().contains("p1"));
|
||||
CHECK_FALSE(merged.entities().contains("p2"));
|
||||
CHECK_FALSE(merged.entities().contains("p3"));
|
||||
}
|
||||
|
||||
TEST_CASE("remove anchor: an anchor another entity uses stays as a point; constraints on removed points go") {
|
||||
Sketch s = insert_spline_anchor_rsketch(one_span(), "s1", SketchPosition(15.0, 8.0));
|
||||
s = add_point_rsketch(s, "far", 15, 30);
|
||||
s = add_line_rsketch(s, "l0", "p2", "far");
|
||||
s = constrain_fix_rsketch(s, "p3");
|
||||
const Sketch after = remove_spline_anchor_rsketch(s, "s1", "p2");
|
||||
CHECK(after.entities().contains("p2"));
|
||||
CHECK_FALSE(after.entities().contains("p3"));
|
||||
CHECK(after.constraints().empty());
|
||||
}
|
||||
|
||||
TEST_CASE("anchors: refusals name the ids") {
|
||||
const Sketch split = insert_spline_anchor_rsketch(one_span(), "s1", SketchPosition(15.0, 8.0));
|
||||
CHECK(failure_text([&] { remove_spline_anchor_rsketch(split, "s1", "a0"); }).find("is an end of 's1'") !=
|
||||
std::string::npos);
|
||||
CHECK(failure_text([&] { remove_spline_anchor_rsketch(split, "s1", "p1"); }).find("is a handle of 's1'") !=
|
||||
std::string::npos);
|
||||
CHECK(failure_text([&] { remove_spline_anchor_rsketch(one_span(), "s1", "zz"); }).find("only its two end anchors") !=
|
||||
std::string::npos);
|
||||
CHECK(failure_text([&] { insert_spline_anchor_rsketch(split, "s1", "p2"); }).find("already has an anchor there") !=
|
||||
std::string::npos);
|
||||
Sketch control = make_sketch_rsketch("control");
|
||||
for (int i = 0; i < 5; ++i)
|
||||
control = add_point_rsketch(control, "q" + std::to_string(i), 5.0 * i, i % 2 == 0 ? 0.0 : 8.0);
|
||||
control = add_bspline_rsketch(control, "s1", "q0", "q4", {"q0", "q1", "q2", "q3", "q4"}, 3);
|
||||
CHECK(failure_text([&] {
|
||||
insert_spline_anchor_rsketch(control, "s1", SketchPosition(10.0, 4.0));
|
||||
}).find("convert_spline_to_anchors_rsketch") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("convert: a control-point B-spline keeps its curve and becomes Bezier spans") {
|
||||
Sketch control = make_sketch_rsketch("control");
|
||||
for (int i = 0; i < 5; ++i)
|
||||
control = add_point_rsketch(control, "q" + std::to_string(i), 5.0 * i, i % 2 == 0 ? 0.0 : 8.0);
|
||||
control = add_bspline_rsketch(control, "s1", "q0", "q4", {"q0", "q1", "q2", "q3", "q4"}, 3);
|
||||
const Sketch after = convert_spline_to_anchors_rsketch(control, "s1");
|
||||
const SketchBSpline spline = after.entities().at("s1").bspline();
|
||||
CHECK(spline.multiplicities == std::vector<int>{4, 3, 4});
|
||||
CHECK(pole_ids(after).front() == "q0");
|
||||
CHECK(pole_ids(after).back() == "q4");
|
||||
CHECK(gap(samples(control), samples(after)) < 1e-9);
|
||||
// already in anchor form: nothing changes
|
||||
CHECK(pole_ids(convert_spline_to_anchors_rsketch(after, "s1")) == pole_ids(after));
|
||||
}
|
||||
|
||||
TEST_CASE("trim keeps the anchor form: the cut piece is still Bezier spans") {
|
||||
Sketch s = insert_spline_anchor_rsketch(one_span(), "s1", SketchPosition(15.0, 8.0));
|
||||
s = add_point_rsketch(s, "t0", 25, -5);
|
||||
s = add_point_rsketch(s, "t1", 25, 20);
|
||||
s = add_line_rsketch(s, "cut", "t0", "t1");
|
||||
const Sketch after = trim_rsketch(s, "s1", SketchPosition(29.0, 1.0));
|
||||
const SketchEntity* piece = nullptr;
|
||||
for (const auto& [id, entity] : after.entities())
|
||||
if (entity.kind == "bspline")
|
||||
piece = &entity;
|
||||
REQUIRE(piece != nullptr);
|
||||
const SketchBSpline spline = piece->bspline();
|
||||
CHECK(spline.degree == 3);
|
||||
CHECK(spline.multiplicities == std::vector<int>{4, 3, 4});
|
||||
}
|
||||
@@ -337,6 +337,9 @@ from simplecadapi._cpp import (
|
||||
fillet_corner_rsketch,
|
||||
project_rsketch,
|
||||
trim_rsketch,
|
||||
insert_spline_anchor_rsketch,
|
||||
remove_spline_anchor_rsketch,
|
||||
convert_spline_to_anchors_rsketch,
|
||||
constrain_mirror_rsketch,
|
||||
constrain_symmetric_rsketch,
|
||||
constrain_tangent_rsketch,
|
||||
@@ -707,6 +710,9 @@ __all__ = [
|
||||
"inspect_sketch_rsketchcrossings",
|
||||
"trim_rsketch",
|
||||
"extend_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"diff_sketch_rsketchdiff",
|
||||
"fillet_corner_rsketch",
|
||||
"chamfer_corner_rsketch",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -331,6 +331,9 @@
|
||||
"transform_rsolid": "Apply a finite nonsingular 4x4 affine matrix in the current coordinate system.\n\nThe matrix may include shear, reflection and nonuniform scale. Perspective\nmatrices and singular maps cannot define a solid and are rejected. The\ninput geometry stays unchanged. The operation is recorded as\n``make_transform_rsolid`` for graph replay. The recorded node carries the kernel's face and edge history, so element\nreferences follow faces through it;\ntag lineage on the result is partial.\n\nArgs:\n solid: The solid to transform.\n matrix: A 4x4 affine matrix (row-major, last row ``0 0 0 1``), finite\n and nonsingular, in current coordinate-system coordinates.\n\nReturns:\n The transformed solid.\n\nRaises:\n ValueError: The matrix is not a finite 4x4 affine matrix, is singular\n or a perspective map, or the kernel could not transform the solid.",
|
||||
"translate_shape": "Translate a shape by an offset vector.",
|
||||
"trim_rsketch": "Remove the part of a line, circle, arc or B-spline that contains ``at``, between the nearest cuts.\n\nA cut is a crossing with another non-construction line, circle, arc, ellipse or B-spline (``against`` limits\nwhich ones) or an end of the entity; a tangent touch is one cut. ``at`` is a point (x, y) in sketch coordinates\nor a point id. Lines, arcs and open B-splines keep the pieces on either side; a circle keeps the arc left over and\na closed B-spline (periodic, or starting and ending on one point) the piece left over (both need two cuts); an\nentity nothing crosses is removed whole. A B-spline piece is a new B-spline (ids s1, s2, ...) of the same curve:\nits first and last control points are its end points, its inner control points are sketch points (an original\ncontrol point the piece keeps unmoved keeps its id, the others are new points p1, p2, ...), and its knots are no\nlonger uniform. Cut points are tied to the cutter with point_on; line pieces inherit horizontal/vertical;\nconstraints on an end point stay with the piece that keeps that point, a tangent at a B-spline end (at_a/at_b)\nmoves to the piece that keeps that end, other constraints that name the removed entity are removed, and so are\nthe original control points no piece uses, with their constraints. Use diff_sketch_rsketchdiff(before, after) to\nsee what changed.",
|
||||
"insert_spline_anchor_rsketch": "Insert an anchor into a B-spline in anchor form, at the curve point nearest ``at``, without changing the curve.\n\nThe anchor form is a pen tool's curve: anchors on the curve, each with an in-handle and an out-handle. It is a cubic\nB-spline whose control points are ``[A0, out0, in1, A1, out1, in2, A2, ...]`` (every one a sketch point) and whose\ninner knots have multiplicity 3, so every span is a cubic Bezier from one anchor to the next; the editor's spline tool\ndraws them, ``convert_spline_to_anchors_rsketch`` turns another B-spline into one. Moving an anchor or a handle is\nmoving its point (the solver moves every control point of such a spline).\n\nThe span under ``at`` is split at that place (de Casteljau), so the curve is the same: the span's two handles get\nshorter (they keep their ids; a dimension or fix on them no longer holds and is dropped, see the notes) and the new\nanchor and its two handles are new points ``p<n>`` (the lowest free numbers). The new knot is the curve parameter of\nthe place, with multiplicity 3. ``at`` is a point (x, y) in sketch coordinates or a point id. The sketch is solved\nfirst. Refused for a B-spline that is not in anchor form and at an existing anchor. Metadata ``last_edit`` notes name\nthe new anchor and its handles; ``diff_sketch_rsketchdiff(before, after)`` lists them too.",
|
||||
"remove_spline_anchor_rsketch": "Remove an inner anchor (and its two handles) from a B-spline in anchor form.\n\n``anchor`` is the point id of an anchor that is not an end. The spans on either side become one span: its handles are\nthe outer handles of the two spans, which keep their ids and directions and get the lengths that fit the old curve best\n(least squares, never reversed), so removing an anchor that ``insert_spline_anchor_rsketch`` made gives back the curve\nit split. A handle that a constraint or another entity holds keeps its place. The removed points are deleted unless\nanother entity uses them, and the constraints on deleted points are dropped (the notes of metadata ``last_edit`` name\nthem). Refused for an end anchor, a handle, a point that is not on the spline, and a B-spline not in anchor form.",
|
||||
"convert_spline_to_anchors_rsketch": "Write a B-spline in anchor form (Bezier spans: anchors on the curve, a handle on each side).\n\nA non-rational B-spline of degree 3 or less keeps its exact shape (degree elevation and knot insertion); a rational one\nor one of a higher degree is approximated within 1e-4 and the notes of metadata ``last_edit`` say how close. The end\npoints keep their ids; an inner control point that does not move keeps its id, the others are new points ``p<n>``, and\ncontrol points no entity uses any more are deleted with their constraints. A B-spline already in anchor form is left\nas it is (a note says so). Refused for a periodic B-spline. See ``insert_spline_anchor_rsketch`` for the form.",
|
||||
"trim_surface_face": "Project 3D wires onto a carrier and return one trimmed face.",
|
||||
"trim_surface_rface": "Trim a carrier Face to exactly one connected Face.\n\nExisting carrier bounds and holes are preserved by intersecting them with\nthe requested closed, simple outer loop and optional closed, simple holes.\nEmpty or disconnected intersections are rejected. Every trim curve must\nlie on the carrier within ``tolerance``. Periodic carriers do not support\nholes; their outer loop must fit within one seam period without crossing\nthe seam.",
|
||||
"twisted_sweep_rsolid": "Sweep a planar profile along a straight axis with linear rotation.\n\n``twist_angle`` is the signed total rotation in degrees. The operation uses\na cylindrical auxiliary spine to define a continuous rotation law, yielding\none continuous side face per profile edge instead of a segmented ruled loft.",
|
||||
|
||||
@@ -485,6 +485,9 @@
|
||||
"translate_shape_ocp": "simplecadapi.kernel.ocp_transforms",
|
||||
"translate_z_placement": "simplecadapi.product.placement",
|
||||
"trim_rsketch": "simplecadapi.operators.sketch",
|
||||
"insert_spline_anchor_rsketch": "simplecadapi.operators.sketch",
|
||||
"remove_spline_anchor_rsketch": "simplecadapi.operators.sketch",
|
||||
"convert_spline_to_anchors_rsketch": "simplecadapi.operators.sketch",
|
||||
"trim_surface_face": "simplecadapi.kernel.ocp_surfaces",
|
||||
"trim_surface_rface": "simplecadapi.operators.geometry",
|
||||
"twisted_sweep_rsolid": "simplecadapi.operators.features",
|
||||
|
||||
@@ -201,7 +201,9 @@ def _configure_features(subparsers: argparse._SubParsersAction) -> None:
|
||||
description="A sketch feature is a document (plane, points, entities, constraints) inside a cell. `op` applies one edit "
|
||||
"operation to it (a pure function of the document: ids are deterministic and the answer lists what was created, removed "
|
||||
"and dropped) and writes the result back; `--dry-run` only prints it. Operations: trim {entity, at:[x,y], against?}, "
|
||||
"extend {entity, end:start|end, to?}; each is the SDK function of the same name (scad.trim_rsketch, scad.extend_rsketch), which "
|
||||
"extend {entity, end:start|end, to?}, fillet_corner, chamfer_corner, project, insert_spline_anchor {spline, at:[x,y]}, "
|
||||
"remove_spline_anchor {spline, anchor}, convert_spline_to_anchors {spline}; each is the SDK function of the same name "
|
||||
"(scad.trim_rsketch, scad.insert_spline_anchor_rsketch, ...), which "
|
||||
"an agent can equally call in a notebook cell.",
|
||||
)
|
||||
ssub = sketch.add_subparsers(dest="sketch_command", required=True)
|
||||
|
||||
@@ -57,7 +57,6 @@ _DIR_OPTIONS = [
|
||||
{"value": "-normal", "label": "against the normal of the sketch plane"},
|
||||
]
|
||||
_PLANE_NORMALS = {"XY": (0.0, 0.0, 1.0), "XZ": (0.0, 1.0, 0.0), "YZ": (1.0, 0.0, 0.0)}
|
||||
_PLANE_OPTIONS = [{"value": key, "label": key} for key in _PLANE_NORMALS]
|
||||
|
||||
|
||||
class FeatureError(ValueError):
|
||||
@@ -389,85 +388,12 @@ def _cone(c: Context) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def _extrude_rect(c: Context) -> list[str]:
|
||||
return [
|
||||
f"_profile = scad.make_rectangle_rface(width={c.var('width')}, height={c.var('height')}, center={c.point('center')}, normal={c.normal('plane')})",
|
||||
f"{c.out} = scad.extrude_rsolid(",
|
||||
f" profile=_profile, direction={c.normal('plane')}, distance={c.var('distance')},",
|
||||
f" start_face_tag={c.tag('start')}, end_face_tag={c.tag('end')}, side_faces_tag={c.tag('side')},",
|
||||
")",
|
||||
]
|
||||
|
||||
|
||||
def _extrude_circle(c: Context) -> list[str]:
|
||||
return [
|
||||
f"_profile = scad.make_circle_rface(center={c.point('center')}, radius={c.var('radius')}, normal={c.normal('plane')})",
|
||||
f"{c.out} = scad.extrude_rsolid(",
|
||||
f" profile=_profile, direction={c.normal('plane')}, distance={c.var('distance')},",
|
||||
f" start_face_tag={c.tag('start')}, end_face_tag={c.tag('end')}, side_faces_tag={c.tag('side')},",
|
||||
")",
|
||||
]
|
||||
|
||||
|
||||
def _points(values: Mapping[str, Any]) -> list[tuple[float, float]]:
|
||||
return [(float(x), float(y)) for x, y in values["points"]]
|
||||
|
||||
|
||||
def _extrude_polygon(c: Context) -> list[str]:
|
||||
pts = ", ".join(f"({_num(x)}, {_num(y)}, 0.0)" for x, y in _points(c.values))
|
||||
return [
|
||||
f"_outline = scad.make_polyline_rwire(points=[{pts}], closed=True)",
|
||||
"_profile = scad.make_face_from_wire_rface(wire=_outline, normal=(0.0, 0.0, 1.0))",
|
||||
f"{c.out} = scad.extrude_rsolid(",
|
||||
f" profile=_profile, direction=(0.0, 0.0, 1.0), distance={c.var('distance')},",
|
||||
f" start_face_tag={c.tag('start')}, end_face_tag={c.tag('end')}, side_faces_tag={c.tag('side')},",
|
||||
")",
|
||||
]
|
||||
|
||||
|
||||
def _revolve(c: Context) -> list[str]:
|
||||
return [
|
||||
"# the section sits in the XZ plane, beside the Z axis, and turns about it",
|
||||
f"_profile = scad.make_rectangle_rface(width={c.var('width')}, height={c.var('height')},",
|
||||
f" center=({c.var('offset')} + {c.var('width')} / 2, 0.0, {c.var('height')} / 2), normal=(0.0, 1.0, 0.0))",
|
||||
f"{c.out} = scad.revolve_rsolid(profile=_profile, axis=(0.0, 0.0, 1.0), angle={c.var('angle')}, origin=(0.0, 0.0, 0.0),",
|
||||
# a full turn has no start or end face to name; those tags are written only for a partial turn
|
||||
" " + (f"start_face_tag={c.tag('start')}, end_face_tag={c.tag('end')}, " if c.values["angle"] < 360 else "") + f"side_faces_tag={c.tag('side')})",
|
||||
]
|
||||
|
||||
|
||||
def _loft_circles(c: Context) -> list[str]:
|
||||
return [
|
||||
"_bottom = scad.make_circle_rwire(center=(0.0, 0.0, 0.0), radius=" + c.var("bottom_radius") + ", normal=(0.0, 0.0, 1.0))",
|
||||
"_top = scad.make_circle_rwire(center=(0.0, 0.0, " + c.var("height") + "), radius=" + c.var("top_radius") + ", normal=(0.0, 0.0, 1.0))",
|
||||
f"{c.out} = scad.loft_rsolid(profiles=[_bottom, _top], ruled={c.var('ruled')},",
|
||||
f" start_face_tag={c.tag('start')}, end_face_tag={c.tag('end')}, side_faces_tag={c.tag('side')})",
|
||||
]
|
||||
|
||||
|
||||
def _loft_rects(c: Context) -> list[str]:
|
||||
return [
|
||||
f"_bottom = scad.make_rectangle_rwire(width={c.var('bottom_width')}, height={c.var('bottom_height')}, center=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0))",
|
||||
f"_top = scad.make_rectangle_rwire(width={c.var('top_width')}, height={c.var('top_height')}, center=(0.0, 0.0, {c.var('height')}), normal=(0.0, 0.0, 1.0))",
|
||||
f"{c.out} = scad.loft_rsolid(profiles=[_bottom, _top], ruled={c.var('ruled')},",
|
||||
f" start_face_tag={c.tag('start')}, end_face_tag={c.tag('end')}, side_faces_tag={c.tag('side')})",
|
||||
]
|
||||
|
||||
|
||||
def _sweep(c: Context) -> list[str]:
|
||||
pts = [(float(x), float(y), float(z)) for x, y, z in c.values["path"]]
|
||||
path = ", ".join(f"({_num(x)}, {_num(y)}, {_num(z)})" for x, y, z in pts)
|
||||
return [
|
||||
f"_path = scad.make_polyline_rwire(points=[{path}], closed=False)",
|
||||
"# the circle stands on the first point, square to the first segment",
|
||||
f"_a, _b = {pts[0]!r}, {pts[1]!r}",
|
||||
"_dir = tuple(_q - _p for _p, _q in zip(_a, _b))",
|
||||
"_len = sum(_d * _d for _d in _dir) ** 0.5",
|
||||
"_dir = tuple(_d / _len for _d in _dir)",
|
||||
f"_profile = scad.make_circle_rface(center=_a, radius={c.var('radius')}, normal=_dir)",
|
||||
f"{c.out} = scad.sweep_rsolid(profile=_profile, path=_path, is_frenet=False,",
|
||||
f" start_face_tag={c.tag('start')}, end_face_tag={c.tag('end')}, side_faces_tag={c.tag('side')})",
|
||||
]
|
||||
|
||||
|
||||
def _sketch(c: Context) -> list[str]:
|
||||
@@ -642,14 +568,22 @@ _WORKPLANE_METHODS = [
|
||||
{"value": "midplane", "label": "halfway between two parallel faces"},
|
||||
{"value": "points", "label": "through three vertices"},
|
||||
{"value": "axis", "label": "through an edge, turned about it"},
|
||||
{"value": "offset", "label": "moved and turned from a plane, a workplane or a face"},
|
||||
]
|
||||
_NAMED_PLANES = ("XY", "XZ", "YZ")
|
||||
_OFFSET = {"method": ["offset"]}
|
||||
_ON_FACE = {"method": ["face", "face_edge"]}
|
||||
|
||||
|
||||
def _workplane(c: Context) -> list[str]:
|
||||
"""A workplane from picked geometry: one recorded SDK constructor per way of picking (see make_workplane_*)."""
|
||||
"""A workplane from picked geometry: one recorded SDK constructor per way of picking (see make_workplane_*), or one
|
||||
placed by hand on a plane, a workplane or a face (``make_workplane_offset_rworkplane``: the editor's handles)."""
|
||||
method = c.choice("method")
|
||||
c.body("body")
|
||||
base = str(c.values.get("base") or "XY")
|
||||
if method != "offset" or base == "face":
|
||||
if not c.values.get("body"):
|
||||
raise FeatureError("this workplane is made from the model's geometry: there is no body yet")
|
||||
c.body("body")
|
||||
lines: list[str] = []
|
||||
|
||||
def pick(slot: str) -> str:
|
||||
@@ -658,7 +592,20 @@ def _workplane(c: Context) -> list[str]:
|
||||
lines.append(f"{name} = {name}.resolve({{BODY}})[0]")
|
||||
return name
|
||||
|
||||
if method in ("face", "face_edge"):
|
||||
if method == "offset":
|
||||
if base in _NAMED_PLANES:
|
||||
on = repr(base)
|
||||
elif base == "face":
|
||||
# the face's frame with the x direction the handles were drawn with, so the plane made is the one shown
|
||||
x_dir = f", x_dir={c.point('x_dir')}" if c.values.get("x_dir") else ""
|
||||
on = f"scad.make_workplane_from_face_rworkplane({pick('face')}{x_dir})"
|
||||
elif _NAME.fullmatch(base):
|
||||
on = c.body_named(base)
|
||||
else:
|
||||
raise FeatureError(f"Base: {base!r} is not XY, XZ, YZ, a picked face or a workplane of this notebook")
|
||||
call = (f"scad.make_workplane_offset_rworkplane({on}, offset={c.point('move')}, "
|
||||
f"rx={c.var('rx')}, ry={c.var('ry')}, rz={c.var('rz')})")
|
||||
elif method in ("face", "face_edge"):
|
||||
face = pick("face")
|
||||
x_edge = f", x_edge={pick('edge')}" if method == "face_edge" else ""
|
||||
call = f"scad.make_workplane_from_face_rworkplane({face}{x_edge}, offset={c.var('offset')}, flip={c.var('flip')})"
|
||||
@@ -674,7 +621,6 @@ def _workplane(c: Context) -> list[str]:
|
||||
|
||||
|
||||
_AXIS = lambda name, label, default="+z": _enum(name, label, _AXIS_OPTIONS, default) # noqa: E731
|
||||
_PLANE = lambda: _enum("plane", "Sketch plane", _PLANE_OPTIONS, "XY", help="The profile lies in this plane and is pushed along its normal.") # noqa: E731
|
||||
_PROFILE = lambda: Slot("profile", "Sketch profile", "profile", help="A sketch made earlier.") # noqa: E731
|
||||
_BODY = lambda: _body("body", "Body", "The body this feature works on (default: the last one made).") # noqa: E731
|
||||
|
||||
@@ -690,27 +636,7 @@ SPECS: tuple[Spec, ...] = (
|
||||
Spec("cone", "Cone / frustum", "Primitives", "build", "solid", "A cone, or a frustum when the top radius is above zero.",
|
||||
(_length("bottom_radius", "Bottom radius", 15.0), Slot("top_radius", "Top radius", "length", default=0.0, unit="mm", min=0.0),
|
||||
_length("height", "Height", 25.0), _point("origin", "Bottom face centre"), _AXIS("axis", "Axis")), _cone),
|
||||
Spec("extrude_rect", "Extrude rectangle", "Profiles", "build", "solid", "A rectangle pushed along the normal of its plane.",
|
||||
(_PLANE(), _length("width", "Width", 40.0), _length("height", "Height", 20.0), _point("center", "Centre"), _signed("distance", "Distance", 10.0, min=0.001)), _extrude_rect),
|
||||
Spec("extrude_circle", "Extrude circle", "Profiles", "build", "solid", "A circle pushed along the normal of its plane.",
|
||||
(_PLANE(), _length("radius", "Radius", 12.0), _point("center", "Centre"), _signed("distance", "Distance", 10.0, min=0.001)), _extrude_circle),
|
||||
Spec("extrude_polygon", "Extrude polygon", "Profiles", "build", "solid", "A closed polygon in the XY plane pushed up the Z axis.",
|
||||
(Slot("points", "Corners (x, y per line)", "points2d", default=[[0, 0], [40, 0], [40, 20], [20, 30], [0, 20]], unit="mm"),
|
||||
_signed("distance", "Distance", 10.0, min=0.001)), _extrude_polygon),
|
||||
Spec("revolve", "Revolve", "Profiles", "build", "solid", "A rectangle beside the Z axis, turned about it.",
|
||||
(_length("width", "Section width", 10.0), _length("height", "Section height", 25.0),
|
||||
Slot("offset", "Distance from the axis", "length", default=10.0, unit="mm", min=0.0),
|
||||
Slot("angle", "Angle", "angle", default=360.0, unit="deg", min=1.0, max=360.0)), _revolve),
|
||||
Spec("loft_circles", "Loft circles", "Profiles", "build", "solid", "A solid between two circles, one above the other.",
|
||||
(_length("bottom_radius", "Bottom radius", 15.0), _length("top_radius", "Top radius", 8.0), _length("height", "Height", 25.0),
|
||||
Slot("ruled", "Straight sides", "bool", default=False)), _loft_circles),
|
||||
Spec("loft_rects", "Loft rectangles", "Profiles", "build", "solid", "A solid between two rectangles, one above the other.",
|
||||
(_length("bottom_width", "Bottom width", 30.0), _length("bottom_height", "Bottom height", 20.0),
|
||||
_length("top_width", "Top width", 15.0), _length("top_height", "Top height", 10.0), _length("height", "Height", 25.0),
|
||||
Slot("ruled", "Straight sides", "bool", default=True)), _loft_rects),
|
||||
Spec("sweep_circle", "Sweep circle along a path", "Profiles", "build", "solid", "A circle swept along a polyline.",
|
||||
(_length("radius", "Radius", 4.0), Slot("path", "Path points (x, y, z per line)", "points3d", default=[[0, 0, 0], [0, 0, 30], [30, 0, 60]], unit="mm")), _sweep),
|
||||
Spec("sketch", "Sketch", "Sketch", "build, profile=sketch", "face", "A constrained 2D sketch on a plane, made into a face.",
|
||||
Spec("sketch", "Sketch", "Sketch", "build, profile=sketch", "face", "A constrained 2D sketch on a plane, made into a face (a closed profile) or a wire (a profile or an open path).",
|
||||
(Slot("sketch", "Sketch", "sketch", default={"plane": "XY", "points": [], "entities": [], "constraints": [], "profile": 0}),), _sketch),
|
||||
Spec("extrude_sketch", "Extrude sketch", "Sketch", "build", "solid", "Push a sketch face along a direction.",
|
||||
(_PROFILE(), _enum("direction", "Direction", _DIR_OPTIONS, "normal"), _signed("distance", "Distance", 10.0, min=0.001)), _extrude_sketch),
|
||||
@@ -730,7 +656,7 @@ SPECS: tuple[Spec, ...] = (
|
||||
(_body("base", "First body"), _body("other", "Second body")), _intersect),
|
||||
Spec("hole", "Hole", "Features", "subtract", "solid", "A round hole from a point on a surface, in a direction, to a depth.",
|
||||
(_BODY(), _point("position", "Start point (on the surface)", help="Pick a face to fill the point and direction."),
|
||||
_enum("direction", "Direction into the material", _HOLE_DIRECTIONS, "-z", help="An axis, the normal of the face you picked (into the material), or any vector."),
|
||||
_enum("direction", "Direction into the material", _HOLE_DIRECTIONS, "face", help="An axis, the normal of the face you picked (into the material), or any vector."),
|
||||
*(Slot(name, label, "float", default=default, min=-1000.0, max=1000.0, show_when=_HOLE_VECTOR)
|
||||
for name, label, default in (("dx", "Direction x", 0.0), ("dy", "Direction y", 0.0), ("dz", "Direction z", -1.0))),
|
||||
_length("diameter", "Diameter", 6.0), _length("depth", "Depth", 10.0)), _hole),
|
||||
@@ -760,9 +686,12 @@ SPECS: tuple[Spec, ...] = (
|
||||
(_BODY(), Slot("factor", "Factor", "float", default=1.5, min=0.01, max=100.0), _point("origin", "Centre")), _scale),
|
||||
Spec("workplane", "Workplane", "Datums", "datum", "workplane",
|
||||
"A workplane from picked geometry: on a planar face (x along an edge if one is picked, an offset along the normal), "
|
||||
"halfway between two parallel faces, through three vertices, or through an edge turned about it. Sketch on it, "
|
||||
"halfway between two parallel faces, through three vertices, or through an edge turned about it; or placed by hand "
|
||||
"(moved and turned with the handles) on XY / XZ / YZ, another workplane or a face. Sketch on it, "
|
||||
"or place features in it with `with wp:`.",
|
||||
(_BODY(), _enum("method", "From", _WORKPLANE_METHODS, "face"),
|
||||
(dataclasses.replace(_BODY(), optional=True), _enum("method", "From", _WORKPLANE_METHODS, "face"),
|
||||
Slot("base", "Base", "text", default="XY", show_when=_OFFSET,
|
||||
help="XY, XZ or YZ, the name of a workplane of the notebook, or face (the picked face)."),
|
||||
Slot("face", "Face", "select", entity="face", single=True, optional=True,
|
||||
show_when={"method": ["face", "face_edge", "midplane", "axis"]},
|
||||
help="A planar face (for an axis: the face the plane starts from)."),
|
||||
@@ -776,7 +705,12 @@ SPECS: tuple[Spec, ...] = (
|
||||
_signed("offset", "Offset along the normal", 0.0, show_when=_ON_FACE),
|
||||
Slot("flip", "Flip the normal", "bool", default=False, show_when=_ON_FACE),
|
||||
Slot("angle", "Angle about the edge", "angle", default=0.0, unit="deg", min=-360.0, max=360.0,
|
||||
show_when={"method": ["axis"]})), _workplane),
|
||||
show_when={"method": ["axis"]}),
|
||||
Slot("x_dir", "x direction on the face", "point", default=None, unit=None, optional=True, show_when=_OFFSET),
|
||||
dataclasses.replace(_point("move", "Move", help="The origin's offset along the base's own x, y and normal (mm)."),
|
||||
show_when=_OFFSET),
|
||||
*(Slot(axis, f"Turn about {label}", "angle", default=0.0, unit="deg", min=-360.0, max=360.0, show_when=_OFFSET)
|
||||
for axis, label in (("rx", "x"), ("ry", "y"), ("rz", "the normal")))), _workplane),
|
||||
)
|
||||
|
||||
_COMBINE_OPTIONS = [
|
||||
@@ -785,7 +719,7 @@ _COMBINE_OPTIONS = [
|
||||
{"value": "intersect", "label": "Intersect"},
|
||||
{"value": "new", "label": "New body"},
|
||||
]
|
||||
_COMBINABLE = frozenset({"box", "cylinder", "sphere", "cone", "extrude_rect", "extrude_circle", "extrude_polygon", "revolve", "loft_circles", "loft_rects", "sweep_circle", "extrude_sketch", "revolve_sketch", "extrude_face"})
|
||||
_COMBINABLE = frozenset({"box", "cylinder", "sphere", "cone", "extrude_sketch", "revolve_sketch", "extrude_face"})
|
||||
_COMBINE_ROLE = {"new": "build", "join": "add", "cut": "subtract", "intersect": "intersect"}
|
||||
|
||||
|
||||
@@ -851,7 +785,7 @@ def catalog() -> dict[str, Any]:
|
||||
|
||||
|
||||
def default_slug(spec_id: str, taken: set[str]) -> str:
|
||||
base = {"extrude_rect": "block", "extrude_circle": "disc", "extrude_polygon": "profile_solid", "workplane": "wp"}.get(spec_id, spec_id)
|
||||
base = {"workplane": "wp"}.get(spec_id, spec_id)
|
||||
if base.startswith("op."): # an SDK operation: what it makes (make_spur_gear_rsolid -> spur_gear)
|
||||
base = re.sub(r"^(make|add|create)_", "", base[3:].rsplit("_r", 1)[0]) or "shape"
|
||||
candidate, number = base, 1
|
||||
@@ -908,8 +842,9 @@ def check_values(spec: Spec, values: Mapping[str, Any], bodies: Mapping[str, str
|
||||
raise FeatureError(f"{slot.label}: three numbers (x, y, z)")
|
||||
clean[slot.name] = [_checked_number(Slot(slot.name, slot.label, "float", min=slot.min, max=slot.max), part) for part in raw]
|
||||
elif slot.kind in ("body", "profile"):
|
||||
if slot.optional and clean.get("operation", "new") == "new":
|
||||
continue # nothing to combine with
|
||||
combining = any(other.name == "operation" for other in spec.slots)
|
||||
if slot.optional and ((combining and clean.get("operation", "new") == "new") or (not combining and raw is None)):
|
||||
continue # nothing to combine with (or, for an optional body, none given)
|
||||
if raw is None and slot.optional:
|
||||
raise FeatureError("there is no body to combine with: choose 'New body' to start one")
|
||||
name = str(raw)
|
||||
@@ -1171,7 +1106,7 @@ def render_feature(
|
||||
feature="\n".join(feature_lines),
|
||||
before=ctx.before,
|
||||
reads=ctx.reads,
|
||||
produces=spec.produces,
|
||||
produces=sketch_doc.output_of(clean["sketch"]) if spec.id == "sketch" else spec.produces,
|
||||
gui=gui,
|
||||
)
|
||||
|
||||
|
||||
@@ -106,6 +106,8 @@ class FeatureService:
|
||||
if head.role != "datum": # a workplane on a body's face is not built from the body: the body stays open
|
||||
consumed.update(loaded & set(bodies))
|
||||
produces = F.BY_ID[gui["spec"]].produces if gui else "solid"
|
||||
if gui and gui["spec"] == "sketch": # a sketch makes a face or a wire, as its document says
|
||||
produces = sketch_doc.output_of(gui.get("values", {}).get("sketch") or {})
|
||||
part_of = head.slug[: -len("_parts")] if head.slug.endswith("_parts") and head.slug[: -len("_parts")] in assembly_slugs else None
|
||||
made = defined if head.role in _ROLES_WITH_BODIES and not part_of else []
|
||||
for name in made:
|
||||
@@ -136,7 +138,7 @@ class FeatureService:
|
||||
profiles = []
|
||||
for feature in features:
|
||||
gui = feature["gui"]
|
||||
if gui and gui["spec"] == "sketch" and feature["makes"]:
|
||||
if gui and gui["spec"] == "sketch" and feature["makes"] and sketch_doc.output_of(gui["values"].get("sketch") or {}) == "face":
|
||||
plane = (gui["values"].get("sketch") or {}).get("plane", "XY")
|
||||
profiles.append(
|
||||
{
|
||||
@@ -233,11 +235,12 @@ class FeatureService:
|
||||
params_anchor = self._params_anchor(cells)
|
||||
feature_anchor = request.get("after") or self._feature_anchor(snap, cells)
|
||||
if rendered.params:
|
||||
steps.append(self._create(params_anchor, "\n".join(rendered.params), run=False))
|
||||
# run now: the feature cell below reads these names, and a cell never run defines nothing (NameError)
|
||||
steps.append(self._create(params_anchor, "\n".join(rendered.params), run=True))
|
||||
if feature_anchor == params_anchor: # the params cell sits where the feature goes: keep params first
|
||||
feature_anchor = steps[-1]["id"]
|
||||
for code in rendered.before:
|
||||
before = self._create(feature_anchor, code, run=False)
|
||||
before = self._create(feature_anchor, code, run=True)
|
||||
steps.append(before)
|
||||
feature_anchor = before["id"]
|
||||
made = self._create(feature_anchor, rendered.feature, run=True)
|
||||
|
||||
@@ -12,6 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
from collections import Counter
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
@@ -60,6 +61,10 @@ _GROUPS = {
|
||||
}
|
||||
|
||||
|
||||
_MAKES = {"edge": "curve (edge)", "wire": "wire", "face": "face", "shell": "surface", "solid": "solid", "solids": "solids"}
|
||||
"""How a label names what an operation makes, where two operations share a name."""
|
||||
|
||||
|
||||
def _label(name: str) -> str:
|
||||
return name.replace("_", " ").strip().capitalize()
|
||||
|
||||
@@ -225,7 +230,13 @@ def operation_specs() -> tuple[Any, ...]:
|
||||
spec = _spec_for(op, features)
|
||||
if spec is not None:
|
||||
out.append(spec)
|
||||
return tuple(out)
|
||||
# Operations that differ only in what they make (loft_rsolid / loft_rshell, make_circle_redge / _rwire / _rface)
|
||||
# would read as one: their labels say what each makes.
|
||||
count = Counter(spec.label for spec in out)
|
||||
return tuple(
|
||||
dataclasses.replace(spec, label=f"{spec.label} → {_MAKES.get(spec.produces, spec.produces)}") if count[spec.label] > 1 else spec
|
||||
for spec in out
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["PREFIX", "operation_specs"]
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
"""The sketch document a 2D canvas edits, the cell code it becomes, and the solve a canvas asks for while a point is dragged.
|
||||
|
||||
A document is plain data: a plane, points (their coordinates are solver seeds), entities (line, circle, arc) that name
|
||||
points, constraints that name entities or points, and which profile of the solved sketch becomes the face::
|
||||
points, constraints that name entities or points, and which profile of the solved sketch becomes the face (or, with
|
||||
``"output": "wire"``, the wire: a closed loop or an open chain, for a sweep path or a loft section)::
|
||||
|
||||
{"plane": "XY",
|
||||
"points": [{"id": "a", "x": 0, "y": 0}, ...],
|
||||
"entities": [{"id": "l0", "kind": "line", "start": "a", "end": "b", "construction": false}, ...],
|
||||
"constraints": [{"id": "c1", "kind": "horizontal", "targets": ["l0"]},
|
||||
{"id": "c2", "kind": "length", "targets": ["l0"], "value": 40.0}, ...],
|
||||
"profile": 0, "inner": [], "fully_constrained": true}
|
||||
"profile": 0, "inner": [], "fully_constrained": true, "output": "face"}
|
||||
|
||||
:func:`validate` checks it (every id that reaches code matches a fixed pattern, every number is finite), :func:`render` writes
|
||||
the sketch cell (dimensions become ``scad.var`` sliders in the params cell), and :func:`solve` runs the SDK's solver without
|
||||
@@ -30,7 +31,11 @@ PLANES = ("XY", "XZ", "YZ")
|
||||
PLANE_NORMALS = {"XY": "+z", "XZ": "-y", "YZ": "+x"}
|
||||
ENTITY_KINDS = {"line": ("start", "end"), "circle": ("center",), "arc": ("start", "end", "center"), "bspline": ("start", "end")}
|
||||
"""A B-spline also lists its ``control_points`` (point ids, the first and the last are its start and end) and a ``degree``, and,
|
||||
when they are not the uniform clamped ones (a trimmed or extended B-spline), its distinct ``knots`` and their ``multiplicities``."""
|
||||
when they are not the uniform clamped ones (a trimmed or extended B-spline), its distinct ``knots`` and their ``multiplicities``.
|
||||
The editor draws B-splines in anchor form (degree 3, inner multiplicities 3: ``[A0, out0, in1, A1, ...]``, anchors on the curve
|
||||
with a handle on each side); ``insert_spline_anchor``, ``remove_spline_anchor`` and ``convert_spline_to_anchors`` edit that form."""
|
||||
OUTPUTS = ("face", "wire")
|
||||
"""What the sketch cell makes of its profile: a face (``make_face_from_sketch_rface``) or a wire (``make_wire_from_sketch_rwire``)."""
|
||||
_MAX_DEGREE = 5
|
||||
|
||||
# kind -> (target parameter names in the SDK function, unit of its value or None, extra keyword parameters)
|
||||
@@ -227,7 +232,10 @@ def validate(doc: Mapping[str, Any]) -> dict[str, Any]:
|
||||
if isinstance(raw_profile, bool) or not isinstance(profile, int) or profile < 0:
|
||||
raise SketchError("the profile must be a whole number from zero")
|
||||
inner = [int(i) for i in doc.get("inner") or [] if isinstance(i, int) and not isinstance(i, bool) and i >= 0 and i != profile]
|
||||
return {
|
||||
output = doc.get("output") or "face"
|
||||
if output not in OUTPUTS:
|
||||
raise SketchError("the output of a sketch is a face or a wire")
|
||||
clean = {
|
||||
"plane": plane,
|
||||
"points": points,
|
||||
"entities": entities,
|
||||
@@ -236,6 +244,14 @@ def validate(doc: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"inner": inner,
|
||||
"fully_constrained": bool(doc.get("fully_constrained", False)),
|
||||
}
|
||||
if output == "wire": # a face sketch keeps the document it always had
|
||||
clean["output"] = "wire"
|
||||
return clean
|
||||
|
||||
|
||||
def output_of(doc: Mapping[str, Any]) -> str:
|
||||
"""What the sketch document makes: ``"face"`` or ``"wire"``."""
|
||||
return "wire" if doc.get("output") == "wire" else "face"
|
||||
|
||||
|
||||
# ---- code ---------------------------------------------------------------------------------------------------------------------
|
||||
@@ -312,7 +328,7 @@ def _calls(doc: Mapping[str, Any], *, var_for: Mapping[str, str] | None = None)
|
||||
|
||||
|
||||
def render(slug: str, doc: Mapping[str, Any]) -> tuple[list[str], list[str]]:
|
||||
"""(lines of the params cell body, lines of the feature cell body) for a validated *doc*; the face is bound to *slug*."""
|
||||
"""(lines of the params cell body, lines of the feature cell body) for a validated *doc*; the face (or wire) is bound to *slug*."""
|
||||
params: list[str] = []
|
||||
var_for: dict[str, str] = {}
|
||||
for constraint in doc["constraints"]:
|
||||
@@ -335,10 +351,14 @@ def render(slug: str, doc: Mapping[str, Any]) -> tuple[list[str], list[str]]:
|
||||
)
|
||||
var_for[constraint["id"]] = name
|
||||
inner = f"[{', '.join(str(i) for i in doc['inner'])}]"
|
||||
if output_of(doc) == "wire": # a closed loop or an open chain: a sweep path, a loft section
|
||||
make = f"{slug} = scad.make_wire_from_sketch_rwire(sketch=_sketch, profile={doc['profile']}, require_fully_constrained={bool(doc['fully_constrained'])})"
|
||||
else:
|
||||
make = f"{slug} = scad.make_face_from_sketch_rface(sketch=_sketch, profile={doc['profile']}, inner_profiles={inner}, require_fully_constrained={bool(doc['fully_constrained'])})"
|
||||
lines = [
|
||||
f"_sketch = scad.make_sketch_rsketch(name={json.dumps(slug)}, plane={_plane_literal(doc['plane'])})",
|
||||
*_calls(doc, var_for=var_for),
|
||||
f"{slug} = scad.make_face_from_sketch_rface(sketch=_sketch, profile={doc['profile']}, inner_profiles={inner}, require_fully_constrained={bool(doc['fully_constrained'])})",
|
||||
make,
|
||||
]
|
||||
return params, lines
|
||||
|
||||
@@ -415,7 +435,9 @@ def _bspline_samples(solved: Mapping[str, Any], count: int = 64) -> dict[str, An
|
||||
# only how a GUI holds a sketch. These adapters turn a document into an SDK ``Sketch``, call the operation by its SDK name and
|
||||
# turn the result back into a document: there is no geometry here.
|
||||
|
||||
EDIT_OPERATIONS = frozenset({"trim", "extend", "fillet_corner", "chamfer_corner", "project"}) # the SDK's ``<name>_rsketch`` functions that edit a sketch (add more as the SDK gains them)
|
||||
EDIT_OPERATIONS = frozenset(
|
||||
{"trim", "extend", "fillet_corner", "chamfer_corner", "project", "insert_spline_anchor", "remove_spline_anchor", "convert_spline_to_anchors"}
|
||||
) # the SDK's ``<name>_rsketch`` functions that edit a sketch (add more as the SDK gains them)
|
||||
|
||||
|
||||
def to_sketch(doc: Mapping[str, Any]) -> Any:
|
||||
@@ -435,7 +457,7 @@ def _target(item: Mapping[str, Any]) -> str:
|
||||
|
||||
|
||||
def from_sketch(sketch: Any, like: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""The document of an SDK ``Sketch`` (the plane, profile choice and constrained flag are taken from *like*)."""
|
||||
"""The document of an SDK ``Sketch`` (the plane, the constrained flag and the output are taken from *like*)."""
|
||||
data = sketch.to_dict()
|
||||
points: list[dict[str, Any]] = []
|
||||
entities: list[dict[str, Any]] = []
|
||||
@@ -484,6 +506,7 @@ def from_sketch(sketch: Any, like: Mapping[str, Any] | None = None) -> dict[str,
|
||||
"profile": 0,
|
||||
"inner": [],
|
||||
"fully_constrained": base.get("fully_constrained", False),
|
||||
"output": base.get("output", "face"),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -529,4 +552,4 @@ __all__ = [
|
||||
"apply_edit",
|
||||
"from_sketch",
|
||||
"to_sketch",
|
||||
"CONSTRAINTS", "ENTITY_KINDS", "PLANES", "PLANE_NORMALS", "SketchError", "plane_frame", "plane_normal", "plane_workplane", "render", "solve", "validate", "validate_plane"]
|
||||
"CONSTRAINTS", "ENTITY_KINDS", "OUTPUTS", "PLANES", "PLANE_NORMALS", "SketchError", "plane_frame", "plane_normal", "output_of", "plane_workplane", "render", "solve", "validate", "validate_plane"]
|
||||
|
||||
@@ -144,6 +144,9 @@ from simplecadapi._cpp import (
|
||||
fillet_corner_rsketch,
|
||||
project_rsketch,
|
||||
trim_rsketch,
|
||||
insert_spline_anchor_rsketch,
|
||||
remove_spline_anchor_rsketch,
|
||||
convert_spline_to_anchors_rsketch,
|
||||
constrain_mirror_rsketch,
|
||||
constrain_symmetric_rsketch,
|
||||
constrain_tangent_rsketch,
|
||||
@@ -450,6 +453,9 @@ __all__ = [
|
||||
"transform_rsolid",
|
||||
"translate_shape",
|
||||
"trim_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"trim_surface_rface",
|
||||
"twisted_sweep_rsolid",
|
||||
"unground_component_rassembly",
|
||||
|
||||
@@ -39,6 +39,9 @@ from simplecadapi._cpp import (
|
||||
make_wire_from_sketch_rwire,
|
||||
project_rsketch,
|
||||
trim_rsketch,
|
||||
insert_spline_anchor_rsketch,
|
||||
remove_spline_anchor_rsketch,
|
||||
convert_spline_to_anchors_rsketch,
|
||||
# (defined by the module itself)
|
||||
constrain_angle_rsketch,
|
||||
constrain_coincident_rsketch,
|
||||
@@ -125,4 +128,7 @@ __all__ = [
|
||||
"make_wire_from_sketch_rwire",
|
||||
"project_rsketch",
|
||||
"trim_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
]
|
||||
|
||||
@@ -132,6 +132,9 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = {
|
||||
"fillet_corner_rsketch": {"status": "replayable", "op": "fillet_corner_rsketch"},
|
||||
"chamfer_corner_rsketch": {"status": "replayable", "op": "chamfer_corner_rsketch"},
|
||||
"project_rsketch": {"status": "replayable", "op": "project_rsketch"},
|
||||
"insert_spline_anchor_rsketch": {"status": "replayable", "op": "insert_spline_anchor_rsketch"},
|
||||
"remove_spline_anchor_rsketch": {"status": "replayable", "op": "remove_spline_anchor_rsketch"},
|
||||
"convert_spline_to_anchors_rsketch": {"status": "replayable", "op": "convert_spline_to_anchors_rsketch"},
|
||||
"diff_sketch_rsketchdiff": {
|
||||
"status": "diagnostic",
|
||||
"reason": "Compares two sketches for inspection only; the edit that made the difference is the recorded node.",
|
||||
@@ -617,6 +620,9 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = (
|
||||
"fillet_corner_rsketch",
|
||||
"chamfer_corner_rsketch",
|
||||
"project_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"make_constrain_coincident_rsketch",
|
||||
"make_constrain_point_on_rsketch",
|
||||
"make_constrain_horizontal_rsketch",
|
||||
@@ -758,6 +764,9 @@ _CANONICAL_2_1_ONLY_OPS = {
|
||||
"fillet_corner_rsketch",
|
||||
"chamfer_corner_rsketch",
|
||||
"project_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"make_workplane_rworkplane",
|
||||
"make_workplane_from_face_rworkplane",
|
||||
"make_workplane_from_points_rworkplane",
|
||||
@@ -3236,6 +3245,21 @@ def _execute_graph(
|
||||
_store_outputs(node, result)
|
||||
continue
|
||||
|
||||
if op_name in {"insert_spline_anchor_rsketch", "remove_spline_anchor_rsketch", "convert_spline_to_anchors_rsketch"}:
|
||||
extra = {"insert_spline_anchor_rsketch": ("at",), "remove_spline_anchor_rsketch": ("anchor",)}.get(op_name, ())
|
||||
ctx.require_params(node.node_id, op_name, params, ("spline", *extra))
|
||||
sketch_outputs = _input_outputs(ctx, outputs, node, 0)
|
||||
if sketch_outputs:
|
||||
anchor_args: list[Any] = [str(params["spline"])]
|
||||
if op_name == "insert_spline_anchor_rsketch":
|
||||
at = params["at"]
|
||||
anchor_args.append(at if isinstance(at, str) else tuple(at))
|
||||
elif op_name == "remove_spline_anchor_rsketch":
|
||||
anchor_args.append(str(params["anchor"]))
|
||||
result = getattr(ops, op_name)(cast(Sketch, sketch_outputs[0]), *anchor_args)
|
||||
_store_outputs(node, result)
|
||||
continue
|
||||
|
||||
if op_name in {"fillet_corner_rsketch", "chamfer_corner_rsketch"}:
|
||||
size_param = (
|
||||
"radius" if op_name == "fillet_corner_rsketch" else "distance"
|
||||
|
||||
@@ -167,9 +167,10 @@ def test_bad_values_are_refused_with_a_message_and_never_reach_the_source(spec_i
|
||||
|
||||
|
||||
def test_names_are_checked_and_made_unique():
|
||||
taken = {"base", "BASE", "block"}
|
||||
assert F.default_slug("box", taken) == "box"
|
||||
assert F.default_slug("extrude_rect", taken) == "block_2"
|
||||
taken = {"base", "BASE", "box", "wp"}
|
||||
assert F.default_slug("box", taken) == "box_2"
|
||||
assert F.default_slug("workplane", taken) == "wp_2"
|
||||
assert F.default_slug("op.loft_rsolid", taken) == "loft"
|
||||
with pytest.raises(F.FeatureError):
|
||||
F.check_slug("Base", taken)
|
||||
with pytest.raises(F.FeatureError, match="already used"):
|
||||
|
||||
@@ -286,6 +286,7 @@ class TestCoverageMatrix(unittest.TestCase):
|
||||
"make_workplane_from_axis_rworkplane",
|
||||
"make_workplane_midplane_rworkplane",
|
||||
"make_workplane_normal_to_curve_rworkplane",
|
||||
"make_workplane_offset_rworkplane",
|
||||
"make_sketch_rsketch",
|
||||
"add_point_rsketch",
|
||||
"add_line_rsketch",
|
||||
@@ -297,6 +298,9 @@ class TestCoverageMatrix(unittest.TestCase):
|
||||
"fillet_corner_rsketch",
|
||||
"chamfer_corner_rsketch",
|
||||
"project_rsketch",
|
||||
"insert_spline_anchor_rsketch",
|
||||
"remove_spline_anchor_rsketch",
|
||||
"convert_spline_to_anchors_rsketch",
|
||||
"make_constrain_coincident_rsketch",
|
||||
"make_constrain_point_on_rsketch",
|
||||
"make_constrain_horizontal_rsketch",
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
"""B-splines in anchor form (anchors on the curve, a handle on each side) and the sketch output a wire.
|
||||
|
||||
insert_spline_anchor_rsketch / remove_spline_anchor_rsketch / convert_spline_to_anchors_rsketch edit the structure of a cubic
|
||||
B-spline of Bezier spans; the editor's sketch document carries them (``apply_edit``) and its pen tool draws in that form. A
|
||||
sketch document with ``"output": "wire"`` becomes ``make_wire_from_sketch_rwire`` (a closed loop or an open chain), so sweeps
|
||||
and lofts can take sketches.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecadapi.editor import features as F
|
||||
from simplecadapi.editor import sketch_doc as D
|
||||
from simplecadapi.recording.serializer import export_graph_json, import_graph_json, replay_graph
|
||||
|
||||
|
||||
def one_span(name="pen"):
|
||||
sketch = scad.make_sketch_rsketch(name)
|
||||
for pid, xy in {"a0": (0, 0), "h0": (10, 10), "h1": (20, 10), "a1": (30, 0)}.items():
|
||||
sketch = scad.add_point_rsketch(sketch, pid, *xy)
|
||||
return scad.add_bspline_rsketch(sketch, "s1", "a0", "a1", ["a0", "h0", "h1", "a1"], 3)
|
||||
|
||||
|
||||
def spline(sketch, entity_id="s1"):
|
||||
return next(e for e in sketch.to_dict()["entities"] if e["id"] == entity_id)
|
||||
|
||||
|
||||
def poles(sketch, entity_id="s1"):
|
||||
return [c["point_id"] for c in spline(sketch, entity_id)["control_points"]]
|
||||
|
||||
|
||||
def samples(sketch, entity_id="s1", count=60):
|
||||
solved = scad.inspect_sketch_rsketchresult(sketch).to_dict()["solved_entities"][entity_id]
|
||||
edge = scad.make_spline_redge(
|
||||
control_points=[(x, y, 0.0) for x, y in solved["control_points"]],
|
||||
degree=solved["degree"],
|
||||
knots=solved.get("knots"),
|
||||
multiplicities=solved.get("multiplicities"),
|
||||
)
|
||||
return scad.sample_curve_rcurvature(edge=edge, count=count)["points"]
|
||||
|
||||
|
||||
def gap(a, b):
|
||||
return max(abs(p[0] - q[0]) + abs(p[1] - q[1]) for p, q in zip(a, b))
|
||||
|
||||
|
||||
def xy(sketch, point_id):
|
||||
item = next(e for e in sketch.to_dict()["entities"] if e["id"] == point_id)
|
||||
return (item["x"], item["y"])
|
||||
|
||||
|
||||
# ---- the SDK operations -------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_inserting_an_anchor_keeps_the_curve_and_the_ids_of_the_spans_handles():
|
||||
before = one_span()
|
||||
after = scad.insert_spline_anchor_rsketch(before, "s1", (12.0, 8.0))
|
||||
assert poles(after) == ["a0", "h0", "p1", "p2", "p3", "h1", "a1"]
|
||||
assert spline(after)["multiplicities"] == [4, 3, 4]
|
||||
assert gap(samples(before), samples(after)) < 1e-9
|
||||
assert "anchor 'p2'" in after.get_metadata("last_edit")["notes"][0]
|
||||
diff = scad.diff_sketch_rsketchdiff(before=before, after=after)
|
||||
assert diff["created"] == ["p1", "p2", "p3"] and set(diff["changed"]) == {"h0", "h1", "s1"}
|
||||
|
||||
|
||||
def test_removing_an_anchor_keeps_the_ends_and_the_outer_handles():
|
||||
before = one_span()
|
||||
split = scad.insert_spline_anchor_rsketch(before, "s1", (22.0, 6.0))
|
||||
split = scad.insert_spline_anchor_rsketch(split, "s1", (5.0, 4.0))
|
||||
middle = poles(split)[6] # the anchor inserted first is now the third
|
||||
merged = scad.remove_spline_anchor_rsketch(split, "s1", middle)
|
||||
ids = poles(merged)
|
||||
assert ids[0] == "a0" and ids[-1] == "a1" and len(ids) == 7
|
||||
# the outer handles keep their ids and their directions
|
||||
assert ids[5] == "h1"
|
||||
a1, h1_before, h1_after = xy(split, "a1"), xy(split, "h1"), xy(merged, "h1")
|
||||
cross = (h1_before[0] - a1[0]) * (h1_after[1] - a1[1]) - (h1_before[1] - a1[1]) * (h1_after[0] - a1[0])
|
||||
assert abs(cross) < 1e-9
|
||||
# removing both inserted anchors gives back the curve they split
|
||||
back = scad.remove_spline_anchor_rsketch(merged, "s1", ids[3])
|
||||
assert poles(back) == ["a0", "h0", "h1", "a1"]
|
||||
assert gap(samples(before), samples(back)) < 1e-7
|
||||
|
||||
|
||||
def test_converting_a_control_point_bspline_keeps_its_shape_and_its_end_points():
|
||||
sketch = scad.make_sketch_rsketch("old")
|
||||
for i, (x, y) in enumerate([(0, 0), (5, 10), (10, -5), (15, 8), (20, 0), (25, 6)]):
|
||||
sketch = scad.add_point_rsketch(sketch, f"q{i}", x, y)
|
||||
sketch = scad.add_bspline_rsketch(sketch, "s1", "q0", "q5", [f"q{i}" for i in range(6)], 3)
|
||||
after = scad.convert_spline_to_anchors_rsketch(sketch, "s1")
|
||||
data = spline(after)
|
||||
assert data["degree"] == 3 and data["multiplicities"] == [4, 3, 3, 4]
|
||||
assert poles(after)[0] == "q0" and poles(after)[-1] == "q5"
|
||||
assert gap(samples(sketch), samples(after)) < 1e-9
|
||||
again = scad.convert_spline_to_anchors_rsketch(after, "s1")
|
||||
assert poles(again) == poles(after) and "already in anchor form" in again.get_metadata("last_edit")["notes"][0]
|
||||
# a degree-5 spline has no exact anchor form: it is approximated, and the notes say so
|
||||
five = scad.add_bspline_rsketch(sketch, "s5", "q0", "q5", [f"q{i}" for i in range(6)], 5)
|
||||
approx = scad.convert_spline_to_anchors_rsketch(five, "s5")
|
||||
assert spline(approx, "s5")["degree"] == 3 and "approximated" in approx.get_metadata("last_edit")["notes"][0]
|
||||
|
||||
|
||||
def test_refusals_name_the_ids():
|
||||
split = scad.insert_spline_anchor_rsketch(one_span(), "s1", (15.0, 8.0))
|
||||
cases = [
|
||||
(lambda: scad.remove_spline_anchor_rsketch(split, "s1", "a0"), "is an end of 's1'"),
|
||||
(lambda: scad.remove_spline_anchor_rsketch(split, "s1", "p1"), "is a handle of 's1'"),
|
||||
(lambda: scad.insert_spline_anchor_rsketch(split, "s1", "p2"), "already has an anchor there"),
|
||||
(lambda: scad.insert_spline_anchor_rsketch(split, "zz", (1, 1)), "no entity 'zz'"),
|
||||
(lambda: scad.insert_spline_anchor_rsketch(scad.add_point_rsketch(split, "k", 0, 0), "k", (1, 1)), "not a B-spline"),
|
||||
]
|
||||
for call, expected in cases:
|
||||
with pytest.raises(ValueError) as caught:
|
||||
call()
|
||||
assert expected in str(caught.value), (expected, str(caught.value))
|
||||
|
||||
|
||||
def test_trim_keeps_the_anchor_form():
|
||||
sketch = scad.insert_spline_anchor_rsketch(one_span(), "s1", (15.0, 8.0))
|
||||
for pid, point in {"t0": (25, -5), "t1": (25, 20)}.items():
|
||||
sketch = scad.add_point_rsketch(sketch, pid, *point)
|
||||
sketch = scad.add_line_rsketch(sketch, "cut", "t0", "t1")
|
||||
after = scad.trim_rsketch(sketch, "s1", (29.0, 1.0))
|
||||
piece = next(e for e in after.to_dict()["entities"] if e["kind"] == "bspline")
|
||||
assert piece["degree"] == 3 and piece["multiplicities"] == [4, 3, 4]
|
||||
|
||||
|
||||
def test_anchor_edits_are_recorded_and_replayed():
|
||||
with scad.GraphSession() as session:
|
||||
sketch = scad.insert_spline_anchor_rsketch(one_span(), "s1", (12.0, 8.0))
|
||||
sketch = scad.insert_spline_anchor_rsketch(sketch, "s1", (25.0, 4.0))
|
||||
sketch = scad.remove_spline_anchor_rsketch(sketch, "s1", "p2")
|
||||
session.capture_result(value=scad.make_wire_from_sketch_rwire(sketch))
|
||||
payload = json.loads(export_graph_json(session.graph))
|
||||
insert = next(n for n in payload["nodes"] if n["op"] == "insert_spline_anchor_rsketch")
|
||||
assert insert["params"]["spline"] == "s1" and insert["params"]["at"] == [12.0, 8.0]
|
||||
assert any(n["op"] == "remove_spline_anchor_rsketch" and n["params"]["anchor"] == "p2" for n in payload["nodes"])
|
||||
rebuilt = replay_graph(import_graph_json(json.dumps(payload)))
|
||||
length = lambda wire: sum(edge.get_length() for edge in scad.ql.edges().resolve(wire)) # noqa: E731
|
||||
assert length(rebuilt[0]) == pytest.approx(length(scad.make_wire_from_sketch_rwire(sketch)), rel=1e-9)
|
||||
|
||||
|
||||
# ---- the editor's document ------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def pen_doc():
|
||||
"""A pen path of two spans as the editor draws it: knots 0..2, inner multiplicity 3."""
|
||||
return {
|
||||
"plane": "XY",
|
||||
"points": [{"id": i, "x": x, "y": y} for i, x, y in [("a", 0, 0), ("b", 4, 6), ("c", 8, 10), ("d", 12, 10), ("e", 16, 10), ("f", 20, 6), ("g", 24, 0)]],
|
||||
"entities": [{"id": "s1", "kind": "bspline", "start": "a", "end": "g", "control_points": list("abcdefg"), "degree": 3, "knots": [0, 1, 2], "multiplicities": [4, 3, 4]}],
|
||||
"constraints": [],
|
||||
"profile": 0,
|
||||
"inner": [],
|
||||
"fully_constrained": False,
|
||||
}
|
||||
|
||||
|
||||
def test_the_document_carries_anchor_edits_through_the_sdk():
|
||||
doc = D.validate(pen_doc())
|
||||
assert doc["entities"][0]["multiplicities"] == [4, 3, 4]
|
||||
inserted = D.apply_edit(doc, "insert_spline_anchor", {"spline": "s1", "at": [3, 4]})
|
||||
entity = inserted["sketch"]["entities"][0]
|
||||
assert entity["multiplicities"] == [4, 3, 3, 4] and len(entity["control_points"]) == 10
|
||||
assert inserted["created"] == ["p1", "p2", "p3"]
|
||||
removed = D.apply_edit(inserted["sketch"], "remove_spline_anchor", {"spline": "s1", "anchor": "d"})
|
||||
assert removed["sketch"]["entities"][0]["control_points"][3] == "p2" and "d" in removed["removed"]
|
||||
with pytest.raises(D.SketchError, match="is an end of 's1'"):
|
||||
D.apply_edit(doc, "remove_spline_anchor", {"spline": "s1", "anchor": "a"})
|
||||
# the code the cell gets builds the same spline
|
||||
params, lines = D.render("pen", removed["sketch"])
|
||||
assert any("multiplicities=[4, 3, 4]" in line for line in lines)
|
||||
|
||||
|
||||
# ---- a sketch that makes a wire ------------------------------------------------------------------------------------------------
|
||||
|
||||
PATH = {
|
||||
"plane": "XZ",
|
||||
"points": [{"id": "a", "x": 0, "y": 0}, {"id": "b", "x": 0, "y": 20}, {"id": "c", "x": 10, "y": 30}],
|
||||
"entities": [{"id": "l0", "kind": "line", "start": "a", "end": "b"}, {"id": "l1", "kind": "line", "start": "b", "end": "c"}],
|
||||
"constraints": [],
|
||||
"profile": 0,
|
||||
"inner": [],
|
||||
"fully_constrained": False,
|
||||
"output": "wire",
|
||||
}
|
||||
DISC = {
|
||||
"plane": "XY",
|
||||
"points": [{"id": "o", "x": 0, "y": 0}],
|
||||
"entities": [{"id": "k", "kind": "circle", "center": "o", "radius": 2.0}],
|
||||
"constraints": [],
|
||||
"profile": 0,
|
||||
"inner": [],
|
||||
"fully_constrained": False,
|
||||
}
|
||||
|
||||
|
||||
def square(z, half, output="wire"):
|
||||
corners = [(-half, -half), (half, -half), (half, half), (-half, half)]
|
||||
return {
|
||||
"plane": {"origin": [0, 0, z], "x_axis": [1, 0, 0], "y_axis": [0, 1, 0]},
|
||||
"points": [{"id": f"p{i}", "x": x, "y": y} for i, (x, y) in enumerate(corners)],
|
||||
"entities": [{"id": f"l{i}", "kind": "line", "start": f"p{i}", "end": f"p{(i + 1) % 4}"} for i in range(4)],
|
||||
"constraints": [],
|
||||
"profile": 0,
|
||||
"inner": [],
|
||||
"fully_constrained": False,
|
||||
"output": output,
|
||||
}
|
||||
|
||||
|
||||
def test_the_output_is_a_face_unless_the_document_says_wire():
|
||||
assert "output" not in D.validate(DISC) and D.output_of(D.validate(DISC)) == "face"
|
||||
assert D.validate(PATH)["output"] == "wire"
|
||||
with pytest.raises(D.SketchError, match="face or a wire"):
|
||||
D.validate({**DISC, "output": "solid"})
|
||||
_, lines = D.render("path", D.validate(PATH))
|
||||
assert lines[-1] == "path = scad.make_wire_from_sketch_rwire(sketch=_sketch, profile=0, require_fully_constrained=False)"
|
||||
# the SDK lists the open chain as a profile, and an edit keeps the output
|
||||
assert D.solve(PATH)["profiles"][0]["closed"] is False
|
||||
assert D.from_sketch(D.to_sketch(PATH), D.validate(PATH))["output"] == "wire"
|
||||
|
||||
|
||||
def _builder():
|
||||
scope: dict = {"scad": scad}
|
||||
bodies: dict[str, str] = {}
|
||||
|
||||
def add(spec_id, slug, values):
|
||||
rendered = F.render_feature(spec_id, slug, values, bodies=bodies)
|
||||
if rendered.params:
|
||||
exec("\n".join(rendered.params), scope) # noqa: S102 - the code under test is ours
|
||||
exec(rendered.feature, scope) # noqa: S102
|
||||
# what the notebook says the feature makes: a sketch makes what its document says (gui_features.snapshot)
|
||||
bodies[slug] = D.output_of(values["sketch"]) if spec_id == "sketch" else rendered.produces
|
||||
return rendered
|
||||
|
||||
return scope, add
|
||||
|
||||
|
||||
def test_an_open_chain_sketch_is_the_path_a_sketch_face_is_swept_along():
|
||||
with scad.GraphSession(graph_id="sketch-wire-sweep"):
|
||||
scope, add = _builder()
|
||||
add("sketch", "path", {"sketch": PATH})
|
||||
assert isinstance(scope["path"], scad.Wire) and not scope["path"].is_closed()
|
||||
add("sketch", "disc", {"sketch": DISC})
|
||||
add("op.sweep_rsolid", "swept", {"profile": "disc", "path": "path"})
|
||||
assert scope["swept"].get_volume() > 300
|
||||
|
||||
|
||||
def test_closed_sketches_made_wires_are_lofted():
|
||||
with scad.GraphSession(graph_id="sketch-wire-loft"):
|
||||
scope, add = _builder()
|
||||
add("sketch", "low", {"sketch": square(0, 10)})
|
||||
add("sketch", "high", {"sketch": square(20, 5)})
|
||||
assert scope["low"].is_closed() and isinstance(scope["high"], scad.Wire)
|
||||
add("op.loft_rsolid", "frustum", {"profiles": ["low", "high"]})
|
||||
# a square frustum: h / 3 * (A1 + A2 + sqrt(A1 * A2))
|
||||
assert scope["frustum"].get_volume() == pytest.approx(20 / 3 * (400 + 100 + 200), rel=1e-6)
|
||||
|
||||
|
||||
def test_the_notebook_says_a_wire_sketch_makes_a_wire_and_offers_only_face_sketches_as_profiles(tmp_path):
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
|
||||
import uvicorn
|
||||
|
||||
from simplecadapi.editor.server import WorkspaceState, create_app
|
||||
from simplecadapi.editor.templates import create_notebook
|
||||
|
||||
path = create_notebook(tmp_path, "wires", "blank")
|
||||
state = WorkspaceState(tmp_path)
|
||||
state.port = 17763
|
||||
server = uvicorn.Server(uvicorn.Config(create_app(state), port=state.port, log_level="error"))
|
||||
threading.Thread(target=server.run, daemon=True).start()
|
||||
state.hub.attach_loop(asyncio.new_event_loop())
|
||||
|
||||
def wait_idle(timeout=120):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline and not {c.get("status") for c in state.cells} <= {"idle", "stale", "exception", "error", None}:
|
||||
time.sleep(0.3)
|
||||
|
||||
try:
|
||||
state.start_kernel(path)
|
||||
service = state.features
|
||||
service.add({"spec": "sketch", "name": "path", "values": {"sketch": PATH}})
|
||||
service.add({"spec": "sketch", "name": "disc", "values": {"sketch": DISC}})
|
||||
wait_idle()
|
||||
snap = service.snapshot()
|
||||
assert {b["name"]: b["produces"] for b in snap["bodies"]} == {"path": "wire", "disc": "face"}
|
||||
assert [p["name"] for p in snap["profiles"]] == ["disc"]
|
||||
service.add({"spec": "op.sweep_rsolid", "name": "swept", "values": {"profile": "disc", "path": "path"}})
|
||||
wait_idle()
|
||||
snap = service.snapshot()
|
||||
assert all(not f["errors"] for f in snap["features"]), snap["features"]
|
||||
assert snap["tip"] == "swept"
|
||||
assert "path = scad.make_wire_from_sketch_rwire(" in path.read_text()
|
||||
finally:
|
||||
if state.kernel is not None:
|
||||
state.kernel.stop()
|
||||
server.should_exit = True
|
||||
Reference in New Issue
Block a user