* Kernel: the B-rep record and the native body file come from solidcore-record SolidCraft's portable B-rep record (`solidcraft_geom::brep`: brep.rs, topology, history, envelope, part, curve2) and the native body file (`solidcraft_kernel::native`: the tagged binary codec and the container) move to solidcore's `solidcore-record` crate: geometry as data, with structural validation and no maths (solidcore's docs/layers.md, stage 1). Every caller uses `solidcore_record::brep` and `solidcore_record::native`; the old copies are deleted. What computes from coordinates stays with the kernel, in geom's `brep`: - `brep::check`: the record's geometric checks (orthonormal frames, non-degenerate planes, unit revolution axes, non-singular placements). `check::validate` and `check::validate_built` are the record's validation and these together, and every caller of `Brep::validate` uses them, so what is accepted is unchanged; - `brep::label`: a surface's natural ranges (a cone's apex), `curve_interval`, `edge_curve_interval` and `form_turns`; - `brep::pcurve::eval`: a pcurve's point; - `geometry::check`, `placement::moved` and `split_edges` become functions on the record. The kernel's native module keeps the conversion between a body and its saved record (metadata.rs) and checks the decoded record's geometry. `native/analytic.rs`, which no module declared, is deleted. solidcore-record is pinned to its rev on solidcore's `layer-record` branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NvoxKMbMFSQU8tzRtoJhtT * Geometry: Vec2, Vec3, Plane and the profile types come from solidcore-record The plain data of vectors and points, sketch planes and planar profiles (`Seg2`, `Loop2`, `Region2`) moves to `solidcore-record`, with its constants and component-wise operators only (owner decision, solidcore layer split). Their geometry stays in geom as traits: `Vec2Geom`, `Vec3Geom`, `PlaneGeom`, `Seg2Geom`, `Loop2Geom`, `Region2Geom`, `Seg2ArcFit`, `Loop2ArcFit` and `Region2ArcFit`, in scope with `use solidcraft_geom::prelude::*`. Every caller names the types from `solidcore_record`; geom no longer defines or re-exports them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NvoxKMbMFSQU8tzRtoJhtT * Kernel: pin solidcore-record to solidcore main f5e8e9a29 solidcore-record is merged on solidcore main (tangency-labs/solidcore#2519); its crate there is identical to the rev pinned before but for its clippy configuration. The lock is regenerated against the merged rev. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NvoxKMbMFSQU8tzRtoJhtT --------- Co-authored-by: jyviko <2501648+jyviko@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1304 lines
65 KiB
Rust
1304 lines
65 KiB
Rust
//! Interactive sketch tools: click points on the sketch plane (or pick sketch entities) and the
|
||
//! tool runs the matching command. Tools are UI state only; the work is done by commands.
|
||
|
||
use egui::{Pos2, Stroke};
|
||
use serde_json::{Value, json};
|
||
use solidcore_record::Vec2;
|
||
use solidcraft_engine::geom::prelude::*;
|
||
|
||
use crate::SolveApp;
|
||
use crate::tool_modifiers::{Audit, Scope, ToolModifiers};
|
||
use crate::viewport::{Hit, Proj, pick_for_tool as pick, sketch_point_at};
|
||
|
||
const DRAW_SCOPES: &[Scope] = &[Scope::SketchDraw, Scope::SketchDrag];
|
||
|
||
/// Per-tool modifier descriptors owned by this host file (coordinator seeds / audits these).
|
||
pub const MODIFIERS: &[ToolModifiers] = &[
|
||
ToolModifiers { tool: "sketch.line", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.rectangle.two_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.rectangle.center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.rectangle.rounded", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.rectangle.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.circle.center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.circle.two_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.circle.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.arc.three_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.arc.center_point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.polygon.inscribed", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.polygon.circumscribed", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.polygon.edge", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.slot.center_to_center", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.slot.overall", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.point", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
ToolModifiers { tool: "sketch.dimension", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },
|
||
// Constraint tools: pick-only; no tool-specific modifier chords.
|
||
ToolModifiers { tool: "sketch.constraint.horizontal_vertical", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.fix", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.coincident", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.tangent", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.equal", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.parallel", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.perpendicular", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.concentric", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.collinear", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.midpoint", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
ToolModifiers { tool: "sketch.constraint.symmetry", scopes: &[], bindings: &[], audit: Audit::VerifiedNoOp },
|
||
];
|
||
|
||
#[cfg(test)]
|
||
#[path = "sketch_display_preview_tests.rs"]
|
||
mod display_preview_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "sketch_neutral_click_tests.rs"]
|
||
mod neutral_click_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "symmetry_pick_tests.rs"]
|
||
mod symmetry_pick_tests;
|
||
|
||
#[cfg(test)]
|
||
#[path = "sketch_centre_align_ui_tests.rs"]
|
||
mod centre_align_ui_tests;
|
||
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum Kind {
|
||
/// Click points; `n` points complete the shape (0 = chain until finished).
|
||
Draw(usize),
|
||
/// Pick sketch entities; `n` picks run the command.
|
||
Pick(usize),
|
||
/// Pick one straight line, or two distinct points to align.
|
||
HorizontalVertical,
|
||
Dimension,
|
||
/// A tool from `sketch_tools` (it handles its own clicks).
|
||
Ext,
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
pub struct Tool {
|
||
pub cmd: &'static str,
|
||
pub kind: Kind,
|
||
/// Clicked points (sketch coordinates) and the sketch point they snapped to.
|
||
pub pts: Vec<(Vec2, Option<String>)>,
|
||
pub hover: Option<(Vec2, Option<String>)>,
|
||
/// Picked entity ids.
|
||
pub picks: Vec<String>,
|
||
/// Horizontal/Vertical point references, or the Dimension tool's midpoint snaps.
|
||
pub point_picks: Vec<Value>,
|
||
/// Inline dimension boxes for the shape being drawn, the point count they were made for,
|
||
/// and whether the first box should take the keyboard.
|
||
pub dims: Vec<crate::sketch_dims::DimBox>,
|
||
/// Locked inputs from earlier stages of this shape (arc radius, slot length).
|
||
pub dim_history: Vec<crate::sketch_dims::DimBox>,
|
||
pub dims_stage: usize,
|
||
pub dims_focus: bool,
|
||
/// How far (radians, signed) the cursor has gone round a centre-point arc's centre since its
|
||
/// start was placed: its sign is the way the arc runs (#6645).
|
||
pub arc_turn: f64,
|
||
/// Where each point was placed and the sketch points the snap lined it up with (#7828):
|
||
/// constrained to them once the shape is made.
|
||
pub lined: Vec<(Vec2, Vec<crate::sketch_tools::Lined>)>,
|
||
/// The Line tool's chain, which a rest on its last point switches to tangent arcs and back
|
||
/// (#9489).
|
||
pub chain: crate::sketch_line_arc::LineChain,
|
||
/// The construction line tools' Construction/Normal switch (#10258): a segment with a length
|
||
/// becomes a normal sketch line. Each start of a tool begins at Construction.
|
||
pub normal: bool,
|
||
}
|
||
|
||
impl Tool {
|
||
pub fn for_command(id: &str) -> Option<Tool> {
|
||
let (cmd, kind): (&'static str, Kind) = match id {
|
||
"sketch.line" => ("sketch.line", Kind::Draw(0)),
|
||
"sketch.rectangle.two_point" => ("sketch.rectangle.two_point", Kind::Draw(2)),
|
||
"sketch.rectangle.center" => ("sketch.rectangle.center", Kind::Draw(2)),
|
||
"sketch.rectangle.rounded" => ("sketch.rectangle.rounded", Kind::Draw(2)),
|
||
"sketch.rectangle.three_point" => ("sketch.rectangle.three_point", Kind::Draw(3)),
|
||
"sketch.circle.center" => ("sketch.circle.center", Kind::Draw(2)),
|
||
"sketch.circle.two_point" => ("sketch.circle.two_point", Kind::Draw(2)),
|
||
"sketch.circle.three_point" => ("sketch.circle.three_point", Kind::Draw(3)),
|
||
"sketch.arc.three_point" => ("sketch.arc.three_point", Kind::Draw(3)),
|
||
"sketch.arc3d" => ("sketch.arc3d", Kind::Draw(3)),
|
||
"sketch.line3d" => ("sketch.line3d", Kind::Draw(0)),
|
||
"sketch.spline3d" => ("sketch.spline3d", Kind::Draw(0)),
|
||
"sketch.point3d" => ("sketch.point3d", Kind::Draw(1)),
|
||
"sketch.arc.center_point" => ("sketch.arc.center_point", Kind::Draw(3)),
|
||
"sketch.polygon.inscribed" => ("sketch.polygon.inscribed", Kind::Draw(2)),
|
||
"sketch.polygon.circumscribed" => ("sketch.polygon.circumscribed", Kind::Draw(2)),
|
||
"sketch.polygon.edge" => ("sketch.polygon.edge", Kind::Draw(2)),
|
||
"sketch.slot.center_to_center" => ("sketch.slot.center_to_center", Kind::Draw(3)),
|
||
"sketch.slot.overall" => ("sketch.slot.overall", Kind::Draw(3)),
|
||
"sketch.point" => ("sketch.point", Kind::Draw(1)),
|
||
"sketch.dimension" => ("sketch.dimension", Kind::Dimension),
|
||
"sketch.constraint.horizontal_vertical" => ("sketch.constraint.horizontal_vertical", Kind::HorizontalVertical),
|
||
"sketch.constraint.fix" => ("sketch.constraint.fix", Kind::Pick(1)),
|
||
"sketch.constraint.coincident" => ("sketch.constraint.coincident", Kind::Pick(2)),
|
||
"sketch.constraint.tangent" => ("sketch.constraint.tangent", Kind::Pick(2)),
|
||
"sketch.constraint.equal" => ("sketch.constraint.equal", Kind::Pick(2)),
|
||
"sketch.constraint.parallel" => ("sketch.constraint.parallel", Kind::Pick(2)),
|
||
"sketch.constraint.perpendicular" => ("sketch.constraint.perpendicular", Kind::Pick(2)),
|
||
"sketch.constraint.concentric" => ("sketch.constraint.concentric", Kind::Pick(2)),
|
||
"sketch.constraint.collinear" => ("sketch.constraint.collinear", Kind::Pick(2)),
|
||
"sketch.constraint.midpoint" => ("sketch.constraint.midpoint", Kind::Pick(2)),
|
||
"sketch.constraint.symmetry" => ("sketch.constraint.symmetry", Kind::Pick(3)),
|
||
_ => return crate::sketch_tools::tool_for(id),
|
||
};
|
||
Some(Tool {
|
||
cmd,
|
||
kind,
|
||
pts: Vec::new(),
|
||
hover: None,
|
||
picks: Vec::new(),
|
||
point_picks: Vec::new(),
|
||
dims: Vec::new(),
|
||
dim_history: Vec::new(),
|
||
dims_stage: usize::MAX,
|
||
dims_focus: false,
|
||
arc_turn: 0.0,
|
||
lined: Vec::new(),
|
||
chain: Default::default(),
|
||
normal: false,
|
||
})
|
||
}
|
||
}
|
||
|
||
pub fn hint(id: &str) -> String {
|
||
match id {
|
||
"sketch.line" => "Line: click points; right-click or Esc to finish".into(),
|
||
"sketch.rectangle.two_point" => "Rectangle: click two opposite corners".into(),
|
||
"sketch.rectangle.center" => "Center rectangle: click the centre, then a corner".into(),
|
||
"sketch.rectangle.rounded" => "Rounded rectangle: click two opposite corners (Tab to the radius box to type the corner radius)".into(),
|
||
"sketch.rectangle.three_point" => "3-point rectangle: click two points of one edge, then the width".into(),
|
||
"sketch.circle.center" => "Circle: click the centre, then a point on the circle".into(),
|
||
"sketch.arc.three_point" => "Arc: click start, end, then a point on the arc".into(),
|
||
"sketch.arc3d" => "3D Arc: click start, end, then a point on the arc (points may leave the sketch plane)".into(),
|
||
"sketch.line3d" => "3D Line: click world points; right-click or Esc to finish (points may leave the sketch plane)".into(),
|
||
"sketch.spline3d" => "3D Spline: click fit points in 3D; right-click or Esc to finish".into(),
|
||
"sketch.point3d" => "3D Point: click where a 3D point goes".into(),
|
||
"sketch.arc.center_point" => "Arc: click centre and start, go round either way and click the end, or type a signed sweep".into(),
|
||
"sketch.dimension" => {
|
||
"Dimension: pick one or two entities and type the value (or click to place it first); click a dimension to edit it; Enter applies".into()
|
||
}
|
||
"sketch.constraint.horizontal_vertical" => {
|
||
"Horizontal/Vertical: pick a line, two points, or a point and a line; hold Shift to pick a line midpoint".into()
|
||
}
|
||
"sketch.slot.center_to_center" | "sketch.slot.overall" => "Slot: click both ends, then the width".into(),
|
||
"sketch.constraint.midpoint" => "MidPoint: pick a point and a line, or two lines to centre the second on the first".into(),
|
||
_ if id.starts_with("sketch.constraint.") => "Constraint: pick the sketch entities".into(),
|
||
_ => crate::sketch_tools::hint(id).unwrap_or_else(|| "Click in the sketch".into()),
|
||
}
|
||
}
|
||
|
||
fn arg(p: &(Vec2, Option<String>)) -> Value {
|
||
match &p.1 {
|
||
Some(id) => json!(id),
|
||
None => json!([p.0.x, p.0.y]),
|
||
}
|
||
}
|
||
|
||
fn xy(p: &(Vec2, Option<String>)) -> Value {
|
||
json!([p.0.x, p.0.y])
|
||
}
|
||
|
||
/// Shift exposes a line midpoint as a point target, only in the alignment tool.
|
||
fn midpoint_at(app: &SolveApp, proj: &Proj, pos: Pos2, radius: f32) -> Option<(Vec2, String)> {
|
||
let sid = app.session.active_sketch?;
|
||
let state = crate::open_meshing::session_world(&app.session);
|
||
let ss = state.sketch(sid)?;
|
||
pick(app, proj, pos).into_iter().find_map(|hit| {
|
||
let Hit::SketchCurve { sketch, id, straight: true, .. } = hit else { return None };
|
||
if sketch != sid {
|
||
return None;
|
||
}
|
||
let l = ss.sketch.curve_index(&id)?;
|
||
let solidcraft_engine::sketch::Shape::Line { a, b } = ss.sketch.shape(l)? else { return None };
|
||
let mid = (a + b) * 0.5;
|
||
let screen = proj.to_screen(ss.plane.to_world(mid))?;
|
||
(screen.distance(pos) <= radius).then_some((mid, id))
|
||
})
|
||
}
|
||
|
||
pub fn on_hover(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
|
||
crate::sketch3d::on_hover(app, proj, pos);
|
||
if let Some(mut tool) = app.tool.take() {
|
||
crate::sketch_line_arc::rejoin(app, &mut tool);
|
||
app.tool = Some(tool);
|
||
}
|
||
let midpoint = (shift && app.tool.as_ref().is_some_and(|t| t.kind == Kind::HorizontalVertical))
|
||
.then(|| midpoint_at(app, proj, pos, f32::INFINITY))
|
||
.flatten();
|
||
let h = if let Some((point, _)) = midpoint {
|
||
Some((point, Some("Midpoint".into())))
|
||
} else if let Some(point) = app.tool.as_ref().and_then(|tool| crate::sketch_tools::periodic_start_snap(app, tool, proj, pos)) {
|
||
Some((point, Some("Close smooth loop".into())))
|
||
} else {
|
||
sketch_point_at(app, proj, pos)
|
||
};
|
||
let follow = app.preferences.center_arc_follows_cursor;
|
||
if let Some(t) = app.tool.as_mut() {
|
||
t.hover = h;
|
||
if follow {
|
||
follow_arc_turn(t);
|
||
} else {
|
||
t.arc_turn = 0.0;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Add the cursor's latest step round a centre-point arc's centre to the turn it has made since
|
||
/// the start was placed, a step never more than half a turn. A full turn back to the start wraps.
|
||
fn follow_arc_turn(t: &mut Tool) {
|
||
let (Some(c), Some(a), Some(h)) = (t.pts.first(), t.pts.get(1), t.hover.as_ref()) else {
|
||
t.arc_turn = 0.0;
|
||
return;
|
||
};
|
||
if t.cmd != "sketch.arc.center_point" || t.pts.len() != 2 {
|
||
t.arc_turn = 0.0;
|
||
return;
|
||
}
|
||
let (c, a, h) = (c.0, a.0, h.0);
|
||
if h.dist(c) <= 1e-9 || a.dist(c) <= 1e-9 {
|
||
return;
|
||
}
|
||
let at = (a - c).angle() + t.arc_turn;
|
||
let step = ((h - c).angle() - at + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI;
|
||
if step.is_finite() {
|
||
t.arc_turn = (t.arc_turn + step) % std::f64::consts::TAU;
|
||
}
|
||
}
|
||
|
||
/// A centre-point arc's sweep from its start to `end` (radians): counter-clockwise, unless the
|
||
/// cursor went round the centre clockwise from the start (#6645).
|
||
pub(crate) fn center_arc_sweep(t: &Tool, end: Vec2) -> f64 {
|
||
let (Some(c), Some(a)) = (t.pts.first(), t.pts.get(1)) else { return 0.0 };
|
||
let ccw = ((end - c.0).angle() - (a.0 - c.0).angle()).rem_euclid(std::f64::consts::TAU);
|
||
if t.arc_turn < 0.0 && ccw > 0.0 { ccw - std::f64::consts::TAU } else { ccw }
|
||
}
|
||
|
||
pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
|
||
// A click away dismisses the inline editor; it must not also pick the first entity of
|
||
// the next dimension before that cancellation has been processed. The type-first value
|
||
// of the Dimension tool takes clicks itself (a second pick, or where its text goes).
|
||
if crate::dim_view::editing() && crate::dim_view::live().is_none() {
|
||
return;
|
||
}
|
||
let Some(mut tool) = app.tool.take() else { return };
|
||
// In a 3D sketch the drawing tools take points off the plane.
|
||
if crate::sketch3d::on_click(app, &mut tool, proj, pos) {
|
||
app.tool = Some(tool);
|
||
return;
|
||
}
|
||
match tool.kind {
|
||
Kind::Draw(n) => {
|
||
if let Some(p) = sketch_point_at(app, proj, pos) {
|
||
// Typed values win over the cursor; lines snap to horizontal/vertical.
|
||
let p = crate::sketch_dims::placed(app, &tool, &p);
|
||
// A repeated initial point supplies no extent. Keep waiting rather than
|
||
// attempting a degenerate shape; explicit typed values still validate.
|
||
if n != 1 && tool.pts.len() == 1 && tool.pts.first().is_some_and(|first| first.0 == p.0) && !tool.dims.iter().any(|b| b.locked) {
|
||
app.tool = Some(tool);
|
||
return;
|
||
}
|
||
app.tool = Some(tool);
|
||
place(app, p);
|
||
return;
|
||
}
|
||
}
|
||
Kind::HorizontalVertical => {
|
||
let hits = pick(app, proj, pos);
|
||
let midpoint = shift.then(|| midpoint_at(app, proj, pos, 12.0)).flatten();
|
||
let hit = hits.iter().find(|hit| match hit {
|
||
Hit::SketchPoint { sketch, .. } | Hit::SketchCurve { sketch, .. } => Some(*sketch) == app.session.active_sketch,
|
||
_ => false,
|
||
});
|
||
let point = midpoint.map(|(_, id)| json!({"midpoint": id})).or_else(|| match hit {
|
||
Some(Hit::SketchPoint { id, .. }) => Some(json!(id)),
|
||
_ => None,
|
||
});
|
||
if let Some(point) = point {
|
||
if let Some(first) = tool.point_picks.first() {
|
||
if first != &point && app.run(tool.cmd, json!({"points": [first, point]})).is_ok() {
|
||
tool.point_picks.clear();
|
||
}
|
||
} else {
|
||
tool.point_picks.push(point);
|
||
}
|
||
} else if !shift && let Some(Hit::SketchCurve { id, straight: true, .. }) = hit {
|
||
// A line picked on its own is made horizontal/vertical; a line picked after a
|
||
// point aligns that point with the line (a circle's centre with a square's
|
||
// edge, #617).
|
||
let first = tool.point_picks.first().cloned();
|
||
let params = match first {
|
||
None => Some(json!({"line": id})),
|
||
Some(point) => {
|
||
let state = crate::open_meshing::session_world(&app.session);
|
||
app.session.active_sketch.and_then(|sid| state.sketch(sid)).and_then(|ss| point_line_alignment(&ss.sketch, &point, id))
|
||
}
|
||
};
|
||
if let Some(params) = params
|
||
&& app.run(tool.cmd, params).is_ok()
|
||
{
|
||
tool.point_picks.clear();
|
||
}
|
||
}
|
||
}
|
||
Kind::Pick(n) => {
|
||
let hits = pick(app, proj, pos);
|
||
// Symmetry's third pick may be an origin axis lying along the sketch's own x or y
|
||
// (#1075); the command names those `x` / `y`.
|
||
let axis_ok = tool.cmd == "sketch.constraint.symmetry" && tool.picks.len() == 2;
|
||
let entity = hits.iter().find_map(|h| match h {
|
||
Hit::SketchPoint { id, .. } | Hit::SketchCurve { id, .. } => Some(id.clone()),
|
||
Hit::Axis { name } if axis_ok => sketch_axis_of(app, name).map(str::to_string),
|
||
_ => None,
|
||
});
|
||
// With nothing of the sketch there, a body's edge or vertex is picked (kept as its
|
||
// reference): the command projects it, so any body can be constrained to, a mirrored
|
||
// copy too (#6348). Projected geometry is already fixed, so Fix takes sketch entities.
|
||
let model = || {
|
||
hits.iter()
|
||
.filter(|h| tool.cmd != "sketch.constraint.fix" && matches!(h, Hit::Edge { .. } | Hit::Vertex { .. }))
|
||
.find_map(|h| crate::sketch_tools::model_ref(app, h))
|
||
.map(|r| r.to_string())
|
||
};
|
||
if let Some(id) = entity.or_else(model) {
|
||
tool.picks.push(id);
|
||
}
|
||
if tool.picks.len() >= n {
|
||
run_pick(app, &tool);
|
||
tool.picks.clear();
|
||
}
|
||
}
|
||
Kind::Ext => crate::sketch_tools::on_click(app, &mut tool, proj, pos),
|
||
Kind::Dimension => {
|
||
let hits = pick(app, proj, pos);
|
||
// The snap identifies the intended line even when another (projected) edge
|
||
// overlaps it and wins the ordinary curve hit. Both picks can be midpoints.
|
||
let midpoint = sketch_point_at(app, proj, pos).and_then(|(_, snap)| snap).and_then(|id| {
|
||
if id.starts_with("mid:") { return Some(id); }
|
||
// An earlier dimension may already have materialized this midpoint.
|
||
// Picking that point retains the same midpoint intent on subsequent dimensions.
|
||
let state = crate::open_meshing::session_world(&app.session);
|
||
let ss = app.session.active_sketch.and_then(|sid| state.sketch(sid))?;
|
||
let point = ss.sketch.resolve_point(&id)?;
|
||
ss.sketch.constraints.iter().find_map(|c| match c.kind {
|
||
solidcraft_engine::sketch::ConstraintKind::Midpoint { p, l } if !c.driven && p == point => {
|
||
ss.sketch.curves.get(l).map(|c| format!("mid:{}", c.id))
|
||
}
|
||
_ => None,
|
||
})
|
||
}).filter(|id| {
|
||
let Some(line) = id.strip_prefix("mid:") else { return false };
|
||
let state = crate::open_meshing::session_world(&app.session);
|
||
app.session
|
||
.active_sketch
|
||
.and_then(|sid| state.sketch(sid))
|
||
.is_some_and(|ss| {
|
||
ss.sketch.curve_index(line).is_some_and(|l| solidcraft_engine::view::sketch_curve_visible(&ss.sketch, l))
|
||
// A circle/arc and a line still measure their edge-to-edge gap.
|
||
&& tool.picks.first().is_none_or(|first| {
|
||
ss.sketch.curve_index(first).is_none_or(|l| matches!(ss.sketch.shape(l), Some(solidcraft_engine::sketch::Shape::Line { .. })))
|
||
})
|
||
})
|
||
});
|
||
let hit = midpoint
|
||
.as_deref()
|
||
.and_then(|id| id.strip_prefix("mid:"))
|
||
.map(|id| (id.to_string(), true, true))
|
||
.or_else(|| {
|
||
hits.iter().find_map(|h| match h {
|
||
Hit::SketchPoint { sketch, id, .. } if Some(*sketch) == app.session.active_sketch => Some((id.clone(), false, true)),
|
||
Hit::SketchCurve { sketch, id, straight, .. } if Some(*sketch) == app.session.active_sketch => {
|
||
Some((id.clone(), true, *straight))
|
||
}
|
||
_ => None,
|
||
})
|
||
})
|
||
.or_else(|| {
|
||
// With nothing of the sketch under the cursor, a body's edge or vertex may be
|
||
// measured too (#7912): the command projects it into the sketch. An edge is a
|
||
// length of its own; a vertex waits for the entity it is measured against.
|
||
hits.iter().find_map(|h| match h {
|
||
Hit::Edge { .. } => crate::sketch_tools::model_ref(app, h).map(|r| (r.to_string(), true, false)),
|
||
Hit::Vertex { .. } => crate::sketch_tools::model_ref(app, h).map(|r| (r.to_string(), false, false)),
|
||
_ => None,
|
||
})
|
||
});
|
||
let fresh = |tool: &Tool, id: &String| !tool.picks.contains(id) && tool.picks.len() < 2;
|
||
// Before a new dimension is under way, a click on an existing one edits its value;
|
||
// the tool stays on for the next dimension.
|
||
if crate::dim_view::live().is_none()
|
||
&& tool.picks.is_empty()
|
||
&& !app.ui.pick_off.iter().any(|k| k == "dimensions")
|
||
&& crate::dim_view::tool_click(app, pos, hit.is_some())
|
||
{
|
||
app.tool = Some(tool);
|
||
return;
|
||
}
|
||
if let Some(typed) = crate::dim_view::live() {
|
||
match hit {
|
||
// Before anything is typed, another entity joins the dimension, as in the
|
||
// place-first flow (a distance, an angle between lines).
|
||
Some((id, _, midpoint_target)) if !typed && fresh(&tool, &id) => {
|
||
let picks = dimension_picks(&tool, id, midpoint.as_deref(), midpoint_target);
|
||
match crate::dim_view::begin_live(app, picks.clone(), Some(pos)) {
|
||
Ok(live) => {
|
||
if !live {
|
||
crate::dim_view::cancel();
|
||
}
|
||
tool.picks = picks;
|
||
if let Some(midpoint) = midpoint {
|
||
tool.point_picks.push(json!(midpoint));
|
||
}
|
||
}
|
||
Err(error) => app.set_status(error, true),
|
||
}
|
||
}
|
||
// Otherwise the click places the text; the value keeps the keyboard.
|
||
_ => {
|
||
if let Some((at, _)) = sketch_point_at(app, proj, pos) {
|
||
crate::dim_view::pin(app, at);
|
||
}
|
||
}
|
||
}
|
||
} else if let Some((id, curve, midpoint_target)) = hit {
|
||
if fresh(&tool, &id) {
|
||
tool.picks = dimension_picks(&tool, id, midpoint.as_deref(), midpoint_target);
|
||
if let Some(midpoint) = midpoint {
|
||
tool.point_picks.push(json!(midpoint));
|
||
}
|
||
// As soon as the picks determine a dimension (one line, circle or arc, or a
|
||
// second entity), its value takes the keyboard: D, click, type. A pick that
|
||
// doesn't keeps the place-first flow; placing reports why.
|
||
if curve || tool.picks.len() == 2 {
|
||
let _ = crate::dim_view::begin_live(app, tool.picks.clone(), Some(pos));
|
||
}
|
||
}
|
||
} else if !tool.picks.is_empty()
|
||
&& let Some((at, _)) = sketch_point_at(app, proj, pos)
|
||
{
|
||
match crate::dim_view::begin_dimension(app, tool.picks.clone(), at) {
|
||
Ok(()) => {
|
||
tool.picks.clear();
|
||
tool.point_picks.clear();
|
||
}
|
||
Err(error) => app.set_status(error, true),
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if !crate::sketch_text::editing(app) && !crate::sketch_tools::image_placement_finished(&tool) {
|
||
app.tool = Some(tool);
|
||
}
|
||
}
|
||
|
||
/// A single edge still measures its length; a second pick uses the snapped midpoints.
|
||
fn dimension_picks(tool: &Tool, id: String, midpoint: Option<&str>, midpoint_target: bool) -> Vec<String> {
|
||
let mut picks = tool.picks.clone();
|
||
if midpoint_target
|
||
&& picks.len() == 1
|
||
&& let Some(midpoint) = tool.point_picks.first().and_then(Value::as_str)
|
||
&& let Some(first) = picks.first_mut()
|
||
{
|
||
*first = midpoint.to_string();
|
||
}
|
||
picks.push(if picks.len() == 1 { midpoint.map(str::to_string).unwrap_or(id) } else { id });
|
||
picks
|
||
}
|
||
|
||
/// Put down the next point of the shape being drawn; the last point runs the command (with
|
||
/// the typed values as dimension constraints).
|
||
pub fn place(app: &mut SolveApp, p: (Vec2, Option<String>)) {
|
||
let Some(mut tool) = app.tool.take() else { return };
|
||
crate::sketch_line_arc::rejoin(app, &mut tool);
|
||
if tool.kind == Kind::Ext {
|
||
crate::sketch_tools::place_point(app, &mut tool, p);
|
||
// A placed text opens Edit Text, which ends the tool.
|
||
if !crate::sketch_text::editing(app) {
|
||
app.tool = Some(tool);
|
||
}
|
||
return;
|
||
}
|
||
let Kind::Draw(n) = tool.kind else {
|
||
app.tool = Some(tool);
|
||
return;
|
||
};
|
||
if let Err(error) = crate::sketch_dims::validate(app, &tool) {
|
||
app.set_status(error, true);
|
||
app.tool = Some(tool);
|
||
return;
|
||
}
|
||
tool.lined.push((p.0, crate::sketch_tools::lined_at(p.0)));
|
||
tool.pts.push(p);
|
||
let before = crate::sketch_tools::point_ids(app);
|
||
if tool.cmd == "sketch.line" {
|
||
// A new chain's first point: nothing drawn yet to go on tangent from.
|
||
if tool.pts.len() == 1 {
|
||
tool.chain = Default::default();
|
||
}
|
||
if tool.pts.len() >= 2 {
|
||
let (a, b) = (tool.pts[tool.pts.len() - 2].clone(), tool.pts[tool.pts.len() - 1].clone());
|
||
let angled = crate::sketch_dims::has_locked(&tool, "Angle");
|
||
let dimensioned = tool.dims.iter().any(|dimension| dimension.locked);
|
||
if let Ok(v) = draw(app, &tool, json!({"points": [arg(&a), arg(&b)], "infer": !angled})) {
|
||
let curves: Vec<String> = v["curves"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(str::to_string)).collect();
|
||
// Chain: the next segment starts at this one's end point.
|
||
if let Some(id) = curves.first() {
|
||
if angled {
|
||
crate::inference::clear();
|
||
tool.lined.clear();
|
||
} else {
|
||
// Endpoint inference is part of this drawing. Preserve its original
|
||
// undo history even when the history is already at the engine's cap.
|
||
let history = dimensioned.then(|| std::mem::take(&mut app.session.undo));
|
||
crate::inference::commit(app, id, b.0);
|
||
crate::sketch_tools::constrain_lined(app, &mut tool, &[a.0, b.0], &before);
|
||
if let Some(history) = history {
|
||
app.session.undo = history;
|
||
}
|
||
}
|
||
let last = tool.pts.len() - 1;
|
||
tool.pts[last].1 = Some(format!("{id}.end"));
|
||
// The chain needs only its current endpoint, even after many segments.
|
||
tool.pts = vec![tool.pts[last].clone()];
|
||
tool.chain.placed(id, a.clone());
|
||
}
|
||
crate::sketch_dims::reset(&mut tool);
|
||
} else {
|
||
tool.pts.pop();
|
||
tool.lined.pop();
|
||
}
|
||
}
|
||
} else if n > 0 && tool.pts.len() >= n {
|
||
match run_shape(app, &tool) {
|
||
Ok(_) => {
|
||
let placed: Vec<Vec2> = tool.pts.iter().map(|p| p.0).collect();
|
||
crate::sketch_tools::constrain_lined(app, &mut tool, &placed, &before);
|
||
tool.pts.clear();
|
||
crate::sketch_dims::reset(&mut tool);
|
||
}
|
||
Err(error) => {
|
||
app.set_status(error, true);
|
||
tool.pts.pop();
|
||
tool.lined.pop();
|
||
}
|
||
}
|
||
}
|
||
app.tool = Some(tool);
|
||
}
|
||
|
||
/// Geometry and typed constraints are committed atomically, as one undo step. With "Dimension
|
||
/// new shapes" on (Preferences › Sketch), every other size of a shape the engine can dimension
|
||
/// joins them at its size as drawn, and with "Also place them from the origin" the shape is then
|
||
/// placed until fully constrained; the engine's `dimension_roles` decides which shapes those are.
|
||
/// This is the one place drawing tools commit through: the 3D tools (`sketch3d`) take part by
|
||
/// committing here once their creators are listed there.
|
||
pub(crate) fn draw(app: &mut SolveApp, t: &Tool, params: Value) -> Result<Value, String> {
|
||
let dimensions = crate::sketch_dims::dimensions(t);
|
||
let as_drawn = app.preferences.sketch_auto_dimensions && solidcraft_engine::dimension_roles(t.cmd).is_some();
|
||
let locate = as_drawn && app.preferences.sketch_auto_locate;
|
||
if !as_drawn && dimensions.as_object().is_none_or(|values| values.is_empty()) {
|
||
app.run(t.cmd, params)
|
||
} else {
|
||
let request = json!({"command": t.cmd, "params": params, "dimensions": dimensions, "as_drawn": as_drawn, "locate": locate});
|
||
let result = app.run("sketch.draw.dimensioned", request)?;
|
||
// The internal wrapper has no toolbar category; apply the original creator's line
|
||
// type while retaining the draw's undo history, including at the history limit.
|
||
let history = std::mem::take(&mut app.session.undo);
|
||
crate::sketch_palette::apply_mode(app, t.cmd, &result);
|
||
app.session.undo = history;
|
||
// A box typed `name = expression` defined the parameter `name` (#7567).
|
||
let defined: Vec<_> = result["defined"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|name| format!("`{name}`")).collect();
|
||
match defined.as_slice() {
|
||
[] => {}
|
||
[name] => app.set_status(format!("Parameter {name} defined"), false),
|
||
names => app.set_status(format!("Parameters {} defined", names.join(", ")), false),
|
||
}
|
||
Ok(result)
|
||
}
|
||
}
|
||
|
||
fn run_shape(app: &mut SolveApp, t: &Tool) -> Result<Vec<String>, String> {
|
||
let p = &t.pts;
|
||
let d = |a: usize, b: usize| p[a].0.dist(p[b].0);
|
||
let sides = crate::sketch_dims::locked_value(app, t, "Sides").map_or(6, |v| v as usize);
|
||
let params = match t.cmd {
|
||
"sketch.rectangle.two_point" => json!({"p0": xy(&p[0]), "p1": xy(&p[1])}),
|
||
"sketch.rectangle.center" => json!({"center": xy(&p[0]), "corner": xy(&p[1])}),
|
||
"sketch.rectangle.rounded" => {
|
||
json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "radius": crate::sketch_dims::rounded_radius_value(app, t, p[0].0, p[1].0)})
|
||
}
|
||
"sketch.rectangle.three_point" => json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "p2": xy(&p[2])}),
|
||
"sketch.circle.center" => {
|
||
// A centre snapped to an existing point goes as its place, where `connect` ties
|
||
// them with a Coincident the sketch shows (#7299); a midpoint, on-curve, crossing or
|
||
// body-vertex snap goes as itself, so the centre is held there. A second click
|
||
// snapped to a point keeps the circle on that point (#3099).
|
||
let center = match &p[0].1 {
|
||
Some(id) if ["mid:", "on:", "vertex:", "x:"].iter().any(|k| id.starts_with(k)) => json!(id),
|
||
_ => xy(&p[0]),
|
||
};
|
||
let mut v = json!({"center": center, "radius": d(0, 1)});
|
||
if p[1].1.is_some() {
|
||
v["through"] = arg(&p[1]);
|
||
}
|
||
v
|
||
}
|
||
"sketch.circle.two_point" => json!({"p0": xy(&p[0]), "p1": xy(&p[1])}),
|
||
// Each click goes as its snap, as the 3-Point Arc's do: a click snapped to a point or
|
||
// curve keeps the circle on it (#9858).
|
||
"sketch.circle.three_point" => json!({"p0": arg(&p[0]), "p1": arg(&p[1]), "p2": arg(&p[2])}),
|
||
"sketch.arc.three_point" => json!({"start": arg(&p[0]), "end": arg(&p[1]), "through": arg(&p[2])}),
|
||
"sketch.arc.center_point" => {
|
||
// A centre snapped to an existing point goes as its place, where `connect` ties
|
||
// them with a Coincident the sketch shows (#7299); a midpoint, on-curve, crossing or
|
||
// body-vertex snap goes as itself, so the centre is held there.
|
||
let center = match &p[0].1 {
|
||
Some(id) if ["mid:", "on:", "vertex:", "x:"].iter().any(|k| id.starts_with(k)) => json!(id),
|
||
_ => xy(&p[0]),
|
||
};
|
||
match crate::sketch_dims::locked_value(app, t, "Sweep") {
|
||
Some(sweep) => json!({"center": center, "start": arg(&p[1]), "sweep": sweep.to_degrees()}),
|
||
None if center_arc_sweep(t, p[2].0) < 0.0 => {
|
||
json!({"center": center, "start": arg(&p[1]), "end": xy(&p[2]), "clockwise": true})
|
||
}
|
||
None => json!({"center": center, "start": arg(&p[1]), "end": xy(&p[2])}),
|
||
}
|
||
}
|
||
"sketch.polygon.inscribed" | "sketch.polygon.circumscribed" => {
|
||
let a = (p[1].0 - p[0].0).angle().to_degrees();
|
||
json!({"center": xy(&p[0]), "radius": d(0, 1), "sides": sides, "angle": a})
|
||
}
|
||
"sketch.polygon.edge" => json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "sides": sides}),
|
||
"sketch.slot.center_to_center" | "sketch.slot.overall" => {
|
||
let dir = (p[1].0 - p[0].0).normalized().unwrap_or(Vec2::X);
|
||
// Seed the creator with the typed width too: an Overall slot places its cap
|
||
// centres from this width before the driving dimension is applied.
|
||
let width = crate::sketch_dims::locked_value(app, t, "Width").unwrap_or_else(|| (2.0 * dir.cross(p[2].0 - p[0].0).abs()).max(1e-3));
|
||
json!({"p0": xy(&p[0]), "p1": xy(&p[1]), "width": width})
|
||
}
|
||
// A midpoint or on-curve snap goes as itself, so the point is held there (#4691); a
|
||
// snap to an existing point goes as its place, where `connect` joins them.
|
||
"sketch.point" => match &p[0].1 {
|
||
Some(id) if ["mid:", "on:", "vertex:"].iter().any(|k| id.starts_with(k)) => json!({"point": id}),
|
||
_ => json!({"point": xy(&p[0])}),
|
||
},
|
||
_ => return Err(format!("drawing {} is not supported", t.cmd)),
|
||
};
|
||
let result = draw(app, t, params)?;
|
||
Ok(result["curves"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(str::to_string)).collect())
|
||
}
|
||
|
||
/// #617: Aligning a point with a straight line (a circle's centre with a square's edge) aligns
|
||
/// the point with the line's midpoint, in the mode the line's dominant axis suggests. None when
|
||
/// the curve is not a line.
|
||
pub(crate) fn point_line_alignment(sk: &solidcraft_engine::sketch::Sketch, point: &Value, line: &str) -> Option<Value> {
|
||
let points = point_line_points(sk, point, line)?;
|
||
let mode = line_axis_mode(sk, line)?;
|
||
Some(json!({"points": points, "mode": mode}))
|
||
}
|
||
|
||
/// The `points` pair aligning `point` with the midpoint of `line`; None when `line` is not a line.
|
||
pub(crate) fn point_line_points(sk: &solidcraft_engine::sketch::Sketch, point: &Value, line: &str) -> Option<[Value; 2]> {
|
||
let l = sk.curve_index(line)?;
|
||
matches!(sk.shape(l)?, solidcraft_engine::sketch::Shape::Line { .. }).then(|| [point.clone(), json!({"midpoint": line})])
|
||
}
|
||
|
||
/// The axis a straight line is closest to: the alignment mode when a point is aligned with it (#617).
|
||
fn line_axis_mode(sk: &solidcraft_engine::sketch::Sketch, line: &str) -> Option<&'static str> {
|
||
let solidcraft_engine::sketch::Shape::Line { a, b } = sk.shape(sk.curve_index(line)?)? else { return None };
|
||
let d = b - a;
|
||
Some(if d.x.abs() >= d.y.abs() { "horizontal" } else { "vertical" })
|
||
}
|
||
|
||
/// Only consume a complete, unambiguous selection; command validation owns geometry.
|
||
pub(crate) fn constraint_preselection(
|
||
command: &str,
|
||
selection: &[solidcraft_engine::Sel],
|
||
sketch: Option<&solidcraft_engine::sketch::Sketch>,
|
||
) -> Option<Value> {
|
||
use solidcraft_engine::Sel::{SketchCurve, SketchPoint};
|
||
let selected_ids = |curves_only: bool, minimum: usize| -> Option<Vec<&str>> {
|
||
if !(minimum..=200).contains(&selection.len()) {
|
||
return None;
|
||
}
|
||
let ids: Vec<&str> = selection
|
||
.iter()
|
||
.map(|s| match s {
|
||
SketchCurve { id, .. } => Some(id.as_str()),
|
||
SketchPoint { id } if !curves_only => Some(id.as_str()),
|
||
_ => None,
|
||
})
|
||
.collect::<Option<_>>()?;
|
||
let unique: std::collections::BTreeSet<_> = ids.iter().copied().collect();
|
||
(unique.len() == ids.len()).then_some(ids)
|
||
};
|
||
match (command, selection) {
|
||
("sketch.constraint.fix", _) => selected_ids(false, 1).map(|ids| json!({"entities":ids})),
|
||
("sketch.constraint.polygon", _) => selected_ids(true, 3).map(|ids| json!({"lines":ids})),
|
||
// Three or more curves: all of them equal, in pick order (#4985). Two keep the `a, b` form.
|
||
("sketch.constraint.equal", _) if selection.len() >= 3 => selected_ids(true, 3).map(|ids| json!({"curves":ids})),
|
||
("sketch.constraint.curvature", [SketchCurve { id: a, .. }, SketchCurve { id: b, .. }]) if a != b => Some(json!({"a":a,"b":b})),
|
||
("sketch.constraint.horizontal_vertical", [SketchCurve { id, .. }]) => Some(json!({"line":id})),
|
||
// A point and a straight line (a circle's centre and a square's edge, #617): align the
|
||
// point with the line, in the mode the line's own axis suggests.
|
||
("sketch.constraint.horizontal_vertical", [SketchPoint { id }, SketchCurve { id: line, .. }]) => {
|
||
point_line_alignment(sketch?, &json!(id), line)
|
||
}
|
||
("sketch.constraint.horizontal_vertical", [SketchCurve { id: line, .. }, SketchPoint { id }]) => {
|
||
point_line_alignment(sketch?, &json!(id), line)
|
||
}
|
||
("sketch.constraint.horizontal_vertical", _) => crate::selection::alignment_points(selection).map(|points| json!({"points": points})),
|
||
("sketch.constraint.coincident", [_, _]) => crate::selection::coincident_operands(selection),
|
||
("sketch.constraint.concentric", [SketchCurve { id: a, .. }, SketchPoint { id: b }] | [SketchPoint { id: a }, SketchCurve { id: b, .. }])
|
||
if a != b =>
|
||
{
|
||
Some(json!({"a":a,"b":b}))
|
||
}
|
||
(
|
||
"sketch.constraint.midpoint",
|
||
[SketchPoint { id: point }, SketchCurve { id: line, .. }] | [SketchCurve { id: line, .. }, SketchPoint { id: point }],
|
||
) => Some(json!({"point":point,"line":line})),
|
||
("sketch.constraint.midpoint", [SketchCurve { id: a, .. }, SketchCurve { id: b, .. }]) if a != b => Some(json!({"a":a,"b":b})),
|
||
("sketch.constraint.symmetry", [a, b, c]) => {
|
||
let picks = [a, b, c]
|
||
.into_iter()
|
||
.map(|entity| match entity {
|
||
SketchPoint { id } | SketchCurve { id, .. } => Some(json!(id)),
|
||
_ => None,
|
||
})
|
||
.collect::<Option<Vec<_>>>()?;
|
||
symmetry_args(&picks, sketch)
|
||
}
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
pub(crate) fn projection_preselection(selection: &[solidcraft_engine::Sel]) -> Option<Vec<Value>> {
|
||
use solidcraft_engine::Sel;
|
||
// The projection command processes at most 1000 references; never consume a subset.
|
||
if selection.is_empty() || selection.len() > 1000 {
|
||
return None;
|
||
}
|
||
selection
|
||
.iter()
|
||
.map(|item| {
|
||
Some(match item {
|
||
Sel::Body { name } => json!({"body":name}),
|
||
Sel::ExternalSketchCurve { sketch, id } => json!({"sketch":sketch,"curve":id}),
|
||
// A straight line of another sketch, picked into the dialog, names its sketch
|
||
// (#3726): the same reference the external pick stands for (#10291).
|
||
Sel::SketchCurve { id, sketch: Some(sketch) } => json!({"sketch":sketch,"curve":id}),
|
||
Sel::ExternalSketchPoint { sketch, id } => json!({"sketch":sketch,"point":id}),
|
||
Sel::Vertex { body, point } => json!({"body":body,"vertex":[point.x,point.y,point.z]}),
|
||
Sel::Edge { body, point, .. } => json!({"body":body,"edge":[point.x,point.y,point.z]}),
|
||
Sel::Face { body, point, .. } => json!({"body":body,"face":[point.x,point.y,point.z]}),
|
||
Sel::Axis { name } => json!({"axis":name}),
|
||
Sel::Plane { name } => json!({"plane":name}),
|
||
_ => return None,
|
||
})
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// `x` or `y` when the origin axis `name` is the active sketch's own x or y axis: along it, and
|
||
/// through the sketch's origin.
|
||
pub(crate) fn sketch_axis_of(app: &SolveApp, name: &str) -> Option<&'static str> {
|
||
use solidcore_record::Vec3;
|
||
let dir = match name {
|
||
"X" => Vec3::X,
|
||
"Y" => Vec3::Y,
|
||
"Z" => Vec3::Z,
|
||
_ => return None,
|
||
};
|
||
let st = crate::open_meshing::session_world(&app.session);
|
||
let plane = st.sketch(app.session.active_sketch?)?.plane;
|
||
let o = plane.origin;
|
||
if (o - dir * o.dot(dir)).len() > 1e-6 {
|
||
return None;
|
||
}
|
||
if plane.x.dot(dir).abs() > 1.0 - 1e-9 {
|
||
Some("x")
|
||
} else if plane.y.dot(dir).abs() > 1.0 - 1e-9 {
|
||
Some("y")
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
/// Symmetry's arguments from three picked sketch ids in any order (#1796): with two points and
|
||
/// a line, the line; with three lines, the only construction line or centerline among them (the
|
||
/// line drawn between the two it mirrors); otherwise the last pick, as before.
|
||
fn symmetry_args(picks: &[Value], sketch: Option<&solidcraft_engine::sketch::Sketch>) -> Option<Value> {
|
||
let curve = |v: &Value| match v.as_str() {
|
||
Some(id) => sketch.and_then(|sk| sk.curve_index(id).and_then(|i| sk.curves.get(i))),
|
||
None => None,
|
||
};
|
||
let is_line = |v: &Value| matches!(v.as_str(), Some("x" | "y")) || curve(v).is_some();
|
||
let is_axis = |v: &Value| matches!(v.as_str(), Some("x" | "y")) || curve(v).is_some_and(|c| c.construction || c.centerline);
|
||
let only = |f: &dyn Fn(&Value) -> bool| {
|
||
let hits: Vec<usize> = (0..picks.len()).filter(|i| picks.get(*i).is_some_and(f)).collect();
|
||
hits.first().copied().filter(|_| hits.len() == 1)
|
||
};
|
||
if picks.len() != 3 {
|
||
return None;
|
||
}
|
||
let line = only(&is_line).or_else(|| only(&is_axis)).unwrap_or(2);
|
||
let mut rest = (0..3).filter(|i| *i != line).filter_map(|i| picks.get(i));
|
||
let (a, b, line) = (rest.next()?, rest.next()?, picks.get(line)?);
|
||
(a != b).then(|| json!({"a": a, "b": b, "line": line}))
|
||
}
|
||
|
||
fn run_pick(app: &mut SolveApp, t: &Tool) {
|
||
// An entity id, or a model edge's or vertex's reference.
|
||
let k: Vec<Value> = t.picks.iter().map(|pick| serde_json::from_str(pick).ok().filter(Value::is_object).unwrap_or_else(|| json!(pick))).collect();
|
||
let params = match t.cmd {
|
||
"sketch.constraint.fix" => json!({"entity": k[0]}),
|
||
"sketch.constraint.coincident" => json!({"a": k[0], "b": k[1]}),
|
||
// In pick order: a point and a line either way round, or two lines to centre.
|
||
"sketch.constraint.midpoint" => json!({"a": k[0], "b": k[1]}),
|
||
"sketch.constraint.symmetry" => {
|
||
let params = {
|
||
let state = crate::open_meshing::session_world(&app.session);
|
||
symmetry_args(&k, app.session.active_sketch.and_then(|id| state.sketch(id)).map(|ss| &ss.sketch))
|
||
};
|
||
let Some(params) = params else {
|
||
app.set_status("Symmetry: pick two points or two curves and the line between them", true);
|
||
return;
|
||
};
|
||
params
|
||
}
|
||
_ => json!({"a": k[0], "b": k[1]}),
|
||
};
|
||
let _ = app.run(t.cmd, params);
|
||
}
|
||
|
||
/// Take back a pending spline point before undo or Backspace reaches the sketch.
|
||
pub fn undo_spline_point(app: &mut SolveApp) -> bool {
|
||
let Some(t) = app.tool.as_mut() else { return false };
|
||
if !matches!(t.cmd, "sketch.spline.fit_point" | "sketch.spline.control_point" | "sketch.spline.control_point_5") || t.pts.is_empty() {
|
||
return false;
|
||
}
|
||
t.pts.pop();
|
||
crate::sketch_dims::reset(t);
|
||
true
|
||
}
|
||
|
||
/// Right click / Esc: end the current chain (line) or cancel the tool.
|
||
pub fn finish(app: &mut SolveApp) {
|
||
crate::dim_view::cancel();
|
||
if crate::sketch3d::finish(app) {
|
||
return;
|
||
}
|
||
if crate::sketch_line_arc::finish(app) {
|
||
return;
|
||
}
|
||
if let Some(mut t) = app.tool.take_if(|t| t.kind == Kind::Ext) {
|
||
if crate::sketch_tools::finish(app, &mut t) {
|
||
app.tool = Some(t);
|
||
}
|
||
return;
|
||
}
|
||
if let Some(t) = app.tool.as_mut()
|
||
&& !t.pts.is_empty()
|
||
{
|
||
t.pts.clear();
|
||
t.picks.clear();
|
||
crate::sketch_dims::reset(t);
|
||
return;
|
||
}
|
||
app.tool = None;
|
||
}
|
||
|
||
/// Rubber-band preview of the shape being drawn.
|
||
pub(crate) fn paint_preview_curve(
|
||
mut sketch: solidcraft_engine::sketch::Sketch,
|
||
plane: &solidcore_record::Plane,
|
||
painter: &egui::Painter,
|
||
proj: &Proj,
|
||
stroke: Stroke,
|
||
mode: u8,
|
||
) {
|
||
for curve in &mut sketch.curves {
|
||
let line = matches!(curve.kind, solidcraft_engine::sketch::CurveKind::Line { .. });
|
||
curve.centerline = mode == 2 && line;
|
||
curve.infinite = mode == 3 && line;
|
||
curve.construction |= mode != 0 && !curve.centerline;
|
||
}
|
||
let mut budget = solidcraft_engine::render::SamplingBudget::new(4096, 65_536);
|
||
for index in 0..sketch.curves.len() {
|
||
paint_curve(&sketch, index, plane, painter, proj, stroke, &mut budget);
|
||
}
|
||
crate::scenario::publish_count("tool_preview_curves", sketch.curves.len() as f64);
|
||
}
|
||
|
||
pub(crate) fn paint_sketch_path(points: &[solidcore_record::Vec3], mode: u8, painter: &egui::Painter, proj: &Proj, stroke: Stroke) {
|
||
if mode == 0 {
|
||
let screen: Vec<_> = points.iter().filter_map(|point| proj.to_screen(*point)).collect();
|
||
if screen.len() >= 2 {
|
||
painter.add(egui::Shape::line(screen, stroke));
|
||
}
|
||
return;
|
||
}
|
||
let unit = solidcraft_engine::view::grid_step(proj.cam.half_height()).0;
|
||
for (a, b) in crate::viewport::sketch_segments(points, mode, unit) {
|
||
if let (Some(a), Some(b)) = (proj.to_screen(a), proj.to_screen(b)) {
|
||
painter.line_segment([a, b], stroke);
|
||
}
|
||
}
|
||
}
|
||
|
||
pub(crate) fn paint_curve(
|
||
sketch: &solidcraft_engine::sketch::Sketch,
|
||
index: usize,
|
||
plane: &solidcore_record::Plane,
|
||
painter: &egui::Painter,
|
||
proj: &Proj,
|
||
stroke: Stroke,
|
||
budget: &mut solidcraft_engine::render::SamplingBudget,
|
||
) {
|
||
for part in crate::sketch_display::curve_with_budget(sketch, index, plane, proj, painter.ctx().pixels_per_point(), budget).parts {
|
||
let mode = sketch.curves.get(index).map_or(0, |c| if c.centerline { 2 } else { u8::from(c.construction) });
|
||
paint_sketch_path(&part, mode, painter, proj, stroke);
|
||
}
|
||
}
|
||
|
||
/// Temporary analytic geometry uses the same exact span extraction as committed curves.
|
||
/// It never solves constraints or modifies the document.
|
||
pub(crate) fn preview_curve(
|
||
t: &Tool,
|
||
hover: Vec2,
|
||
sweep: Option<f64>,
|
||
rho: Option<f64>,
|
||
slot_width: Option<f64>,
|
||
) -> Option<solidcraft_engine::sketch::Sketch> {
|
||
use solidcraft_engine::sketch::{CurveKind, Sketch};
|
||
if !hover.is_finite() || t.pts.len() >= solidcraft_engine::sketch::MAX_SPLINE_POINTS || t.pts.iter().any(|p| !p.0.is_finite()) {
|
||
return None;
|
||
}
|
||
let mut sk = Sketch::new();
|
||
let pts: Vec<_> = t.pts.iter().map(|p| p.0).collect();
|
||
match (t.cmd, pts.as_slice()) {
|
||
("sketch.circle.center" | "sketch.polygon.inscribed" | "sketch.polygon.circumscribed", [c]) => {
|
||
sk.add_circle(*c, c.dist(hover), None, None).ok()?;
|
||
}
|
||
("sketch.circle.two_point", [a]) => {
|
||
sk.add_circle((*a + hover) * 0.5, a.dist(hover) * 0.5, None, None).ok()?;
|
||
}
|
||
// The first click is the middle: the line runs from the cursor's mirror image through
|
||
// it to the cursor (#1358), not from the middle to the cursor.
|
||
("sketch.line.midpoint", [m]) => {
|
||
if m.dist(hover) <= 1e-9 {
|
||
return None;
|
||
}
|
||
sk.add_line(*m * 2.0 - hover, hover, None, None, None).ok()?;
|
||
}
|
||
("sketch.circle.three_point" | "sketch.arc.three_point", [a, b]) => {
|
||
let centre = preview_circumcentre(*a, *b, hover)?;
|
||
if t.cmd == "sketch.circle.three_point" {
|
||
sk.add_circle(centre, centre.dist(*a), None, None).ok()?;
|
||
} else {
|
||
let angle = |p: Vec2| (p - centre).angle();
|
||
let span = |p: Vec2| (angle(p) - angle(*a)).rem_euclid(std::f64::consts::TAU);
|
||
let ccw = span(hover) < span(*b);
|
||
sk.add_arc(centre, if ccw { *a } else { *b }, if ccw { *b } else { *a }, [None; 3], None).ok()?;
|
||
if let Some(curve) = sk.curves.first_mut() {
|
||
curve.reversed = !ccw;
|
||
}
|
||
}
|
||
}
|
||
("sketch.arc.center_point", [c, a]) => {
|
||
let start = (*a - *c).angle();
|
||
let sweep = sweep.unwrap_or_else(|| center_arc_sweep(t, hover));
|
||
if !sweep.is_finite() || sweep.abs() <= 1e-9 || sweep.abs() >= std::f64::consts::TAU {
|
||
return None;
|
||
}
|
||
let b = *c + Vec2::from_angle(start + sweep) * c.dist(*a);
|
||
sk.add_arc(*c, if sweep > 0.0 { *a } else { b }, if sweep > 0.0 { b } else { *a }, [None; 3], None).ok()?;
|
||
if let Some(curve) = sk.curves.first_mut() {
|
||
curve.reversed = sweep < 0.0;
|
||
}
|
||
}
|
||
("sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point", [a, b]) => {
|
||
let dir = (*b - *a).normalized()?;
|
||
// Typed widths can be smaller than the final click's pointer minimum.
|
||
let width = slot_width.unwrap_or_else(|| (2.0 * dir.cross(hover - *a).abs()).max(1e-3));
|
||
if !width.is_finite() || width <= 1e-9 {
|
||
return None;
|
||
}
|
||
let radius = width * 0.5;
|
||
let (c0, c1) = match t.cmd {
|
||
"sketch.slot.overall" if a.dist(*b) > width => (*a + dir * radius, *b - dir * radius),
|
||
"sketch.slot.overall" => return None,
|
||
"sketch.slot.center_point" => (*a * 2.0 - *b, *b),
|
||
_ => (*a, *b),
|
||
};
|
||
let n = dir.perp() * radius;
|
||
sk.add_line(c0 - n, c1 - n, None, None, None).ok()?;
|
||
sk.add_arc(c1, c1 - n, c1 + n, [None; 3], None).ok()?;
|
||
sk.add_line(c1 + n, c0 + n, None, None, None).ok()?;
|
||
sk.add_arc(c0, c0 + n, c0 - n, [None; 3], None).ok()?;
|
||
}
|
||
("sketch.slot.arc_center" | "sketch.slot.arc_three_point", [a, b, c]) => {
|
||
let (centre, start, end, radius, width) = if t.cmd == "sketch.slot.arc_center" {
|
||
(*a, *b, *c, a.dist(*b), (2.0 * (hover.dist(*a) - a.dist(*b)).abs()).max(1e-3))
|
||
} else {
|
||
let centre = preview_circumcentre(*a, *c, *b)?;
|
||
let span = |p: Vec2| ((p - centre).angle() - (*a - centre).angle()).rem_euclid(std::f64::consts::TAU);
|
||
let (start, end) = if span(*b) < span(*c) { (*a, *c) } else { (*c, *a) };
|
||
(centre, start, end, centre.dist(*a), (2.0 * hover.dist(*c)).max(1e-3))
|
||
};
|
||
let width = slot_width.unwrap_or(width);
|
||
let t0 = (start - centre).angle();
|
||
let sweep = ((end - centre).angle() - t0).rem_euclid(std::f64::consts::TAU);
|
||
let half = width * 0.5;
|
||
if !radius.is_finite()
|
||
|| !half.is_finite()
|
||
|| half >= radius
|
||
|| end.dist(centre) < 1e-9
|
||
|| !(sweep > 1e-6 && sweep < std::f64::consts::TAU - 1e-6)
|
||
{
|
||
return None;
|
||
}
|
||
let at = |angle: f64, r: f64| centre + Vec2::from_angle(angle) * r;
|
||
let t1 = t0 + sweep;
|
||
sk.add_arc(centre, at(t0, radius + half), at(t1, radius + half), [None; 3], None).ok()?;
|
||
sk.add_arc(centre, at(t0, radius - half), at(t1, radius - half), [None; 3], None).ok()?;
|
||
sk.add_arc(at(t1, radius), at(t1, radius + half), at(t1, radius - half), [None; 3], None).ok()?;
|
||
sk.add_arc(at(t0, radius), at(t0, radius - half), at(t0, radius + half), [None; 3], None).ok()?;
|
||
let guide = sk.add_arc(centre, at(t0, radius), at(t1, radius), [None; 3], None).ok()?;
|
||
sk.curves.get_mut(guide)?.construction = true;
|
||
}
|
||
("sketch.ellipse", [c, m]) => {
|
||
let u = (*m - *c).normalized()?;
|
||
let d = hover - *c;
|
||
let k = 1.0 - (d.dot(u) / c.dist(*m)).powi(2);
|
||
if !k.is_finite() || k <= 1e-12 {
|
||
return None;
|
||
}
|
||
let r = d.cross(u).abs() / k.sqrt();
|
||
let c = sk.add_point(*c, None).ok()?;
|
||
let m = sk.add_point(*m, None).ok()?;
|
||
sk.add_curve(CurveKind::Ellipse { c, m, r }, None).ok()?;
|
||
}
|
||
("sketch.conic", [a, b]) => {
|
||
// Positioning the apex (the third click): the live conic through the cursor at the
|
||
// typed `rho` (or the default parabola's 0.5), so the curve it is about to become is
|
||
// on screen while it is being placed, and a typed `rho` reshapes it before the
|
||
// click. Without this the tool showed only the straight start-to-end, end-to-cursor
|
||
// rubber band every tool draws while it has points still to place.
|
||
let rho = rho.filter(|r| r.is_finite() && *r > 1e-6 && *r < 1.0 - 1e-6).unwrap_or(0.5);
|
||
let a = sk.add_point(*a, None).ok()?;
|
||
let b = sk.add_point(*b, None).ok()?;
|
||
let apex = sk.add_point(hover, None).ok()?;
|
||
sk.add_curve(CurveKind::Conic { a, b, apex, rho }, None).ok()?;
|
||
}
|
||
("sketch.spline.fit_point" | "sketch.spline.control_point" | "sketch.spline.control_point_5", points) if !points.is_empty() => {
|
||
let periodic = t.cmd == "sketch.spline.fit_point" && points.len() >= 3 && points.first() == Some(&hover);
|
||
let mut indices = points.iter().map(|p| sk.add_point(*p, None).ok()).collect::<Option<Vec<_>>>()?;
|
||
if periodic {
|
||
indices.push(*indices.first()?);
|
||
} else if points.last() != Some(&hover) {
|
||
indices.push(sk.add_point(hover, None).ok()?);
|
||
}
|
||
sk.add_curve(
|
||
CurveKind::Spline {
|
||
pts: indices,
|
||
control: t.cmd != "sketch.spline.fit_point",
|
||
degree: if t.cmd == "sketch.spline.control_point_5" { 5 } else { 3 },
|
||
periodic,
|
||
nurbs: None,
|
||
},
|
||
None,
|
||
)
|
||
.ok()?;
|
||
}
|
||
_ => return None,
|
||
}
|
||
Some(sk)
|
||
}
|
||
|
||
fn preview_circumcentre(a: Vec2, b: Vec2, c: Vec2) -> Option<Vec2> {
|
||
let ab = b - a;
|
||
let ac = c - a;
|
||
let d = 2.0 * ab.cross(ac);
|
||
if !d.is_finite() || d.abs() < 1e-12 {
|
||
return None;
|
||
}
|
||
let centre = a + Vec2::new(ac.y * ab.len2() - ab.y * ac.len2(), ab.x * ac.len2() - ac.x * ab.len2()) / d;
|
||
centre.is_finite().then_some(centre)
|
||
}
|
||
|
||
/// The polygon's actual straight edges, in the same orientation as the eventual command.
|
||
/// Keep preview work bounded even while a side-count expression is being edited.
|
||
pub(crate) fn polygon_outline(t: &Tool, hover: Vec2, sides: f64) -> Option<Vec<Vec2>> {
|
||
if !hover.is_finite() || !(3.0..=200.0).contains(&sides) || sides.fract() != 0.0 || t.pts.len() != 1 {
|
||
return None;
|
||
}
|
||
let a = t.pts.first()?.0;
|
||
let n = sides as usize;
|
||
let half = std::f64::consts::PI / sides;
|
||
let distance = a.dist(hover);
|
||
if !a.is_finite() || !distance.is_finite() || distance <= 1e-9 {
|
||
return None;
|
||
}
|
||
let (centre, radius, start) = match t.cmd {
|
||
"sketch.polygon.inscribed" => (a, distance, (hover - a).angle()),
|
||
"sketch.polygon.circumscribed" => (a, distance / half.cos(), (hover - a).angle() + half),
|
||
"sketch.polygon.edge" => {
|
||
let radius = distance / (2.0 * half.sin());
|
||
let centre = (a + hover) * 0.5 + (hover - a).normalized()?.perp() * (radius * half.cos());
|
||
(centre, radius, (a - centre).angle())
|
||
}
|
||
_ => return None,
|
||
};
|
||
let mut corners: Vec<_> = (0..n).map(|i| centre + Vec2::from_angle(start + std::f64::consts::TAU * i as f64 / sides) * radius).collect();
|
||
if corners.iter().any(|p| !p.is_finite()) {
|
||
return None;
|
||
}
|
||
corners.push(*corners.first()?);
|
||
Some(corners)
|
||
}
|
||
|
||
pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {
|
||
if crate::sketch3d::preview(app, t, painter, proj) {
|
||
return;
|
||
}
|
||
if t.kind == Kind::Ext {
|
||
return crate::sketch_tools::preview(app, t, painter, proj);
|
||
}
|
||
let Some(sid) = app.session.active_sketch else { return };
|
||
let st = crate::open_meshing::session_world(&app.session);
|
||
let Some(ss) = st.sketch(sid) else { return };
|
||
let to = |p: Vec2| proj.to_screen(ss.plane.to_world(p));
|
||
// Drawn straight onto the view: its side's colours (#4146).
|
||
let tk = crate::theme::Tokens::view();
|
||
let stroke = Stroke::new(1.5, tk.sketch_accent);
|
||
if let Some((hp, snap)) = &t.hover
|
||
&& let Some(sp) = to(*hp)
|
||
{
|
||
painter.circle_stroke(sp, if snap.is_some() { 6.0 } else { 3.0 }, stroke);
|
||
if snap.as_deref() == Some("Midpoint") && t.kind == Kind::HorizontalVertical {
|
||
painter.circle_stroke(sp, 8.0, Stroke::new(2.0, tk.accent));
|
||
}
|
||
let readout = painter.text(
|
||
crate::tool_cursor::readout_at(painter, proj.rect, sp),
|
||
egui::Align2::LEFT_TOP,
|
||
format!("{}, {}", crate::prefs::show_mm(app, hp.x, 1), crate::prefs::show_mm(app, hp.y, 1)),
|
||
egui::FontId::proportional(crate::theme::Tokens::get().font_small),
|
||
tk.text_dim,
|
||
);
|
||
crate::scenario::publish_rect("viewport:readout", readout);
|
||
}
|
||
if matches!(t.kind, Kind::HorizontalVertical | Kind::Dimension) {
|
||
for target in &t.point_picks {
|
||
let midpoint = target.get("midpoint").and_then(Value::as_str).or_else(|| target.as_str().and_then(|id| id.strip_prefix("mid:")));
|
||
let point = if let Some(id) = midpoint {
|
||
ss.sketch.curve_index(id).and_then(|l| match ss.sketch.shape(l)? {
|
||
solidcraft_engine::sketch::Shape::Line { a, b } => Some((a + b) * 0.5),
|
||
_ => None,
|
||
})
|
||
} else {
|
||
target.as_str().and_then(|id| ss.sketch.resolve_point(id)).and_then(|p| ss.sketch.point(p))
|
||
};
|
||
if let Some(sp) = point.and_then(to) {
|
||
painter.circle_stroke(sp, 6.0, Stroke::new(2.0, tk.accent));
|
||
}
|
||
}
|
||
}
|
||
let Some(hover) = t.hover.as_ref() else { return };
|
||
let h = crate::sketch_dims::shown(app, t, hover);
|
||
if let Some(corners) = polygon_outline(t, h, crate::sketch_dims::locked_value(app, t, "Sides").unwrap_or(6.0)) {
|
||
let outline: Vec<_> = corners.iter().map(|c| ss.plane.to_world(*c)).collect();
|
||
paint_sketch_path(&outline, crate::sketch_palette::mode(app), painter, proj, stroke);
|
||
crate::scenario::publish_count("polygon_preview_edges", (corners.len() - 1) as f64);
|
||
if t.cmd == "sketch.polygon.edge" {
|
||
return;
|
||
}
|
||
}
|
||
|
||
if let Some(curve) = preview_curve(
|
||
t,
|
||
h,
|
||
crate::sketch_dims::locked_value(app, t, "Sweep"),
|
||
crate::sketch_dims::locked_value(app, t, "Rho"),
|
||
crate::sketch_dims::locked_value(app, t, "Width"),
|
||
) {
|
||
paint_preview_curve(curve, &ss.plane, painter, proj, stroke, crate::sketch_palette::mode(app));
|
||
return;
|
||
}
|
||
let pts: Vec<Vec2> = t.pts.iter().map(|p| p.0).collect();
|
||
let line = |a: Vec2, b: Vec2| {
|
||
paint_sketch_path(&[ss.plane.to_world(a), ss.plane.to_world(b)], crate::sketch_palette::mode(app), painter, proj, stroke);
|
||
};
|
||
match (t.cmd, pts.as_slice()) {
|
||
("sketch.line", [.., last]) => {
|
||
line(*last, h);
|
||
// Horizontal/vertical inference marker.
|
||
if let Some(horizontal) = crate::sketch_dims::axis_aligned(*last, h)
|
||
&& let Some(m) = to((*last + h) * 0.5)
|
||
{
|
||
let g = if horizontal { egui::vec2(0.0, -12.0) } else { egui::vec2(12.0, 0.0) };
|
||
painter.text(
|
||
m + g,
|
||
egui::Align2::CENTER_CENTER,
|
||
if horizontal { "H" } else { "V" },
|
||
egui::FontId::proportional(crate::theme::Tokens::get().font_micro),
|
||
tk.sketch_accent,
|
||
);
|
||
}
|
||
}
|
||
("sketch.rectangle.two_point", [a]) => {
|
||
let (b, c) = (Vec2::new(h.x, a.y), Vec2::new(a.x, h.y));
|
||
line(*a, b);
|
||
line(b, h);
|
||
line(h, c);
|
||
line(c, *a);
|
||
}
|
||
("sketch.rectangle.rounded", [a]) => {
|
||
let r = crate::sketch_dims::rounded_radius(app, t, *a, h);
|
||
let outline: Vec<_> = rounded_outline(*a, h, r).into_iter().map(|q| ss.plane.to_world(q)).collect();
|
||
paint_sketch_path(&outline, crate::sketch_palette::mode(app), painter, proj, stroke);
|
||
}
|
||
("sketch.rectangle.center", [c]) => {
|
||
let d = h - *c;
|
||
let k =
|
||
[Vec2::new(c.x - d.x, c.y - d.y), Vec2::new(c.x + d.x, c.y - d.y), Vec2::new(c.x + d.x, c.y + d.y), Vec2::new(c.x - d.x, c.y + d.y)];
|
||
for i in 0..4 {
|
||
line(k[i], k[(i + 1) % 4]);
|
||
}
|
||
}
|
||
(_, [a]) => line(*a, h),
|
||
(_, [a, b]) => {
|
||
line(*a, *b);
|
||
line(*b, h);
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
/// The closed outline of the rectangle with corners `a`, `b` and corner radius `r` (clamped to
|
||
/// fit), as points for a preview: counter-clockwise, arcs sampled, first point repeated last.
|
||
pub(crate) fn rounded_outline(a: Vec2, b: Vec2, r: f64) -> Vec<Vec2> {
|
||
let (lo, hi) = (Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y)));
|
||
let r = if r.is_finite() { r.clamp(0.0, 0.5 * (hi.x - lo.x).min(hi.y - lo.y)) } else { 0.0 };
|
||
let q = std::f64::consts::FRAC_PI_2;
|
||
// Corner centres and the angle each arc starts at, CCW from the bottom-right corner.
|
||
let corners = [
|
||
(Vec2::new(hi.x - r, lo.y + r), -q),
|
||
(Vec2::new(hi.x - r, hi.y - r), 0.0),
|
||
(Vec2::new(lo.x + r, hi.y - r), q),
|
||
(Vec2::new(lo.x + r, lo.y + r), 2.0 * q),
|
||
];
|
||
let mut pts = Vec::with_capacity(4 * 9 + 1);
|
||
for (c, a0) in corners {
|
||
for i in 0..=8 {
|
||
pts.push(c + Vec2::from_angle(a0 + q * f64::from(i) / 8.0) * r);
|
||
}
|
||
}
|
||
if let Some(first) = pts.first().copied() {
|
||
pts.push(first);
|
||
}
|
||
pts
|
||
}
|