From 72fd3fd35b42cb24384f68dca52622236c2f330b Mon Sep 17 00:00:00 2001 From: ramox81 <184937705+ramox81@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:12:46 +0300 Subject: [PATCH] Linear dimensional constraints: point flow, dynamic dimension, driving parameter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DCLINEAR, DCHORIZONTAL, DCVERTICAL and DCALIGNED follow the reference flow: `Specify first constraint point or [Object] :`, `Specify second constraint point:`, `Specify dimension line location:`, then `Dimension text = …` and `Enter value or name and value :`. Linear reads horizontal or vertical from the dimension line location the way a linear dimension does; Object takes a line's, an arc's or a polyline segment's ends. A miss reports `No valid constraint point found.` / `No object found.` and asks again; another object type reports `Invalid selection for Linear. Select a line, polyline segment or arc.`. Each constraint creates a drawing parameter (`d1`, `d2`, …, or the typed `name=expression`), drives the constraint through it, and draws a dynamic dimension in constraint gray whose text follows CONSTRAINTNAMEFORMAT (`d1=100.0000`); the dimension is associated with the constrained objects and its text is refreshed after every solve. A typed value other than the measured one moves the second point while the first stays, and so does a later parameter edit. Deleting the constraint removes its dimension and, when nothing else reads it, its parameter. Co-Authored-By: Claude Fable 5.1 --- src/app/command_driver.rs | 248 ++++++++++++- src/app/commands/draw.rs | 42 ++- src/command.rs | 29 ++ src/modules/annotate/aligned_dim.rs | 40 +- src/modules/annotate/linear_dim.rs | 42 ++- src/modules/parametric/dim_constraint.rs | 445 +++++++++++++++++++++++ src/modules/parametric/mod.rs | 2 + src/scene/mod.rs | 5 + src/scene/parametric_constraints.rs | 81 ++++- 9 files changed, 898 insertions(+), 36 deletions(-) create mode 100644 src/modules/parametric/dim_constraint.rs diff --git a/src/app/command_driver.rs b/src/app/command_driver.rs index 0e21a8e6e..6a3584ab0 100644 --- a/src/app/command_driver.rs +++ b/src/app/command_driver.rs @@ -1103,6 +1103,50 @@ impl OpenCADStudio { TableCellEditStart::Started } + /// Reports a refused command-line value and shows the prompt again. + fn reprompt_active_command(&mut self, i: usize, message: &str) { + self.command_line.push_error(message); + if let Some(prompt) = self.tabs[i].active_cmd.as_ref().map(|command| command.prompt()) { + self.command_line.push_info(&prompt); + } + } + + /// Drops what removed dimensional constraints leave behind: their dynamic + /// dimensions, and their parameters when no other constraint reads them. + pub(crate) fn purge_dimensional_extras( + &mut self, + i: usize, + dimensions: Vec, + parameters: Vec, + ) { + if !dimensions.is_empty() { + self.tabs[i].scene.erase_entities(&dimensions); + } + let unused: Vec = parameters + .into_iter() + .filter(|name| { + !self.tabs[i] + .scene + .parametric_constraints + .iter() + .flat_map(|set| set.constraints.iter()) + .any(|constraint| { + matches!( + &constraint.driving_param, + Some(crate::scene::named_parameters::DrivingValue::Named(used)) + if used == name + ) + }) + }) + .collect(); + if !unused.is_empty() { + self.tabs[i].scene.record_undo_named_parameters_before(); + for name in &unused { + self.tabs[i].scene.named_parameters_mut().remove(name); + } + } + } + fn remove_parametric_constraint( &mut self, id: crate::scene::parametric_constraints::ConstraintId, @@ -1117,8 +1161,13 @@ impl OpenCADStudio { return false; }; let touched: Vec = constraint.refs.iter().map(|r| r.entity).collect(); + let dimension = set.dimensions.get(&id).copied(); + let parameter = match &constraint.driving_param { + Some(crate::scene::named_parameters::DrivingValue::Named(name)) => Some(name.clone()), + _ => None, + }; let constraints_before = set.clone(); - let pending = self.begin_undo(i, label, touched.len(), true); + let pending = self.begin_undo(i, label, touched.len(), dimension.is_none()); self.tabs[i] .scene .record_undo_parametric_constraints_before(scope, constraints_before); @@ -1126,6 +1175,11 @@ impl OpenCADStudio { .scene .parametric_constraint_set_mut(scope) .remove(id); + self.purge_dimensional_extras( + i, + dimension.into_iter().collect(), + parameter.into_iter().collect(), + ); if self.tabs[i].scene.selected_constraint == Some(id) { self.tabs[i].scene.selected_constraint = None; } @@ -1219,6 +1273,23 @@ impl OpenCADStudio { .flat_map(|c| c.refs.iter().map(|r| r.entity)) .collect(); + // A changed value moves a dimensional constraint's second point; its + // first point stays, as in the reference. + let anchors: Vec = self.tabs[i] + .scene + .parametric_constraints + .iter() + .flat_map(|set| set.constraints.iter()) + .filter(|c| { + c.enabled + && matches!( + c.driving_param, + Some(crate::scene::named_parameters::DrivingValue::Named(_)) + ) + }) + .filter_map(|c| c.refs.first().copied()) + .filter(|reference| reference.marker.is_some()) + .collect(); let pending = self.begin_undo(i, "Apply named parameters", touched.len(), true); self.tabs[i].scene.record_undo_named_parameters_before(); self.tabs[i].scene.named_parameters = table; @@ -1228,10 +1299,15 @@ impl OpenCADStudio { .into_iter() .map(|h| (h, crate::scene::ChangeKind::Modified)) .collect(); - self.tabs[i].scene.bump_entities(&changes); + self.tabs[i].scene.bump_entities_with_parametric_policy( + &changes, + &anchors, + self.constraint_solve_mode, + ); } else { self.tabs[i].scene.sync_native_parametric_graph(); } + self.tabs[i].scene.refresh_dynamic_dimension_texts(); if let Some(pd) = pending { self.commit_undo_delta(i, pd); } @@ -3450,6 +3526,174 @@ impl OpenCADStudio { self.commit_undo_delta(i, pd); } } + CmdResult::CheckConstraintPoint(pick) => { + use crate::scene::parametric_constraints::{ + nearest_parametric_point, nearest_parametric_point_on_entity, resolve_point, + }; + let scope = self.tabs[i].current_parametric_scope(); + let resolved = { + let document = &self.tabs[i].scene.document; + let world = + acadrust::types::Vector3::new(pick.point.x, pick.point.y, pick.point.z); + let reference = match pick.handle { + Some(handle) => { + nearest_parametric_point_on_entity(document, scope, handle, world) + } + None => nearest_parametric_point(document, scope, world, None), + }; + reference.map(|reference| { + let point = document + .get_entity(reference.entity) + .zip(reference.marker) + .and_then(|(entity, marker)| resolve_point(entity, marker)) + .map_or(pick.point, |p| glam::DVec3::new(p.x, p.y, p.z)); + (reference, point) + }) + }; + let Some((reference, point)) = resolved else { + return self.apply_cmd_result(CmdResult::ReportError( + crate::modules::parametric::DimConstraintCommand::NO_POINT.to_string(), + )); + }; + let result = self.tabs[i] + .active_cmd + .as_mut() + .map(|command| command.accept_constraint_point(reference, point)); + return match result { + Some(result) => self.apply_cmd_result(result), + None => Task::none(), + }; + } + CmdResult::AddDimensionalConstraint { + kind, + first, + second, + first_point, + second_point, + location, + axis, + name, + expression, + label, + } => { + use crate::modules::annotate::{aligned_dim, linear_dim}; + use crate::scene::named_parameters::{is_valid_name, DrivingValue}; + use crate::scene::parametric_constraints::{dynamic_dimension_text, ConstraintKind}; + + let scope = self.tabs[i].current_parametric_scope(); + let refs = vec![first, second]; + // A refused value keeps the prompt open, as the reference's + // editor does. + if let Err(message) = self.tabs[i].scene.validate_parametric_constraint( + kind, + &refs, + Some(&DrivingValue::Literal(1.0)), + ) { + self.reprompt_active_command(i, message); + return Task::none(); + } + let name = name.trim().to_string(); + if !is_valid_name(&name) { + self.reprompt_active_command(i, "Invalid parameter name."); + return Task::none(); + } + let mut table = self.tabs[i].scene.named_parameters().clone(); + if let Err(error) = table.set(&name, &expression) { + self.reprompt_active_command(i, &error.to_string()); + return Task::none(); + } + let value = match table.resolve(&name) { + Ok(value) if value.is_finite() => value, + _ => { + self.reprompt_active_command(i, "Invalid expression."); + return Task::none(); + } + }; + let text = dynamic_dimension_text( + &name, + value, + self.tabs[i].scene.constraint_name_format, + ); + let mut entity = if kind == ConstraintKind::Distance { + aligned_dim::aligned_dimension_entity( + first_point, + second_point, + location, + Some(text), + ) + } else { + linear_dim::linear_dimension_entity( + first_point, + second_point, + location, + axis, + Some(text), + ) + }; + crate::scene::creation_style::apply_current_creation_styles( + &self.tabs[i].scene.document, + &mut entity, + ); + let layer = self.tabs[i].active_layer.clone(); + if layer != "0" { + entity.as_entity_mut().set_layer(layer); + } + // A dynamic dimension draws in the constraint gray, not the + // current color. + entity.common_mut().color = acadrust::types::Color::Rgb { + r: 103, + g: 109, + b: 118, + }; + let constraints_before = self.tabs[i] + .scene + .parametric_constraint_set(scope) + .cloned() + .unwrap_or_else(|| { + crate::scene::parametric_constraints::ParametricConstraintSet::new(scope) + }); + let mut touched = vec![first.entity]; + if second.entity != first.entity { + touched.push(second.entity); + } + let pending = self.begin_undo(i, label, touched.len() + 1, false); + self.tabs[i] + .scene + .record_undo_parametric_constraints_before(scope, constraints_before); + self.tabs[i].scene.record_undo_named_parameters_before(); + self.tabs[i].scene.named_parameters = table; + let dimension = self.tabs[i].scene.add_entity(entity); + let set = self.tabs[i].scene.parametric_constraint_set_mut(scope); + let id = set.add(kind, refs, Some(DrivingValue::Named(name))); + set.dimensions.insert(id, dimension); + self.tabs[i].scene.note_parametric_constraint_applied( + scope, + id, + self.constraint_bar_display, + ); + self.tabs[i].scene.attach_dimension_association( + dimension, + vec![Some(first.entity), Some(second.entity)], + ); + let changes: Vec<(Handle, crate::scene::ChangeKind)> = touched + .into_iter() + .map(|handle| (handle, crate::scene::ChangeKind::Modified)) + .collect(); + // The first point stays; a value other than the measured one + // moves the second, as in the reference. + self.tabs[i].scene.bump_entities_with_parametric_policy( + &changes, + &[first], + self.constraint_solve_mode, + ); + self.tabs[i].dirty = true; + self.tabs[i].active_cmd = None; + self.tabs[i].snap_result = None; + self.refresh_properties(); + if let Some(pd) = pending { + self.commit_undo_delta(i, pd); + } + } CmdResult::AddFixedConstraint(pick) => { use crate::modules::parametric::FixConstraintCommand; use crate::scene::parametric_constraints::{ diff --git a/src/app/commands/draw.rs b/src/app/commands/draw.rs index 582cbfb41..79d66aa27 100644 --- a/src/app/commands/draw.rs +++ b/src/app/commands/draw.rs @@ -1131,7 +1131,26 @@ impl OpenCADStudio { self.command_line.push_output("No constraints found."); return None; } - let pending = self.begin_undo(i, "Delete constraints", handles.len(), true); + let dimensions: Vec = ids + .iter() + .filter_map(|id| before.dimensions.get(id).copied()) + .collect(); + let parameters: Vec = ids + .iter() + .filter_map(|id| before.get(*id)) + .filter_map(|constraint| match &constraint.driving_param { + Some(crate::scene::named_parameters::DrivingValue::Named(name)) => { + Some(name.clone()) + } + _ => None, + }) + .collect(); + let pending = self.begin_undo( + i, + "Delete constraints", + handles.len(), + dimensions.is_empty(), + ); self.tabs[i] .scene .record_undo_parametric_constraints_before(scope, before); @@ -1139,6 +1158,7 @@ impl OpenCADStudio { for id in &ids { set.remove(*id); } + self.purge_dimensional_extras(i, dimensions, parameters); let changes: Vec<_> = handles .iter() .copied() @@ -1726,8 +1746,24 @@ impl OpenCADStudio { } } - "DCONSTRAINT" | "DCLINEAR" | "DCHORIZONTAL" | "DCVERTICAL" | "DCALIGNED" - | "DCRADIUS" | "DCDIAMETER" => { + "DCLINEAR" | "DCHORIZONTAL" | "DCVERTICAL" | "DCALIGNED" => { + use crate::modules::parametric::{DimConstraintAxis, DimConstraintCommand}; + use crate::scene::parametric_constraints::next_dimensional_parameter_name; + let axis = match cmd { + "DCHORIZONTAL" => DimConstraintAxis::Horizontal, + "DCVERTICAL" => DimConstraintAxis::Vertical, + "DCALIGNED" => DimConstraintAxis::Aligned, + _ => DimConstraintAxis::Linear, + }; + let name = next_dimensional_parameter_name(self.tabs[i].scene.named_parameters()); + // Both constraint points are picked inside the command. + self.tabs[i].scene.deselect_all(); + let command = DimConstraintCommand::new(axis, name); + self.command_line.push_info(&command.prompt()); + self.tabs[i].active_cmd = Some(Box::new(command)); + } + + "DCONSTRAINT" | "DCRADIUS" | "DCDIAMETER" => { let handles = self.tabs[i].scene.selected_handles_in_order(); if handles.is_empty() { use crate::modules::draw::select::SelectObjectsCommand; diff --git a/src/command.rs b/src/command.rs index 6655c5351..b1b9d48e9 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1610,6 +1610,25 @@ pub enum CmdResult { multiple: bool, label: &'static str, }, + /// Resolves a constraint-point pick against the live document and hands + /// it back through `CadCommand::accept_constraint_point`; a miss reports + /// `No valid constraint point found.` and asks again. + CheckConstraintPoint(CoincidentPick), + /// Adds a dimensional constraint between two constraint points together + /// with the dynamic dimension that shows it and the parameter + /// (`name` = `expression`) that drives it. + AddDimensionalConstraint { + kind: crate::scene::parametric_constraints::ConstraintKind, + first: crate::scene::parametric_constraints::ParametricRef, + second: crate::scene::parametric_constraints::ParametricRef, + first_point: DVec3, + second_point: DVec3, + location: DVec3, + axis: DVec3, + name: String, + expression: String, + label: &'static str, + }, /// Adds a point or object symmetry relation around a picked line. The /// first reference and axis remain fixed during initial placement. AddSymmetricConstraint { @@ -2453,6 +2472,16 @@ pub trait CadCommand: Send { false } + /// A constraint point the host resolved for a `CheckConstraintPoint` + /// pick, with its world position. + fn accept_constraint_point( + &mut self, + _reference: crate::scene::parametric_constraints::ParametricRef, + _point: DVec3, + ) -> CmdResult { + CmdResult::NeedPoint + } + /// Include filled hatch / DXF SOLID regions in the entity hit-test. /// /// Most entity-pick commands operate on curve geometry and intentionally diff --git a/src/modules/annotate/aligned_dim.rs b/src/modules/annotate/aligned_dim.rs index 36013041b..179cefed2 100644 --- a/src/modules/annotate/aligned_dim.rs +++ b/src/modules/annotate/aligned_dim.rs @@ -67,26 +67,36 @@ impl AlignedDimensionCommand { let first = self.plane.to_local(first); let second = self.plane.to_local(second); let point = self.plane.to_local(point); - let mut dim = DimensionAligned::new(v3(first), v3(second)); - // The placement point is stored so commit matches the preview. - dim.definition_point = v3(point); - dim.base.definition_point = v3(point); - let (d1, d2) = dim_line_endpoints(first, second, point); - dim.base.text_middle_point = v3((d1 + d2) * 0.5); - dim.base.insertion_point = dim.base.text_middle_point; - dim.base.actual_measurement = dim.measurement(); - crate::entities::dimension::set_dimension_text_override( - &mut dim.base, - self.text_override.clone(), - ); + let mut entity = aligned_dimension_entity(first, second, point, self.text_override.clone()); // An explicit text angle overrides the default rotation. - if let Some(angle) = self.text_angle { - dim.base.text_rotation = angle; + if let (Some(angle), EntityType::Dimension(dimension)) = (self.text_angle, &mut entity) { + dimension.base_mut().text_rotation = angle; } - self.plane.place_entity(EntityType::Dimension(Dimension::Aligned(dim))) + self.plane.place_entity(entity) } } +/// An aligned dimension between two points of the working plane, its +/// dimension line through `point` — what DIMALIGNED places and what an +/// aligned dimensional constraint draws. +pub(crate) fn aligned_dimension_entity( + first: DVec3, + second: DVec3, + point: DVec3, + text_override: Option, +) -> EntityType { + let mut dim = DimensionAligned::new(v3(first), v3(second)); + // The placement point is stored so commit matches the preview. + dim.definition_point = v3(point); + dim.base.definition_point = v3(point); + let (d1, d2) = dim_line_endpoints(first, second, point); + dim.base.text_middle_point = v3((d1 + d2) * 0.5); + dim.base.insertion_point = dim.base.text_middle_point; + dim.base.actual_measurement = dim.measurement(); + crate::entities::dimension::set_dimension_text_override(&mut dim.base, text_override); + EntityType::Dimension(Dimension::Aligned(dim)) +} + impl CadCommand for AlignedDimensionCommand { fn set_working_plane(&mut self, plane: WorkingPlane) { self.plane = plane; diff --git a/src/modules/annotate/linear_dim.rs b/src/modules/annotate/linear_dim.rs index 5e9b00c94..ed6066506 100644 --- a/src/modules/annotate/linear_dim.rs +++ b/src/modules/annotate/linear_dim.rs @@ -15,7 +15,7 @@ use glam::DVec3; use crate::t; /// Select the measured axis from where the dimension line clears the points. -fn measure_axis(first: DVec3, second: DVec3, def: DVec3) -> DVec3 { +pub(crate) fn measure_axis(first: DVec3, second: DVec3, def: DVec3) -> DVec3 { let outside = |value: f64, a: f64, b: f64| { let (low, high) = if a <= b { (a, b) } else { (b, a) }; (low - value).max(value - high).max(0.0) @@ -113,26 +113,38 @@ impl LinearDimensionCommand { let first = self.plane.to_local(first); let second = self.plane.to_local(second); let point = self.plane.to_local(point); - let mut dim = DimensionLinear::new(v3(first), v3(second)); let axis = self.axis_mode.axis(first, second, point); - dim.rotation = axis.y.atan2(axis.x); - dim.set_offset(dimension_line_offset(second, point, axis)); - dim.base.definition_point = dim.definition_point; - dim.base.text_middle_point = v3(linear_text_pos(first, second, point, axis)); - dim.base.insertion_point = dim.base.text_middle_point; - dim.base.actual_measurement = dim.measurement(); - crate::entities::dimension::set_dimension_text_override( - &mut dim.base, - self.text_override.clone(), - ); + let mut entity = + linear_dimension_entity(first, second, point, axis, self.text_override.clone()); // An explicit text angle overrides the UCS-derived rotation. - if let Some(angle) = self.text_angle { - dim.base.text_rotation = angle; + if let (Some(angle), EntityType::Dimension(dimension)) = (self.text_angle, &mut entity) { + dimension.base_mut().text_rotation = angle; } - self.plane.place_entity(EntityType::Dimension(Dimension::Linear(dim))) + self.plane.place_entity(entity) } } +/// A linear dimension between two points of the working plane, its +/// dimension line through `point` along `axis` — what DIMLINEAR places and +/// what a dynamic dimensional constraint draws. +pub(crate) fn linear_dimension_entity( + first: DVec3, + second: DVec3, + point: DVec3, + axis: DVec3, + text_override: Option, +) -> EntityType { + let mut dim = DimensionLinear::new(v3(first), v3(second)); + dim.rotation = axis.y.atan2(axis.x); + dim.set_offset(dimension_line_offset(second, point, axis)); + dim.base.definition_point = dim.definition_point; + dim.base.text_middle_point = v3(linear_text_pos(first, second, point, axis)); + dim.base.insertion_point = dim.base.text_middle_point; + dim.base.actual_measurement = dim.measurement(); + crate::entities::dimension::set_dimension_text_override(&mut dim.base, text_override); + EntityType::Dimension(Dimension::Linear(dim)) +} + impl CadCommand for LinearDimensionCommand { fn name(&self) -> &'static str { "DIMLINEAR" diff --git a/src/modules/parametric/dim_constraint.rs b/src/modules/parametric/dim_constraint.rs new file mode 100644 index 000000000..a4ccb007d --- /dev/null +++ b/src/modules/parametric/dim_constraint.rs @@ -0,0 +1,445 @@ +use acadrust::{EntityType, Handle}; +use glam::DVec3; + +use crate::command::{CadCommand, CmdOption, CmdResult, CoincidentPick}; +use crate::scene::parametric_constraints::{ + measured_expression, resolve_point, ConstraintKind, ParametricRef, +}; + +/// Which distance a dimensional constraint measures. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum DimConstraintAxis { + /// Horizontal or vertical, decided by where the dimension line goes. + Linear, + Horizontal, + Vertical, + Aligned, +} + +#[derive(Clone, Copy)] +enum Step { + /// `Specify first constraint point or [Object] :` + First, + /// `Select object:` + Object, + /// `Specify second constraint point:` + Second { + first: ParametricRef, + first_point: DVec3, + }, + /// `Specify dimension line location:` + Location { + first: ParametricRef, + second: ParametricRef, + first_point: DVec3, + second_point: DVec3, + }, + /// `Enter value or name and value :` + Value { + first: ParametricRef, + second: ParametricRef, + first_point: DVec3, + second_point: DVec3, + location: DVec3, + axis: DVec3, + kind: ConstraintKind, + measured: f64, + }, +} + +/// The reference's Linear/Horizontal/Vertical/Aligned dimensional constraint: +/// two constraint points (or one object's ends), a dimension line location, +/// then the parameter name and expression the dynamic dimension carries. +pub struct DimConstraintCommand { + axis: DimConstraintAxis, + step: Step, + picked_entity: Option, + /// The next free `dN` the host reserved for this constraint. + default_name: String, +} + +impl DimConstraintCommand { + pub const NO_OBJECT: &'static str = "No object found."; + pub const NO_POINT: &'static str = "No valid constraint point found."; + pub const SAME_POINT: &'static str = + "The object or point is already selected. Select a different object or constraint point."; + + pub fn new(axis: DimConstraintAxis, default_name: String) -> Self { + Self { + axis, + step: Step::First, + picked_entity: None, + default_name, + } + } + + fn command_name(&self) -> &'static str { + match self.axis { + DimConstraintAxis::Linear => "DCLINEAR", + DimConstraintAxis::Horizontal => "DCHORIZONTAL", + DimConstraintAxis::Vertical => "DCVERTICAL", + DimConstraintAxis::Aligned => "DCALIGNED", + } + } + + fn noun(&self) -> &'static str { + match self.axis { + DimConstraintAxis::Linear => "Linear", + DimConstraintAxis::Horizontal => "Horizontal", + DimConstraintAxis::Vertical => "Vertical", + DimConstraintAxis::Aligned => "Aligned", + } + } + + fn report(message: &str) -> CmdResult { + CmdResult::ReportError(message.to_string()) + } + + /// The two end points an object pick constrains: a line's or an arc's + /// ends, the picked polyline segment's vertices. + fn object_ends( + entity: &EntityType, + handle: Handle, + point: DVec3, + ) -> Option<(ParametricRef, ParametricRef)> { + match entity { + EntityType::Line(_) | EntityType::Arc(_) => { + Some((ParametricRef::point(handle, 0), ParametricRef::point(handle, 1))) + } + EntityType::LwPolyline(_) | EntityType::Polyline2D(_) => { + let (source, _, _) = + crate::scene::centerline::picked_source(entity, handle, point)?; + let index = source.segment_index; + // A closed polyline's last segment ends at the first vertex. + let end = if resolve_point(entity, index + 1).is_some() { + index + 1 + } else { + 0 + }; + Some((ParametricRef::point(handle, index), ParametricRef::point(handle, end))) + } + _ => None, + } + } + + fn world(entity: &EntityType, reference: ParametricRef) -> Option { + let point = resolve_point(entity, reference.marker?)?; + Some(DVec3::new(point.x, point.y, point.z)) + } + + /// The measured kind and axis: Linear reads the dimension line location + /// the way a linear dimension does, the others are fixed. + fn decide(&self, first: DVec3, second: DVec3, location: DVec3) -> (ConstraintKind, DVec3) { + match self.axis { + DimConstraintAxis::Linear => { + let axis = + crate::modules::annotate::linear_dim::measure_axis(first, second, location); + if axis.x.abs() > 0.5 { + (ConstraintKind::DistanceX, DVec3::X) + } else { + (ConstraintKind::DistanceY, DVec3::Y) + } + } + DimConstraintAxis::Horizontal => (ConstraintKind::DistanceX, DVec3::X), + DimConstraintAxis::Vertical => (ConstraintKind::DistanceY, DVec3::Y), + DimConstraintAxis::Aligned => ( + ConstraintKind::Distance, + (second - first).normalize_or(DVec3::X), + ), + } + } + + fn measured(kind: ConstraintKind, first: DVec3, second: DVec3) -> f64 { + match kind { + ConstraintKind::DistanceX => (second.x - first.x).abs(), + ConstraintKind::DistanceY => (second.y - first.y).abs(), + _ => (second - first).length(), + } + } + + fn build(&self, name: String, expression: String) -> Option { + let Step::Value { + first, + second, + first_point, + second_point, + location, + axis, + kind, + .. + } = self.step + else { + return None; + }; + if expression.trim().is_empty() { + return None; + } + Some(CmdResult::AddDimensionalConstraint { + kind, + first, + second, + first_point, + second_point, + location, + axis, + name, + expression, + label: match self.axis { + DimConstraintAxis::Linear => "Linear constraint", + DimConstraintAxis::Horizontal => "Horizontal distance constraint", + DimConstraintAxis::Vertical => "Vertical distance constraint", + DimConstraintAxis::Aligned => "Aligned constraint", + }, + }) + } +} + +impl CadCommand for DimConstraintCommand { + fn name(&self) -> &'static str { + self.command_name() + } + + fn prompt(&self) -> String { + let name = self.command_name(); + match self.step { + Step::First => { + format!("{name} Specify first constraint point or [Object] :") + } + Step::Object => format!("{name} Select object:"), + Step::Second { .. } => format!("{name} Specify second constraint point:"), + Step::Location { .. } => format!("{name} Specify dimension line location:"), + Step::Value { measured, .. } => format!( + "{name} Enter value or name and value <{}={}>:", + self.default_name, + measured_expression(measured) + ), + } + } + + fn options(&self) -> Vec { + matches!(self.step, Step::First) + .then(|| vec![CmdOption::new("Object", "O")]) + .unwrap_or_default() + } + + fn wants_text_input(&self) -> bool { + true + } + + fn point_step_accepts_keywords(&self) -> bool { + matches!(self.step, Step::First | Step::Value { .. }) + } + + fn on_text_input(&mut self, text: &str) -> Option { + match self.step { + Step::First => { + let keyword = text.trim().trim_start_matches('_').to_ascii_uppercase(); + if matches!(keyword.as_str(), "O" | "OBJECT") { + self.step = Step::Object; + return Some(CmdResult::NeedPoint); + } + None + } + Step::Value { .. } => { + let text = text.trim(); + let (name, expression) = match text.split_once('=') { + Some((name, expression)) => (name.trim().to_string(), expression.trim().to_string()), + None => (self.default_name.clone(), text.to_string()), + }; + self.build(name, expression) + } + _ => None, + } + } + + fn needs_entity_pick(&self) -> bool { + matches!(self.step, Step::First | Step::Object | Step::Second { .. }) + } + + fn entity_pick_accepts_points(&self) -> bool { + true + } + + fn typed_point_picks_entity(&self) -> bool { + true + } + + fn entity_pick_highlights_hover(&self) -> bool { + true + } + + fn inject_before_entity_pick(&self) -> bool { + true + } + + fn inject_picked_entity(&mut self, entity: EntityType) { + self.picked_entity = Some(entity); + } + + fn on_entity_pick(&mut self, handle: Handle, point: DVec3) -> CmdResult { + match self.step { + // The host resolves the constraint point and hands it back + // through `accept_constraint_point`. + Step::First | Step::Second { .. } => CmdResult::CheckConstraintPoint(CoincidentPick { + handle: (!handle.is_null()).then_some(handle), + point, + whole_curve: false, + }), + Step::Object => { + if handle.is_null() { + return Self::report(Self::NO_OBJECT); + } + let Some(entity) = self.picked_entity.take() else { + return CmdResult::NeedPoint; + }; + let Some((first, second)) = Self::object_ends(&entity, handle, point) else { + return Self::report(&format!( + "Invalid selection for {}. Select a line, polyline segment or arc.", + self.noun() + )); + }; + let (Some(first_point), Some(second_point)) = + (Self::world(&entity, first), Self::world(&entity, second)) + else { + return Self::report(Self::NO_POINT); + }; + self.step = Step::Location { + first, + second, + first_point, + second_point, + }; + CmdResult::NeedPoint + } + Step::Location { .. } | Step::Value { .. } => self.on_point(point), + } + } + + fn accept_constraint_point(&mut self, reference: ParametricRef, point: DVec3) -> CmdResult { + match self.step { + Step::First => { + self.step = Step::Second { + first: reference, + first_point: point, + }; + CmdResult::NeedPoint + } + Step::Second { first, first_point } => { + if first == reference { + return Self::report(Self::SAME_POINT); + } + self.step = Step::Location { + first, + second: reference, + first_point, + second_point: point, + }; + CmdResult::NeedPoint + } + _ => CmdResult::NeedPoint, + } + } + + fn on_point(&mut self, point: DVec3) -> CmdResult { + match self.step { + Step::First | Step::Second { .. } => CmdResult::CheckConstraintPoint(CoincidentPick { + handle: None, + point, + whole_curve: false, + }), + Step::Object => Self::report(Self::NO_OBJECT), + Step::Location { + first, + second, + first_point, + second_point, + } => { + let (kind, axis) = self.decide(first_point, second_point, point); + let measured = Self::measured(kind, first_point, second_point); + self.step = Step::Value { + first, + second, + first_point, + second_point, + location: point, + axis, + kind, + measured, + }; + CmdResult::ReportMeasurement(format!("Dimension text = {measured:.4}")) + } + Step::Value { .. } => CmdResult::NeedPoint, + } + } + + fn on_enter(&mut self) -> CmdResult { + match self.step { + Step::First => { + self.step = Step::Object; + CmdResult::NeedPoint + } + Step::Value { measured, .. } => self + .build(self.default_name.clone(), measured_expression(measured)) + .unwrap_or(CmdResult::Cancel), + _ => CmdResult::Cancel, + } + } + + fn on_escape(&mut self) -> CmdResult { + CmdResult::Cancel + } +} + +#[cfg(test)] +mod tests { + use super::*; + use acadrust::entities::Line; + use acadrust::types::Vector3; + + #[test] + fn object_pick_takes_the_line_ends_then_asks_for_the_location() { + let mut command = DimConstraintCommand::new(DimConstraintAxis::Linear, "d1".into()); + assert!(matches!(command.on_enter(), CmdResult::NeedPoint)); + command.inject_picked_entity(EntityType::Line(Line::from_points( + Vector3::ZERO, + Vector3::new(100.0, 50.0, 0.0), + ))); + assert!(matches!( + command.on_entity_pick(Handle::new(7), DVec3::new(50.0, 25.0, 0.0)), + CmdResult::NeedPoint + )); + // Below the pair: horizontal, so the measured value is the X span. + let CmdResult::ReportMeasurement(text) = command.on_point(DVec3::new(50.0, -30.0, 0.0)) + else { + panic!("the location must report the dimension text"); + }; + assert_eq!(text, "Dimension text = 100.0000"); + assert_eq!( + command.prompt(), + "DCLINEAR Enter value or name and value :" + ); + let CmdResult::AddDimensionalConstraint { + kind, name, expression, .. + } = command.on_text_input("w=d1*2").expect("a value builds the constraint") + else { + panic!("the value must build the constraint"); + }; + assert_eq!(kind, ConstraintKind::DistanceX); + assert_eq!(name, "w"); + assert_eq!(expression, "d1*2"); + } + + #[test] + fn a_location_beside_the_pair_measures_vertically() { + let mut command = DimConstraintCommand::new(DimConstraintAxis::Linear, "d1".into()); + let first = ParametricRef::point(Handle::new(7), 0); + let second = ParametricRef::point(Handle::new(7), 1); + command.accept_constraint_point(first, DVec3::ZERO); + command.accept_constraint_point(second, DVec3::new(100.0, 50.0, 0.0)); + let CmdResult::ReportMeasurement(text) = command.on_point(DVec3::new(140.0, 25.0, 0.0)) + else { + panic!("the location must report the dimension text"); + }; + assert_eq!(text, "Dimension text = 50.0000"); + } +} diff --git a/src/modules/parametric/mod.rs b/src/modules/parametric/mod.rs index ebe13aa90..44ad59d44 100644 --- a/src/modules/parametric/mod.rs +++ b/src/modules/parametric/mod.rs @@ -4,6 +4,7 @@ mod coincident; mod concentric; +mod dim_constraint; mod constraint_bar; mod equal_distance; #[path = "equal.rs"] @@ -25,6 +26,7 @@ mod tools; mod value; pub use coincident::{coincident_tool, CoincidentConstraintCommand}; pub use concentric::ConcentricConstraintCommand; +pub use dim_constraint::{DimConstraintAxis, DimConstraintCommand}; pub use constraint_bar::ConstraintBarOptionCommand; pub use equal_command::EqualConstraintCommand; pub use equal_distance::{equal_distance_tool, EqualDistanceConstraintCommand}; diff --git a/src/scene/mod.rs b/src/scene/mod.rs index e2b373127..60821cba1 100644 --- a/src/scene/mod.rs +++ b/src/scene/mod.rs @@ -2295,6 +2295,9 @@ pub struct Scene { has_associative_centers: std::cell::Cell>, /// Runtime parametric constraint sets decoded from standard graph scopes. pub(crate) parametric_constraints: Vec, + /// CONSTRAINTNAMEFORMAT: what a dynamic dimension's text shows — + /// 0 the parameter name, 1 the value, 2 `name=value`. + pub constraint_name_format: u8, /// Session-only visibility overrides for constraint glyphs. hidden_parametric_constraints: HashSet<( parametric_constraints::ParametricScope, @@ -2625,6 +2628,7 @@ impl Scene { dependency_index_cache: RefCell::new(None), associative_hatch_source_cache: RefCell::new(None), parametric_constraints: Vec::new(), + constraint_name_format: 2, hidden_parametric_constraints: HashSet::default(), shown_parametric_constraints: HashSet::default(), named_parameters: named_parameters::ParameterTable::new(), @@ -3319,6 +3323,7 @@ impl Scene { } } if !self.parametric_constraints.is_empty() || !self.named_parameters.is_empty() { + self.refresh_dynamic_dimension_texts(); self.sync_native_parametric_graph(); } if !changes.is_empty() { diff --git a/src/scene/parametric_constraints.rs b/src/scene/parametric_constraints.rs index 0ab068550..4f9317a75 100644 --- a/src/scene/parametric_constraints.rs +++ b/src/scene/parametric_constraints.rs @@ -351,6 +351,37 @@ pub(crate) fn equal_size_follower( Some(entity) } +/// The first free `d1`, `d2`, … name a new dimensional constraint takes. +pub(crate) fn next_dimensional_parameter_name( + table: &super::named_parameters::ParameterTable, +) -> String { + (1..) + .map(|n| format!("d{n}")) + .find(|name| !table.contains(name)) + .unwrap_or_else(|| "d1".to_string()) +} + +/// The text a dynamic dimension shows: CONSTRAINTNAMEFORMAT 0 = name, +/// 1 = value, 2 = name=value. +pub(crate) fn dynamic_dimension_text(name: &str, value: f64, format: u8) -> String { + match format { + 0 => name.to_string(), + 1 => format!("{value:.4}"), + _ => format!("{name}={value:.4}"), + } +} + +/// The expression a measured value seeds a parameter with (`100`, `111.8034`). +pub(crate) fn measured_expression(value: f64) -> String { + let text = format!("{value:.4}"); + let text = text.trim_end_matches('0').trim_end_matches('.'); + if text.is_empty() || text == "-" { + "0".to_string() + } else { + text.to_string() + } +} + /// Grabbed points are exact kernel inputs; the solver anchors the remaining /// endpoint coordinates according to the line's directional constraints. pub(crate) fn grip_solve_anchor_refs( @@ -585,6 +616,8 @@ pub struct ParametricConstraintSet { /// parameter names may legitimately occur in different blocks. pub(crate) local_parameters: super::named_parameters::ParameterTable, pub(crate) retained_standard_groups: Vec, + /// The dynamic dimension that shows a dimensional constraint, by id. + pub(crate) dimensions: std::collections::HashMap, /// Cached total remaining degrees of freedom, summed across every /// independent solve partition in this scope — updated by /// `parametric_solve::solve_scope` each time this set is resolved. `None` @@ -611,6 +644,7 @@ impl ParametricConstraintSet { next_id: 0, local_parameters: super::named_parameters::ParameterTable::new(), retained_standard_groups: Vec::new(), + dimensions: std::collections::HashMap::new(), dof: None, conflicts: Vec::new(), } @@ -702,6 +736,7 @@ impl ParametricConstraintSet { /// Removes a constraint by id. Returns whether one was actually removed. pub fn remove(&mut self, id: ConstraintId) -> bool { + self.dimensions.remove(&id); let before = self.constraints.len(); self.constraints.retain(|c| c.id != id); self.constraints.len() != before @@ -1420,6 +1455,49 @@ impl super::Scene { !self.hidden_parametric_constraints.contains(&(scope, id)) } + /// Rewrites every dynamic dimension's text from its constraint's + /// parameter name and current value, in the CONSTRAINTNAMEFORMAT + /// reading `constraint_name_format` selects. + pub(crate) fn refresh_dynamic_dimension_texts(&mut self) { + let format = self.constraint_name_format; + let mut updates: Vec<(Handle, String)> = Vec::new(); + for set in &self.parametric_constraints { + let table = if set.local_parameters.is_empty() { + &self.named_parameters + } else { + &set.local_parameters + }; + for (id, dimension) in &set.dimensions { + let Some(constraint) = set.get(*id) else { + continue; + }; + let (name, value) = match &constraint.driving_param { + Some(DrivingValue::Named(name)) => { + (name.clone(), table.resolve(name).unwrap_or(f64::NAN)) + } + Some(DrivingValue::Literal(value)) => (String::new(), *value), + None => continue, + }; + updates.push((*dimension, dynamic_dimension_text(&name, value, format))); + } + } + for (handle, text) in updates { + let Some(acadrust::EntityType::Dimension(mut dimension)) = + self.document.get_entity(handle).cloned() + else { + continue; + }; + if dimension.base().user_text.as_deref() == Some(text.as_str()) { + continue; + } + crate::entities::dimension::set_dimension_text_override( + dimension.base_mut(), + Some(text), + ); + self.update_entity(acadrust::EntityType::Dimension(dimension)); + } + } + pub fn should_display_parametric_constraint( &self, scope: ParametricScope, @@ -1861,7 +1939,8 @@ impl super::Scene { }; set.constraints .iter() - .filter(|c| c.enabled) + // A dynamic dimension is its constraint's whole display. + .filter(|c| c.enabled && !set.dimensions.contains_key(&c.id)) .filter(|c| { let selected = c .refs