Extend: extend a free arc in place and add the line the preview draws (#4615) (#4618)

* Slightly fix the extend tool

* Extend: add the line the preview draws, and stop an arc on another curve

sketch.extend reported "nothing to extend to" whenever nothing stood in the
line's way, even though the viewport previewed a line past its end; with
nothing in the way the extension now runs as far as the preview shows, on the
same measurement, so the click adds what was drawn.

An arc extension that ran into another circle or arc refused the target when
its crossing already belonged to another curve's end (a shared crossing point
of two circles): that point is now joined instead, so the extension closes onto
the geometry that is there.

---------

Co-authored-by: SolidCraft Dev <dev@solidcraft.local>
Co-authored-by: n0tfr3shm1lk <n0tfr3shm1lk@ukr.net>
This commit is contained in:
authored and GitHub committed 2026-10-24 20:46:44 +00:00
1 parent f6ff2ff139
commit 4e6939b5cf
6 files changed
+787 -50

No files matched your search

+1 -1
View File
@@ -39,7 +39,7 @@ pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
pub(crate) use features::{EdgeRefForm, edge_ref_form, sketch_key};
pub use features::{auto_operation, extrude_reach};
pub use sketch_modify::trim_piece;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
pub use view_dxf::sketch::exportable as view_dxf_exportable;
pub use view_navigation::standard_view;
mod component_link;
+564 -44
View File
@@ -601,6 +601,454 @@ fn break_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"curves": out, "sketch": info}))
}
/// How far a line with nothing in its way extends: the reach its preview draws, and the length
/// `sketch.extend` adds, so clicking a preview that overhangs its target adds that line instead
/// of nothing.
const EXTEND_REACH: f64 = 50.0;
/// Preview the extend operation without modifying the sketch.
/// Returns the hit point that would be reached if the user extends the curve,
/// or None if extension is not possible (blocked by collinear curves).
pub fn extend_preview(sk: &solidcraft_sketch::Sketch, ci: usize, hover_pos: Vec2) -> Option<Vec2> {
use solidcraft_sketch::{CurveKind, Shape};
let curve = sk.curves.get(ci)?;
let (a, b) = match &curve.kind {
CurveKind::Line { a: pa, b: pb } => (*pa, *pb),
CurveKind::Arc { a: pa, b: pb, .. } => (*pa, *pb),
_ => return None,
};
let pa = sk.point(a)?;
let pb = sk.point(b)?;
let at_b = hover_pos.dist(pb) <= hover_pos.dist(pa);
let end = if at_b { b } else { a };
let end_pt = sk.point(end)?;
let other = if at_b { pa } else { pb };
// Get the shape (line or arc) of the curve to extend
let sh = sk.shape(ci)?;
let unbounded = match sh {
Shape::Line { .. } => sh,
Shape::Round { c, r, start, .. } => Shape::Round { c, r, start, sweep: std::f64::consts::TAU },
};
// Quick check for collinearity blocking by neighbors
for other_curve in sk.curves.iter() {
if let CurveKind::Line { a: na, b: nb } = &other_curve.kind
&& (*na == end || *nb == end)
{
let other_idx = if *na == end { *nb } else { *na };
if let Some(other_pos) = sk.point(other_idx) {
let dir = (end_pt - other).normalized()?;
let v = other_pos - end_pt;
// Collinear and in the same direction: this blocks extension.
if v.cross(dir).abs() < 1e-6 && v.dot(dir) > 1e-6 {
return None;
}
}
}
}
// Now search for actual hit points using the same algorithm as extend
let mut best_gap = f64::MAX;
let mut best_hit: Option<Vec2> = None;
let mut budget = 500_000usize; // Reduced budget for preview
let tol_preview = 1e-7;
// Get the extension direction
let dir = (end_pt - other).normalized().unwrap_or_default();
for (oi, other_curve) in sk.curves.iter().enumerate() {
if oi == ci {
continue;
}
// Skip curves that share the endpoint we're extending from
let shares_endpoint = match &other_curve.kind {
CurveKind::Line { a, b } => *a == end || *b == end,
CurveKind::Arc { a, b, .. } => *a == end || *b == end,
_ => false,
};
if shares_endpoint {
// Check for collinearity blocking (already checked above, but re-check here)
if let CurveKind::Line { a: na, b: nb } = &other_curve.kind {
let other_idx = if *na == end { *nb } else { *na };
if let Some(other_pos) = sk.point(other_idx) {
let v = other_pos - end_pt;
let cross = v.cross(dir);
let dot = v.dot(dir);
if cross.abs() < 1e-6 && dot > 1e-6 {
// Collinear and in same direction - blocks extension
continue; // Skip this curve for hit finding
}
}
}
}
let pieces = sk.exact_segs(oi).unwrap_or_else(|| sk.segs(oi));
// For infinite lines, extend segments
let pieces_to_check: Vec<_> =
if other_curve.infinite { pieces.iter().map(|s| support::endless(s, end_pt)).collect() } else { pieces.to_vec() };
for piece in pieces_to_check {
// Try to get hits - hits() will return empty vec or error for unsupported types
if let Ok(hits) = support::hits(&unbounded, &piece, &mut budget) {
for q in hits {
// Check if hit is beyond the current end
let t = sh.param(q);
let gap = match sh {
Shape::Line { a, b } => {
let l = a.dist(b);
if at_b { (t - 1.0) * l } else { -t * l }
}
Shape::Round { r, .. } => {
let (_, t1) = sh.range();
if t <= t1 + tol_preview / r.max(1e-12) || t >= TAU - tol_preview / r.max(1e-12) {
continue;
}
if at_b { (t - t1) * r } else { (TAU - t) * r }
}
};
// Only consider hits that are further than tolerance
if gap > tol_preview * 10.0 && gap < best_gap {
// CRITICAL CHECK: Verify no other curve lies between end_pt and q along the extension direction
let mut blocked = false;
for (oi2, _check_curve) in sk.curves.iter().enumerate() {
if oi2 == ci {
continue;
}
if oi2 == oi {
continue;
} // Skip the curve we just found hit on
// Check if any segment of this curve lies between end_pt and q
let segs = sk.exact_segs(oi2).unwrap_or_else(|| sk.segs(oi2));
for seg in segs {
// Get the endpoints of this segment
let (sa, sb) = match seg {
solidcraft_geom::Seg2::Line { a: sa, b: sb } => (sa, sb),
solidcraft_geom::Seg2::Arc { center, radius, start, sweep } => {
// For arcs, check the start and end points
let angle = start + sweep;
(
center + Vec2::new(radius * start.cos(), radius * start.sin()),
center + Vec2::new(radius * angle.cos(), radius * angle.sin()),
)
}
_ => continue,
};
// Check if either endpoint lies between end_pt and q along the extension direction
let vec_to_sa = sa - end_pt;
let proj_sa = vec_to_sa.dot(dir);
if proj_sa > tol_preview && proj_sa < gap - tol_preview {
// Point sa projects onto the extension path between start and hit
// Check if it's close to the line (within tolerance)
let perp_dist = (sa - end_pt).cross(dir).abs();
if perp_dist < tol_preview * 10.0 {
blocked = true;
break;
}
}
let vec_to_sb = sb - end_pt;
let proj_sb = vec_to_sb.dot(dir);
if proj_sb > tol_preview && proj_sb < gap - tol_preview {
let perp_dist = (sb - end_pt).cross(dir).abs();
if perp_dist < tol_preview * 10.0 {
blocked = true;
break;
}
}
if blocked {
break;
}
}
if blocked {
break;
}
}
if !blocked {
best_gap = gap;
best_hit = Some(q);
}
}
}
}
}
}
// CRITICAL CHECK 3: Verify no other curve endpoint coincides with the hit point.
// If another curve already ends at this location, we should not create a new overlapping line.
if let Some(hit) = best_hit {
for (oi2, _other_curve) in sk.curves.iter().enumerate() {
if oi2 == ci {
continue;
}
// Get endpoints of the other curve
let ends = match &sk.curves.get(oi2).map(|c| &c.kind) {
Some(CurveKind::Line { a, b }) => [a, b],
Some(CurveKind::Arc { a, b, .. }) => [a, b],
_ => continue,
};
for &end_idx in &ends {
if let Some(pt) = sk.point(*end_idx) {
// If an existing point is at the hit location (within tolerance), block extension.
if pt.dist(hit) < tol_preview * 10.0 {
return None;
}
}
}
}
}
best_hit.or(Some(end_pt + dir * EXTEND_REACH))
}
/// One end of an arc growing along the arc's own circle, as a new arc, and what stops it.
///
/// Arcs extend both ways: past their `b` end counter-clockwise and past their `a` end clockwise,
/// each as far as the first geometry on that path. The path ends at the arc's far end, where the
/// arc itself begins again, so an extension never runs over the arc it grows from; reaching it
/// closes the gap between the two ends.
#[derive(Clone, Copy, Debug)]
struct ArcAim {
/// The arc's end that grows (a point index), and the far end the extension must not pass.
end: usize,
far: usize,
/// Whether the growing end is the arc's `b` end: `b` grows counter-clockwise, `a` clockwise.
at_b: bool,
/// The arc's circle: the centre itself and the radius.
centre: Vec2,
radius: f64,
/// The angle the growing end sits at, and how far round the circle the extension travels.
end_angle: f64,
travel: f64,
/// The point the extension stops at, and the curve that stops it there.
hit: Vec2,
cutter: usize,
}
impl ArcAim {
/// The extension as points along the circle, the growing end first.
fn points(&self) -> Vec<Vec2> {
const N: usize = 64;
let dir = if self.at_b { 1.0 } else { -1.0 };
(0..=N).map(|i| self.centre + Vec2::from_angle(self.end_angle + dir * self.travel * i as f64 / N as f64) * self.radius).collect()
}
}
/// The first geometry an arc meets when it grows from the end of `ci` nearest `at`, or `None`
/// when nothing is in the way. Both ends grow: past `b` counter-clockwise, past `a` clockwise,
/// and only as far as the nearest curve on that path stops them. Two curves stopping it at the
/// same distance is an error, not a guess.
fn arc_aim(sk: &Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<Option<ArcAim>> {
let Some(CurveKind::Arc { a, b, .. }) = sk.curves.get(ci).map(|c| c.kind.clone()) else { return Ok(None) };
let Some(Shape::Round { c: centre, r, start, sweep }) = sk.shape(ci) else { return Ok(None) };
if !(r.is_finite() && r > 0.0) || !start.is_finite() || !sweep.is_finite() {
return Err(bad(cmd, "the arc's circle is not usable"));
}
// A whole circle has no end to grow from.
if sweep >= TAU - 1e-12 {
return Ok(None);
}
let (Some(qa), Some(qb)) = (sk.point(a), sk.point(b)) else { return Ok(None) };
let at_b = at.dist(qb) <= at.dist(qa);
let (end, far, end_angle) = if at_b { (b, a, start + sweep) } else { (a, b, start) };
// The extension runs from the growing end round to the far end, where the arc itself begins
// again: it may stop on it (closing the gap between the two ends) but not pass it.
let reach = TAU - sweep;
let angle_tol = TOL / r;
let far_tol = TOL * 10.0 / r;
let circle = Shape::Round { c: centre, r, start: 0.0, sweep: TAU };
let mut best: Option<(f64, Vec2, usize)> = None;
let mut ambiguous = false;
let mut budget = 1_000_000usize;
let mut segment_count = 0usize;
for (oi, curve) in sk.curves.iter().enumerate() {
if oi == ci {
continue;
}
// A circle passes over arcs lying on it, so no intersection reports them: an arc on the
// same circle stops the extension where it begins along the way, and the gap ends there.
if matches!(curve.kind, CurveKind::Arc { .. })
&& let Some(Shape::Round { c: oc, r: or, start: os, sweep: ow }) = sk.shape(oi)
&& oc.dist(centre) <= TOL * 10.0
&& (or - r).abs() <= TOL * 10.0
{
if !(os.is_finite() && ow.is_finite() && ow > 0.0) {
return Err(bad(cmd, "another arc on the same circle is not usable"));
}
let (entry, travel) = if at_b { (os, (os - end_angle).rem_euclid(TAU)) } else { (os + ow, (end_angle - os - ow).rem_euclid(TAU)) };
// Lying on that arc already, or on the point it goes on from, leaves no gap to fill:
// the extension could only double the arc that is there.
let into = if at_b { (end_angle - os).rem_euclid(TAU) } else { (os + ow - end_angle).rem_euclid(TAU) };
if travel <= angle_tol || into <= angle_tol || into < ow - angle_tol {
return Err(bad(cmd, "the arc already continues into another arc on its circle"));
}
if travel > reach + far_tol {
continue;
}
let entry = centre + Vec2::from_angle(entry) * r;
keep_stop(&mut best, &mut ambiguous, travel, entry, oi, angle_tol);
continue;
}
let mut pieces = sk.exact_segs(oi).unwrap_or_else(|| sk.segs(oi));
// An infinite line (#1359) is a boundary along its whole line.
if curve.infinite {
pieces = pieces.iter().map(|s| support::endless(s, centre)).collect();
}
segment_count += pieces.len();
if segment_count > 16_384 {
return Err(bad(cmd, "too many exact curve pieces to extend safely"));
}
for piece in &pieces {
for q in support::hits(&circle, piece, &mut budget)? {
let travel = if at_b { (q - centre).angle() - end_angle } else { end_angle - (q - centre).angle() }.rem_euclid(TAU);
// The growing end itself, or past the arc's far end (where the extension would
// run over the arc).
if travel <= angle_tol || travel > reach + far_tol {
continue;
}
keep_stop(&mut best, &mut ambiguous, travel, q, oi, angle_tol);
}
}
}
if ambiguous {
return Err(bad(cmd, "multiple curves stop the extension at the same distance"));
}
Ok(best.map(|(travel, hit, cutter)| ArcAim { end, far, at_b, centre, radius: r, end_angle, travel, hit, cutter }))
}
/// Keep the stop the nearest of the candidates, and remember it when another curve stops the
/// extension at the same distance somewhere else; the same point from several curves is one stop.
fn keep_stop(best: &mut Option<(f64, Vec2, usize)>, ambiguous: &mut bool, travel: f64, q: Vec2, oi: usize, angle_tol: f64) {
if best.is_none_or(|x| travel < x.0 - angle_tol) {
*best = Some((travel, q, oi));
*ambiguous = false;
} else if best.is_some_and(|x| (travel - x.0).abs() <= angle_tol && x.1.dist(q) > TOL) {
*ambiguous = true;
}
}
/// The point the extension ends at when the sketch already has one there: the arc's own far end
/// (closing the gap between its two ends), or the end of another curve the extension runs into —
/// an arc on the same circle across the gap, or any other curve crossing its path. Joining that
/// point keeps the geometry one chain instead of laying a second point over a point that is
/// there, so a circle met exactly where another curve already ends closes onto that curve.
/// `None` when the stop needs a new point.
fn arc_stop(sk: &Sketch, ci: usize, aim: &ArcAim) -> Option<usize> {
let at_hit = |p: usize| sk.point(p).is_some_and(|pt| pt.dist(aim.hit) <= TOL * 10.0);
if at_hit(aim.far) {
return Some(aim.far);
}
sk.curves.iter().enumerate().filter(|(i, _)| *i != ci).find_map(|(_, c)| {
let ends = match c.kind {
CurveKind::Line { a, b } | CurveKind::Arc { a, b, .. } => [a, b],
_ => return None,
};
ends.into_iter().find(|p| at_hit(*p))
})
}
/// Add the arc an extension needs: a new arc on the same circle as `ci`, from the growing end to
/// the stop, sweeping the way the extension went. The arc being extended keeps its geometry and
/// its constraints; the extension is new geometry.
fn add_arc_extension(sk: &mut Sketch, ci: usize, aim: &ArcAim, stop: Option<usize>) -> Result<String> {
let centre = match sk.curves.get(ci).map(|c| c.kind.clone()) {
Some(CurveKind::Arc { c, .. }) => c,
_ => return Err(bad("sketch.extend", "only arcs extend along their circle")),
};
let stop = match stop {
Some(p) => p,
None => sk.add_point(aim.hit, None)?,
};
// `CurveKind::Arc` always sweeps counter-clockwise from `a` to `b`: growing `b` runs from the
// arc's end to the stop, growing `a` runs the other way round, from the stop back to the end.
let kind = if aim.at_b { CurveKind::Arc { c: centre, a: aim.end, b: stop } } else { CurveKind::Arc { c: centre, a: stop, b: aim.end } };
sk.add_curve(kind, None)?;
Ok(sk.points.get(stop).map(|x| x.id.clone()).unwrap_or_default())
}
/// Whether `q` already is another curve's end: extending there would double geometry that is
/// there, so extend refuses instead of adding an overlapping curve.
fn ends_at_curve_end(sk: &Sketch, ci: usize, q: Vec2) -> bool {
sk.curves.iter().enumerate().filter(|(i, _)| *i != ci).any(|(_, c)| {
let ends = match &c.kind {
CurveKind::Line { a, b } | CurveKind::Arc { a, b, .. } => [*a, *b],
_ => return false,
};
ends.iter().any(|e| sk.point(*e).is_some_and(|pt| pt.dist(q) < TOL * 10.0))
})
}
/// Whether the growing end of an arc already carries geometry: another curve starts there, or a
/// constraint holds the point. Such an end keeps its place, so the extension has to be new
/// geometry.
fn arc_end_held(sk: &Sketch, ci: usize, end: usize) -> bool {
if sk.curves.iter().enumerate().any(|(i, c)| i != ci && uses(c, end)) {
return true;
}
sk.constraints.iter().any(|c| {
use solidcraft_sketch::ConstraintKind::*;
match c.kind {
Coincident { p, q } => p == end || q == end,
Fix { p } | PointOnCurve { p, .. } | Midpoint { p, .. } => p == end,
HorizontalPoints { p, q } | VerticalPoints { p, q } | Symmetric { p, q, .. } => p == end || q == end,
_ => false,
}
})
}
/// Extend an arc, in either direction, up to the first geometry on the way. A free end grows in
/// place, so the sketch keeps one arc; an end that already carries geometry, or a stop where the
/// sketch already has a point, is joined by a new arc instead.
fn extend_arc(sk: &mut Sketch, ci: usize, at: Vec2) -> Result<String> {
let cmd = "sketch.extend";
let Some(aim) = arc_aim(sk, ci, at, cmd)? else {
return Err(bad(cmd, "nothing to extend to"));
};
let stop = arc_stop(sk, ci, &aim);
// The arc's own far end is where the arc begins again: moving the end onto it would leave a
// whole circle, so the gap is filled by a new arc joining that end.
if stop.is_some_and(|p| p == aim.far) || arc_end_held(sk, ci, aim.end) {
return add_arc_extension(sk, ci, &aim, stop);
}
// A free end moves along instead, if the solver lets it.
let original = sk.point(aim.end).unwrap_or_default();
if let Some(pt) = sk.points.get_mut(aim.end) {
pt.pos = aim.hit;
}
let before = sk.points.iter().map(|p| p.pos).collect::<Vec<_>>();
let hold = solidcraft_sketch::Hold { points: (0..sk.points.len()).filter(|i| *i != aim.end).collect(), radii: (0..sk.curves.len()).collect() };
let moved = solidcraft_sketch::solve_with(sk, &hold, None, solidcraft_sketch::Analysis::StatusOnly, None).ok()
&& sk.point(aim.end).is_some_and(|point| point.dist(aim.hit) <= TOL)
&& sk.points.iter().enumerate().all(|(i, point)| i == aim.end || point.pos.dist(before[i]) <= TOL);
if !moved {
// The solve could not put the end where it belongs: the extension is a new arc instead.
if let Some(pt) = sk.points.get_mut(aim.end) {
pt.pos = original;
}
return add_arc_extension(sk, ci, &aim, stop);
}
// Held to what stopped it, the end stays on the geometry it reached.
pin(sk, aim.end, aim.cutter)?;
Ok(sk.points.get(aim.end).map(|x| x.id.clone()).unwrap_or_default())
}
/// The arc `sketch.extend` would add from the end of `ci` nearest `hover_pos`, for the viewport to
/// show before the click: the new arc as points, the growing end first. `None` when extending
/// there is not possible (nothing on the way stops it, or stopping it is ambiguous).
pub fn extend_arc_preview(sk: &solidcraft_sketch::Sketch, ci: usize, hover_pos: Vec2) -> Option<Vec<Vec2>> {
let aim = arc_aim(sk, ci, hover_pos, "sketch.extend").ok().flatten()?;
Some(aim.points())
}
fn extend(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.extend";
let at = req_vec2(cmd, p, "at")?;
@@ -611,35 +1059,60 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {
}
let ci = curve_arg(sk, p, cmd)?;
refuse_offset_ends(sk, ci, "extend", cmd)?;
// An arc grows along its own circle, either way round: in place when its end is free, as
// a new arc when the end already carries geometry.
if matches!(sk.curves.get(ci).map(|c| &c.kind), Some(CurveKind::Arc { .. })) {
return extend_arc(sk, ci, at);
}
let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?;
let (pa, pb) = match sk.curves.get(ci).map(|c| c.kind.clone()) {
Some(CurveKind::Line { a, b }) | Some(CurveKind::Arc { a, b, .. }) => (a, b),
_ => return Err(bad(cmd, "only lines and arcs can be extended")),
let Some(CurveKind::Line { a: pa, b: pb }) = sk.curves.get(ci).map(|c| c.kind.clone()) else {
return Err(bad(cmd, "only lines and arcs can be extended"));
};
let (qa, qb) = (sk.point(pa).unwrap_or_default(), sk.point(pb).unwrap_or_default());
let at_b = at.dist(qb) <= at.dist(qa);
let end = if at_b { pb } else { pa };
let shared = sk.curves.iter().enumerate().filter(|(i, c)| *i != ci && uses(c, end)).count();
if shared > 0 || sk.points.get(end).is_some_and(|q| q.fixed) {
return Err(bad(cmd, "that end is connected to other geometry"));
let neighbors: Vec<_> = sk.curves.iter().enumerate().filter(|(i, c)| *i != ci && uses(c, end)).collect();
// Fixed ends are allowed: an extension that cannot move an end adds a new line from it,
// so the fixed point itself never moves (a diagonal ending at the origin can be
// continued through it).
let extension_direction = {
let p_end = sk.point(end).unwrap_or_default();
let p_other = if at_b { qa } else { qb };
(p_end - p_other).normalized()
}
// Candidate hits on the unbounded curve beyond the chosen end.
let unbounded = match sh {
Shape::Line { .. } => sh,
Shape::Round { c, r, start, .. } => Shape::Round { c, r, start, sweep: TAU },
};
let (_, t1) = sh.range();
.ok_or_else(|| bad(cmd, "cannot determine extension direction"))?;
// A neighbour running on the same way as the extension has it nowhere to go.
for (_, c) in &neighbors {
// Arcs do not block a line: the line runs past the point they share.
if matches!(c.kind, CurveKind::Arc { .. }) {
continue;
}
if let CurveKind::Line { a: na, b: nb } = c.kind {
let other_idx = if na == end { nb } else { na };
let other_pos = sk.point(other_idx).unwrap_or_default();
// From the shared point to the neighbour's other end.
let v = other_pos - sk.point(end).unwrap_or_default();
if v.cross(extension_direction).abs() < 1e-6 && v.dot(extension_direction) > 1e-6 {
return Err(bad(cmd, "that end is connected to other geometry"));
}
}
}
// Candidate stops on the line's unbounded support beyond the chosen end.
let length = qa.dist(qb);
let mut best: Option<(f64, Vec2, usize)> = None;
let mut ambiguous = false;
let mut budget = 1_000_000usize;
let mut segment_count = 0usize;
for (oi, _) in sk.curves.iter().enumerate() {
for (oi, curve) in sk.curves.iter().enumerate() {
if oi == ci {
continue;
}
let mut pieces = sk.exact_segs(oi).unwrap_or_else(|| sk.segs(oi));
// An infinite line (#1359) is a boundary along its whole line.
if sk.curves.get(oi).is_some_and(|c| c.infinite) {
if curve.infinite {
pieces = pieces.iter().map(|s| support::endless(s, sh.point(sh.param(at)))).collect();
}
segment_count += pieces.len();
@@ -647,50 +1120,97 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "too many exact curve pieces to extend safely"));
}
for piece in &pieces {
for q in support::hits(&unbounded, piece, &mut budget)? {
for q in support::hits(&sh, piece, &mut budget)? {
let t = sh.param(q);
let gap = match sh {
Shape::Line { a, b } => {
let l = a.dist(b);
if at_b { (t - 1.0) * l } else { -t * l }
}
Shape::Round { r, .. } => {
// A hit already inside the arc cannot lengthen either end. In
// particular, extending the start must not turn a quarter into an eighth.
if t <= t1 + TOL / r.max(1e-12) || t >= TAU - TOL / r.max(1e-12) {
continue;
}
if at_b { (t - t1) * r } else { (TAU - t) * r }
}
};
if gap > TOL * 10.0 {
if best.is_none_or(|b| gap < b.0 - TOL) {
best = Some((gap, q, oi));
ambiguous = false;
} else if best.is_some_and(|b| (gap - b.0).abs() <= TOL && (b.2 != oi || b.1.dist(q) > TOL)) {
ambiguous = true;
}
let gap = if at_b { (t - 1.0) * length } else { -t * length };
if gap <= TOL * 10.0 {
continue;
}
if best.is_none_or(|x| gap < x.0 - TOL) {
best = Some((gap, q, oi));
ambiguous = false;
} else if best.is_some_and(|x| (gap - x.0).abs() <= TOL && (x.2 != oi || x.1.dist(q) > TOL)) {
ambiguous = true;
}
}
}
}
if ambiguous {
return Err(bad(cmd, "multiple curves stop the extension at the same distance"));
}
let (_, q, oi) = best.ok_or_else(|| bad(cmd, "nothing to extend to"))?;
// Nothing in the way stops the extension: it runs as far as the preview draws, so the
// click adds the line the user saw rather than reporting that there is nothing to reach.
let (q, cutter) = match best {
Some((_, q, oi)) => {
// A target that is already another curve's end would double that geometry.
if ends_at_curve_end(sk, ci, q) {
return Err(bad(cmd, "the extension target coincides with existing geometry"));
}
(q, Some(oi))
}
None => (sk.point(end).unwrap_or_default() + extension_direction * EXTEND_REACH, None),
};
// The end joined to other geometry stays where it is: add a line from it.
if !neighbors.is_empty() {
let np = sk.add_point(q, None)?;
sk.add_curve(CurveKind::Line { a: end, b: np }, None)?;
return Ok(sk.points.get(np).map(|x| x.id.clone()).unwrap_or_default());
}
// An end held by a constraint, or lying on a circle or arc, stays where it is too: the
// extension is a new line from it.
let end_is_held = sk.constraints.iter().any(|c| {
use solidcraft_sketch::ConstraintKind::*;
match c.kind {
Coincident { p, q } => p == end || q == end,
Fix { p } => p == end,
PointOnCurve { p, .. } => p == end,
Midpoint { p, .. } => p == end,
HorizontalPoints { p, q } | VerticalPoints { p, q } => p == end || q == end,
Symmetric { p, q, .. } => p == end || q == end,
_ => false,
}
}) || {
// Geometric check: does the endpoint lie on any circle or arc?
let ep = sk.point(end).unwrap_or_default();
sk.curves.iter().any(|curve| match curve.kind {
CurveKind::Circle { c, r } => (ep - sk.point(c).unwrap_or_default()).len().abs() - r < 1e-6,
// This is an arc's own start or end: it sits on that arc.
CurveKind::Arc { a, b, .. } => ep.dist(sk.point(a).unwrap_or_default()) < 1e-6 || ep.dist(sk.point(b).unwrap_or_default()) < 1e-6,
_ => false,
})
};
if end_is_held {
let np = sk.add_point(q, None)?;
sk.add_curve(CurveKind::Line { a: end, b: np }, None)?;
return Ok(sk.points.get(np).map(|x| x.id.clone()).unwrap_or_default());
}
// A free end moves along instead, if the solver lets it.
if let Some(pt) = sk.points.get_mut(end) {
pt.pos = q;
}
pin(sk, end, oi)?;
// Held to what stopped it, an end stays where the extension put it; an end with nothing
// to hold it is simply placed there.
if let Some(cutter) = cutter {
pin(sk, end, cutter)?;
}
let before = sk.points.iter().map(|p| p.pos).collect::<Vec<_>>();
let hold = solidcraft_sketch::Hold { points: (0..sk.points.len()).filter(|i| *i != end).collect(), radii: (0..sk.curves.len()).collect() };
if !solidcraft_sketch::solve_with(sk, &hold, None, solidcraft_sketch::Analysis::StatusOnly, None).ok()
|| sk.point(end).is_none_or(|point| point.dist(q) > TOL)
|| sk.points.iter().enumerate().any(|(i, point)| i != end && point.pos.dist(before[i]) > TOL)
{
return Err(bad(cmd, "the extension conflicts with constraints or cannot preserve its original support"));
let moved = solidcraft_sketch::solve_with(sk, &hold, None, solidcraft_sketch::Analysis::StatusOnly, None).ok()
&& sk.point(end).is_some_and(|point| point.dist(q) <= TOL)
&& sk.points.iter().enumerate().all(|(i, point)| i == end || point.pos.dist(before[i]) <= TOL);
if moved {
return Ok(sk.points.get(end).map(|x| x.id.clone()).unwrap_or_default());
}
Ok(sk.points.get(end).map(|x| x.id.clone()).unwrap_or_default())
// The solve could not put the end where it belongs: add a new line instead.
let np = sk.add_point(q, None)?;
sk.add_curve(CurveKind::Line { a: end, b: np }, None)?;
Ok(sk.points.get(np).map(|x| x.id.clone()).unwrap_or_default())
})?;
Ok(json!({"moved": out, "sketch": info}))
}
@@ -224,6 +224,177 @@ fn exact_extend_arc_rejects_interior_hit_atomically() {
assert_eq!(s.undo.len(), history);
}
#[test]
fn arc_extend_grows_a_free_end_in_place_to_the_first_geometry() {
let mut s = new_sketch();
let arc = ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[10,0],"end":[0,10],"connect":false}))["curves"])[0].clone();
// A cutter crossing the circle at `deg`, two millimetres either side of it.
let cut = |s: &mut Session, deg: f64| {
let a = deg.to_radians();
let (ux, uy) = (a.cos(), a.sin());
let (x, y) = (10.0 * ux, 10.0 * uy);
run(s, "sketch.line", json!({"points": [[x - 2.0 * ux, y - 2.0 * uy], [x + 2.0 * ux, y + 2.0 * uy]], "connect": false, "infer": false}));
};
// Past the arc's end there are two: the extension stops at the nearer one.
cut(&mut s, 200.0);
cut(&mut s, 260.0);
let before = sketch(&s);
let round = |sk: &solidcraft_sketch::Sketch, ci: usize| match sk.shape(ci) {
Some(solidcraft_sketch::Shape::Round { start, sweep, .. }) => (start.to_degrees(), sweep.to_degrees()),
other => panic!("{other:?}"),
};
// A free end grows in place: the arc itself reaches the 200° stop, so the sketch gains no
// curve and no point.
run(&mut s, "sketch.extend", json!({"curve": arc, "at": [0, 10]}));
let sk = sketch(&s);
let ci = sk.curve_index(&arc).unwrap();
assert_eq!((sk.curves.len(), sk.points.len()), (before.curves.len(), before.points.len()), "the arc itself reaches the stop");
let (start, sweep) = round(&sk, ci);
assert!(start.abs() < 1e-6 && (sweep - 200.0).abs() < 1e-6, "{start}, {sweep}");
assert!(sk.shape(ci).is_some_and(|sh| sh.dist(Vec2::new(10.0 * 200.0_f64.to_radians().cos(), 10.0 * 200.0_f64.to_radians().sin())) < 1e-6));
// The other way round: clockwise from the arc's start to the 300° cutter, again in place.
cut(&mut s, 300.0);
let before = sketch(&s);
run(&mut s, "sketch.extend", json!({"curve": arc, "at": [10, 0]}));
let sk = sketch(&s);
assert_eq!((sk.curves.len(), sk.points.len()), (before.curves.len(), before.points.len()), "the arc itself reaches the stop");
let (start, sweep) = round(&sk, ci);
assert!((start.rem_euclid(360.0) - 300.0).abs() < 1e-6 && (sweep - 260.0).abs() < 1e-6, "{start}, {sweep}");
}
#[test]
fn arc_extend_joins_an_end_that_already_carries_geometry_with_a_new_arc() {
let mut s = new_sketch();
let arc = ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[10,0],"end":[0,10],"connect":false}))["curves"])[0].clone();
// A line running on from the arc's end, and a circle crossing the arc's circle further round.
let line = ids(&run(&mut s, "sketch.line", json!({"points":[[0,10],[0,20]],"connect":true,"infer":false}))["curves"])[0].clone();
run(&mut s, "sketch.circle.center", json!({"center":[12,0],"radius":10,"connect":false}));
let before = sketch(&s);
let end = before.resolve_point(&format!("{arc}.end")).expect("the arc's end");
let line_start = before.resolve_point(&format!("{line}.start")).expect("the line's start");
// `connect` ties the line's own point to the arc's end, so the end carries geometry there.
assert!(before.point(end).zip(before.point(line_start)).is_some_and(|(a, b)| a.dist(b) < 1e-9));
assert!(
before
.constraints
.iter()
.any(|c| matches!(c.kind, ConstraintKind::Coincident { p, q } if (p, q) == (end, line_start) || (p, q) == (line_start, end)))
);
run(&mut s, "sketch.extend", json!({"curve": arc, "at": [0, 10]}));
let sk = sketch(&s);
let ci = sk.curve_index(&arc).unwrap();
// The end the line starts at stays where it is, so the arc keeps its geometry...
assert!(matches!(sk.shape(ci).unwrap(), solidcraft_sketch::Shape::Round { sweep, .. } if (sweep - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
// ...and the extension is a new arc from that end to the circle's crossing.
let grown = (0..sk.curves.len())
.find(|i| sk.curves[*i].id != arc && sk.curves[*i].id != line && matches!(sk.curves[*i].kind, CurveKind::Arc { .. }))
.expect("a new arc");
let sh = sk.shape(grown).unwrap();
assert!(sh.dist(Vec2::new(0.0, 10.0)) < 1e-6 && sh.dist(Vec2::new(6.0, -8.0)) < 1e-6, "{sh:?}");
assert_eq!(sk.points.len(), before.points.len() + 1, "the crossing point is new");
}
#[test]
fn arc_extend_closes_the_gap_onto_the_arcs_own_far_end() {
let mut s = new_sketch();
let arc = ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[10,0],"end":[0,10],"connect":false}))["curves"])[0].clone();
// A line touching the circle at the arc's far end: the only geometry on the way round.
run(&mut s, "sketch.line", json!({"points":[[-3,10],[3,10]],"connect":false,"infer":false}));
let before = sketch(&s);
// Growing the arc's start clockwise runs three quarters round to its end.
run(&mut s, "sketch.extend", json!({"curve": arc, "at": [10, 0]}));
let sk = sketch(&s);
let ci = sk.curve_index(&arc).unwrap();
assert!(matches!(sk.shape(ci).unwrap(), solidcraft_sketch::Shape::Round { sweep, .. } if (sweep - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
let closed = (0..sk.curves.len()).find(|i| *i != ci && matches!(sk.curves[*i].kind, CurveKind::Arc { .. })).expect("a new arc");
let sh = sk.shape(closed).unwrap();
assert!(sh.dist(Vec2::new(0.0, 10.0)) < 1e-6 && sh.dist(Vec2::new(10.0, 0.0)) < 1e-6, "{sh:?}");
assert!(matches!(sh, solidcraft_sketch::Shape::Round { sweep, .. } if (sweep - 3.0 * std::f64::consts::FRAC_PI_2).abs() < 1e-9), "{sh:?}");
// The new arc joins the arc's far end instead of laying a second point over it.
assert_eq!(sk.points.len(), before.points.len());
}
#[test]
fn arc_extend_stops_on_another_circle_or_arc() {
let arc_from = |s: &mut Session| {
ids(&run(s, "sketch.arc.center_point", json!({"center":[0,0],"start":[10,0],"end":[0,10],"connect":false}))["curves"])[0].clone()
};
// A whole circle crossing the arc's circle stops the extension where they cross: a free end
// grows to that point, so the arc itself reaches it without new geometry.
let mut s = new_sketch();
let arc = arc_from(&mut s);
run(&mut s, "sketch.circle.center", json!({"center":[12,0],"radius":10}));
let before = sketch(&s);
run(&mut s, "sketch.extend", json!({"curve": arc, "at": [0,10]}));
let sk = sketch(&s);
assert_eq!((sk.curves.len(), sk.points.len()), (before.curves.len(), before.points.len()), "the arc itself reaches the crossing");
let sh = sk.shape(sk.curve_index(&arc).unwrap()).unwrap();
assert!(sh.dist(Vec2::new(6.0, -8.0)) < 1e-6 && sh.dist(Vec2::new(0.0, 10.0)) < 1e-6, "{sh:?}");
// The arc keeps its quarter and grows by the 216.9° it travelled to the crossing.
let grown = std::f64::consts::FRAC_PI_2 + 216.869_897_f64.to_radians();
assert!(matches!(sh, solidcraft_sketch::Shape::Round { sweep, .. } if (sweep - grown).abs() < 1e-6), "{sh:?}");
// The same stop when another arc ends exactly on the crossing: the growing end is free, so the
// arc itself grows onto that point instead of laying a second point over it.
let mut s = new_sketch();
let arc = arc_from(&mut s);
let other =
ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[12,0],"start":[2,0],"end":[6,-8],"connect":false}))["curves"])[0].clone();
let sk = sketch(&s);
let other_end = match sk.curves[sk.curve_index(&other).expect("the other arc")].kind {
CurveKind::Arc { b, .. } => b,
_ => panic!("an arc"),
};
let before = sketch(&s);
run(&mut s, "sketch.extend", json!({"curve": arc, "at": [0,10]}));
let sk = sketch(&s);
assert_eq!((sk.curves.len(), sk.points.len()), (before.curves.len(), before.points.len()), "the arc itself reaches the point that is there");
let ci = sk.curve_index(&arc).expect("the arc");
// The arc keeps its own end point, tied to the point that was already there.
let end = sk.resolve_point(&format!("{arc}.end")).expect("the arc's end");
assert!(sk.point(end).zip(sk.point(other_end)).is_some_and(|(a, b)| a.dist(b) < 1e-9), "the arc ends on the other arc's end");
assert!(
sk.constraints
.iter()
.any(|c| matches!(c.kind, ConstraintKind::Coincident { p, q } if (p, q) == (end, other_end) || (p, q) == (other_end, end)))
);
let sh = sk.shape(ci).expect("the arc's shape");
assert!(sh.dist(Vec2::new(6.0, -8.0)) < 1e-6, "{sh:?}");
}
#[test]
fn extend_with_nothing_in_the_way_adds_the_line_the_preview_shows() {
// The preview paints the extension [`EXTEND_REACH`] past the end when nothing stops it: the
// click adds that line instead of reporting that there is nothing to reach.
let mut s = new_sketch();
let line = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[10,0]],"connect":false,"infer":false}))["curves"])[0].clone();
let sk = sketch(&s);
let ci = sk.curve_index(&line).expect("the line");
let preview = super::extend_preview(&sk, ci, Vec2::new(10.0, 0.0)).expect("a preview with nothing in the way");
assert!(preview.dist(Vec2::new(60.0, 0.0)) < 1e-9, "{preview:?}");
// A free end moves out there, so the sketch keeps one line.
run(&mut s, "sketch.extend", json!({"curve": line, "at": [10.0, 0.0]}));
let sk = sketch(&s);
assert_eq!(sk.curves.len(), 1);
let end = sk.point(sk.resolve_point(&format!("{line}.end")).expect("the line's end")).expect("a point");
assert!(end.dist(Vec2::new(60.0, 0.0)) < 1e-6, "{end:?}");
// An end joined to other geometry stays where it is, so the same click adds a new line out to
// the preview's end.
let mut s = new_sketch();
let lines = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[10,0],[10,10]],"connect":false,"infer":false}))["curves"]);
let sk = sketch(&s);
let ci = sk.curve_index(&lines[0]).expect("the line");
let preview = super::extend_preview(&sk, ci, Vec2::new(10.0, 0.0)).expect("a preview with nothing in the way");
assert!(preview.dist(Vec2::new(60.0, 0.0)) < 1e-9, "{preview:?}");
run(&mut s, "sketch.extend", json!({"curve": lines[0], "at": [10.0, 0.0]}));
let sk = sketch(&s);
assert_eq!(sk.curves.len(), 3);
let added = sk.curves.len() - 1;
assert!(sk.shape(added).is_some_and(|sh| sh.dist(Vec2::new(60.0, 0.0)) < 1e-6), "{added}");
assert!(sk.shape(ci).is_some_and(|sh| sh.dist(Vec2::new(10.0, 0.0)) < 1e-6), "the line being extended stays put");
}
#[test]
fn exact_extend_refuses_ambiguous_stop_without_history_change() {
let mut s = new_sketch();
+10 -2
View File
@@ -99,7 +99,8 @@ fn sound_or_empty(s: &Session) {
#[test]
fn extend_cases() {
// A line extends to a circle; to a spline; with nothing to reach it is a clear error.
// A line extends to a circle; to a spline; with nothing to reach it runs on as far as the
// preview showed.
let mut s = new_sketch();
add(&mut s, "sketch.circle.center", json!({"center": [20, 0], "radius": 5}));
let l = add(&mut s, "sketch.line", json!({"points": [[0, 0], [5, 0]]}))[0].clone();
@@ -119,8 +120,15 @@ fn extend_cases() {
sound(&s);
let mut s = new_sketch();
let l = add(&mut s, "sketch.line", json!({"points": [[0, 0], [5, 0]]}))[0].clone();
assert!(s.execute("sketch.extend", &json!({"curve": l, "at": [5, 0]})).is_err());
s.execute("sketch.extend", &json!({"curve": l, "at": [5, 0]})).unwrap();
sound(&s);
let id = s.active_sketch.unwrap();
let st = s.model.state();
let ss = st.sketch(id).unwrap();
let li = ss.sketch.curve_index(&l).unwrap();
let end = ss.sketch.segs(li).iter().map(|g| g.end().x.max(g.start().x)).fold(f64::NEG_INFINITY, f64::max);
assert!((end - (5.0 + super::EXTEND_REACH)).abs() < 1e-6, "{end}");
drop(st);
// An arc extends along its circle to a line.
let mut s = new_sketch();
add(&mut s, "sketch.line", json!({"points": [[-20, -3], [20, -3]]}));
+8 -3
View File
@@ -88,7 +88,9 @@ pub(super) fn hits(support: &Shape, seg: &Seg2, budget: &mut usize) -> Result<Ve
if let Shape::Line { a: pa, b: pb } = *support
&& (pb - pa).normalized().is_some_and(|d| d.cross(a - pa).abs() < 1e-9 && d.cross(b - pa).abs() < 1e-9)
{
return Err(bad("sketch.extend", "the continuation overlaps another curve"));
// A collinear line is passed over (no hits) so extend can find the next target on
// its way instead of failing.
return Ok(Vec::new());
}
return Ok(intersections(support, &other)
.into_iter()
@@ -105,7 +107,8 @@ pub(super) fn hits(support: &Shape, seg: &Seg2, budget: &mut usize) -> Result<Ve
&& c.dist(center) < 1e-9
&& (r - radius).abs() < 1e-9
{
return Err(bad("sketch.extend", "the continuation overlaps another curve"));
// The same circle is passed over, so extend can find the next target.
return Ok(Vec::new());
}
return Ok(intersections(support, &other)
.into_iter()
@@ -144,7 +147,9 @@ pub(super) fn hits(support: &Shape, seg: &Seg2, budget: &mut usize) -> Result<Ve
}
};
if c.iter().all(|v| v.abs() < 1e-28) {
return Err(bad("sketch.extend", "the continuation overlaps another curve"));
// A zero polynomial: the curve lies on the support (infinite line or circle). Pass it
// over, so extend can find the next target.
return Ok(Vec::new());
}
let mut out = Vec::new();
for t in roots(&c, budget)? {
+33
View File
@@ -1136,6 +1136,31 @@ pub(crate) fn trim_hover_piece(app: &SolveApp, sketch: u64, id: &str) -> Option<
piece
}
/// Extend preview: the geometry that would be added, based on the hover position over curve `id`
/// of `sketch`. Returns None when extend is not active or the geometry does not support a
/// preview. An arc grows along its own circle, in either direction, as a new arc.
fn extend_preview_piece(app: &SolveApp, sketch: u64, id: &str) -> Option<Vec<Vec2>> {
let tool = app.tool.as_ref().filter(|t| t.cmd == "sketch.extend")?;
let hover = tool.hover.as_ref()?;
if active_sketch(app) != Some(sketch) {
return None;
}
let st = app.session.world_state();
let sk = st.sketch(sketch)?;
let hover_pos = hover.0;
let ci = sk.sketch.curve_index(id)?;
let kind = sk.sketch.curves.get(ci)?.kind.clone();
// Arcs extend along their circle either way round, up to the first geometry in the way.
if let solidcraft_engine::sketch::CurveKind::Arc { .. } = kind {
return solidcraft_engine::cmd::extend_arc_preview(&sk.sketch, ci, hover_pos);
}
let solidcraft_engine::sketch::CurveKind::Line { a, b } = kind else { return None };
let at_b = hover_pos.dist(sk.sketch.point(b)?) <= hover_pos.dist(sk.sketch.point(a)?);
let end = sk.sketch.point(if at_b { b } else { a })?;
let hit = solidcraft_engine::cmd::extend_preview(&sk.sketch, ci, hover_pos)?;
Some(vec![end, hit])
}
/// Rubber band for point tools and pick markers.
pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {
let Some(sid) = active_sketch(app) else { return };
@@ -1150,6 +1175,14 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {
// In the error colour, thicker than a hover: it is what the click deletes.
crate::tools::paint_sketch_path(&world, 0, painter, proj, Stroke::new(4.5, tk.error));
}
// Extend preview: the line or arc that would be added (or the end that would move).
if let Some(crate::viewport::Hit::SketchCurve { sketch, id, .. }) = &app.viewport.hover
&& let Some(preview_line) = extend_preview_piece(app, *sketch, id)
{
let world: Vec<_> = preview_line.iter().map(|p| ss.plane.to_world(*p)).collect();
// Draw the preview extension line using preview_new color (same as fillet/chamfer preview)
crate::tools::paint_sketch_path(&world, 0, painter, proj, Stroke::new(2.0, tk.preview_new.gamma_multiply(0.9)));
}
let stroke = Stroke::new(1.5, tk.sketch_accent);
// A Trim drag: the pieces it will remove, then the path drawn so far.
if t.cmd == "sketch.trim" && !t.pts.is_empty() {