Merge pull request #1415 from ramox81/codex/aligned-constraint-parity

Aligned dimensional constraint: Point & line, 2Lines, value and property parity

# Conflicts:
#	src/app/command_driver.rs
#	src/app/update/viewport.rs
#	src/entities/dimension.rs
#	src/scene/parametric_constraints.rs
This commit is contained in:
Hakan Seven committed 2026-09-21 22:41:42 +03:00
commit 7490b2bebd
12 files changed
+1292 -167

No files matched your search

+18 -3
View File
@@ -1217,6 +1217,7 @@ impl Allocator<'_> {
name: &str,
formula: &str,
resolved: f64,
description: &str,
) -> Handle {
if let Some(&handle) = self.variables.get(name) {
if let Some(ObjectType::Associative(object)) = self.document.objects.get_mut(&handle) {
@@ -1244,7 +1245,7 @@ impl Allocator<'_> {
name: name.to_string(),
expression: formula.to_string(),
evaluator: "AcDbCalc:1.0".to_string(),
description: String::new(),
description: description.to_string(),
value: Self::numeric_eval(resolved),
has_cached_value: false,
cached_value: String::new(),
@@ -1883,6 +1884,7 @@ fn driving_value(
variable.expression.clone()
};
if parameters.set(&variable.name, &source).is_ok() {
parameters.set_description(&variable.name, &variable.description);
Some(DrivingValue::Named(variable.name.clone()))
} else {
literal
@@ -2610,6 +2612,7 @@ fn materialize_scope(
variable.action.action_index = index as i32 + 1;
if let Some(parameter) = parameters.get(&variable.name) {
variable.expression = parameter.source.clone();
variable.description = parameters.description(&parameter.name).to_string();
if let Ok(resolved) = parameters.resolve(&parameter.name) {
variable.value = Allocator::numeric_eval(resolved);
}
@@ -2621,7 +2624,13 @@ fn materialize_scope(
if materialize_all_parameters {
for parameter in parameters.iter() {
let resolved = parameters.resolve(&parameter.name).unwrap_or(0.0);
allocator.variable(network_handle, &parameter.name, &parameter.source, resolved);
allocator.variable(
network_handle,
&parameter.name,
&parameter.source,
resolved,
parameters.description(&parameter.name),
);
}
}
@@ -2666,7 +2675,13 @@ fn materialize_scope(
DrivingValue::Literal(_) => (format!("d{node_id}"), resolved.to_string()),
};
node_names.insert(node_id, name.clone());
let variable_handle = allocator.variable(network_handle, &name, &formula, resolved);
let variable_handle = allocator.variable(
network_handle,
&name,
&formula,
resolved,
parameters.description(&name),
);
let dependency_id = group_dependencies.len() as i32 + 1;
let dep_handle =
allocator.value_dependency(group_handle?, variable_handle, resolved, dependency_id);
+21
View File
@@ -474,6 +474,9 @@ pub struct Parameter {
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ParameterTable {
parameters: Vec<Parameter>,
/// The free-text description a parameter carries (the reference's
/// Description column), by name.
descriptions: HashMap<String, String>,
}
impl ParameterTable {
@@ -481,6 +484,23 @@ impl ParameterTable {
Self::default()
}
pub fn description(&self, name: &str) -> &str {
self.descriptions.get(name).map_or("", String::as_str)
}
/// Stores `description` for an existing parameter; an empty text clears it.
pub fn set_description(&mut self, name: &str, description: &str) {
if !self.contains(name) {
return;
}
if description.trim().is_empty() {
self.descriptions.remove(name);
} else {
self.descriptions
.insert(name.to_string(), description.trim().to_string());
}
}
pub fn is_empty(&self) -> bool {
self.parameters.is_empty()
}
@@ -549,6 +569,7 @@ impl ParameterTable {
/// need to invent (a future UI stage may still want to warn before
/// deleting — that's a UI-layer decision, not a data-layer one).
pub fn remove(&mut self, name: &str) -> bool {
self.descriptions.remove(name);
match self.index_of(name) {
Some(i) => {
self.parameters.remove(i);
+276 -68
View File
@@ -367,41 +367,197 @@ pub const DYNAMIC_DIMENSION_GLYPH: &str = "\u{1F512}";
/// The on-screen text height of a dynamic dimension, in pixels.
pub const DYNAMIC_DIMENSION_TEXT_PX: f32 = 12.0;
/// The xdata application that marks an annotational constraint dimension.
pub const ANNOTATIONAL_DIMENSION_APP: &str = "OCS_CONSTRAINT_FORM";
/// The layer the reference keeps dynamic dimensions on; an annotational
/// dimensional constraint sits on an ordinary layer instead.
pub(crate) const DYNAMIC_DIMENSION_LAYER: &str = "*ADSK_CONSTRAINTS";
/// The text a dynamic dimension shows: CONSTRAINTNAMEFORMAT 0 = name,
/// 1 = value, 2 = name=value. A plain number shows as typed (`d1=100`); an
/// expression shows the expression under the reference's `fx:` prefix
/// (`fx: d2=d1*2`).
pub(crate) fn dynamic_dimension_text(name: &str, source: &str, value: f64, format: u8) -> String {
let source = source.trim();
let literal = source.parse::<f64>().is_ok();
let shown = if literal {
source.to_string()
} else {
measured_expression(value)
/// 1 = value, 2 = name=value, the value with its trailing zeros dropped
/// (`d9=80`, `d1=111.8034`). A parameter defined by a formula shows the
/// formula behind `fx:` (`fx: len=d1*2`); a reference (driven) constraint's
/// text sits in parentheses; an annotational one keeps dimension precision.
pub(crate) fn dynamic_dimension_text(
name: &str,
value: f64,
format: u8,
reference: bool,
expression: Option<&str>,
annotational: bool,
) -> String {
let formula = expression
.map(str::trim)
.filter(|source| !source.is_empty() && source.parse::<f64>().is_err());
let shown = match formula {
Some(source) => source.to_string(),
// An annotational dimension shows the value at dimension precision
// (`d1=100.0000`), as the reference does.
None if annotational => format!("{value:.4}"),
None => {
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()
}
}
};
match format {
let text = match format {
0 => name.to_string(),
1 if literal => shown,
1 => format!("fx: {shown}"),
_ if literal => format!("{name}={shown}"),
_ => format!("fx: {name}={source}"),
1 => shown,
_ => format!("{name}={shown}"),
};
let text = if formula.is_some() {
format!("fx: {text}")
} else {
text
};
if reference {
format!("({text})")
} else {
text
}
}
/// The expression a measured value seeds a parameter with (`100`, `111.8034`).
/// The expression a measured value seeds a parameter with: twelve
/// significant digits with the trailing zeros dropped (`100`,
/// `111.803398875`), as the reference stores it.
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 == "-" {
if !value.is_finite() {
return "0".to_string();
}
// Solver noise (24.9999999047) reads as the round value it means.
let snapped = (value * 1.0e4).round() / 1.0e4;
let value = if (value - snapped).abs() < 1.0e-6 {
snapped
} else {
value
};
let magnitude = value.abs();
let integer_digits = if magnitude < 1.0 {
1
} else {
magnitude.log10().floor() as i32 + 1
};
let decimals = (12 - integer_digits).clamp(0, 12) as usize;
let text = format!("{value:.decimals$}");
let text = if text.contains('.') {
text.trim_end_matches('0').trim_end_matches('.')
} else {
text.as_str()
};
if text.is_empty() || text == "-" || text == "-0" {
"0".to_string()
} else {
text.to_string()
}
}
/// Moves a dynamic dimension's extension origins to `first`/`second`,
/// keeping its dimension line where it was; true when anything moved.
fn dynamic_dimension_follow_points(
dimension: &mut acadrust::entities::Dimension,
first: Vector3,
second: Vector3,
) -> bool {
use acadrust::entities::Dimension;
let same = |a: Vector3, b: Vector3| (a - b).length_squared() < 1.0e-16;
let to_dvec = |p: Vector3| glam::DVec3::new(p.x, p.y, p.z);
let (current_first, current_second, definition, axis) = match dimension {
Dimension::Aligned(d) => (d.first_point, d.second_point, d.definition_point, None),
Dimension::Linear(d) => (
d.first_point,
d.second_point,
d.definition_point,
Some(glam::DVec3::new(d.rotation.cos(), d.rotation.sin(), 0.0)),
),
_ => return false,
};
if same(current_first, first) && same(current_second, second) {
return false;
}
let text = dimension.base().user_text.clone();
let rebuilt = match axis {
None => crate::modules::annotate::aligned_dim::aligned_dimension_entity(
to_dvec(first),
to_dvec(second),
to_dvec(definition),
text,
),
Some(axis) => crate::modules::annotate::linear_dim::linear_dimension_entity(
to_dvec(first),
to_dvec(second),
to_dvec(definition),
axis,
text,
),
};
let acadrust::EntityType::Dimension(mut rebuilt) = rebuilt else {
return false;
};
// Everything but the geometry stays: identity, layer, color, style, xdata.
let base = dimension.base();
let target = rebuilt.base_mut();
target.common = base.common.clone();
target.style_name = base.style_name.clone();
target.text_rotation = base.text_rotation;
target.attachment_point = base.attachment_point;
target.line_spacing_style = base.line_spacing_style;
target.line_spacing_factor = base.line_spacing_factor;
*dimension = rebuilt;
true
}
/// What stays put when a dimensional constraint's value changes: its first
/// point, and — when the distance runs perpendicular to a line that owns
/// that point (2Lines, line-first Point & line) — the whole line, so the
/// other object moves, as in the reference.
pub(crate) fn dimensional_anchor_refs(
document: &acadrust::CadDocument,
refs: &[ParametricRef],
) -> Vec<ParametricRef> {
let Some(&first) = refs.first() else {
return Vec::new();
};
let mut anchors = vec![first];
if let Some(&line) = refs.get(2).filter(|line| line.entity == first.entity) {
let ends = match line.segment_index() {
Some(index) => {
let index = index as i32;
let end = document
.get_entity(line.entity)
.and_then(|entity| resolve_point(entity, index + 1))
.map_or(0, |_| index + 1);
[
ParametricRef::point(line.entity, index),
ParametricRef::point(line.entity, end),
]
}
None => [
ParametricRef::point(line.entity, 0),
ParametricRef::point(line.entity, 1),
],
};
anchors.extend(ends.into_iter().filter(|end| *end != first));
}
anchors
}
/// The constraint a dynamic dimension shows, with the table its parameter
/// lives in.
pub(crate) fn dynamic_dimension_constraint(
sets: &[ParametricConstraintSet],
handle: Handle,
) -> Option<(&ParametricConstraintSet, &ParametricConstraint)> {
sets.iter().find_map(|set| {
let id = set
.dimensions
.iter()
.find_map(|(id, dimension)| (*dimension == handle).then_some(*id))?;
Some((set, set.get(id)?))
})
}
/// 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(
@@ -1477,12 +1633,16 @@ impl super::Scene {
/// Rewrites every dynamic dimension's text from its constraint's
/// parameter name and current value, in the CONSTRAINTNAMEFORMAT
/// reading `constraint_name_format` selects.
/// reading `constraint_name_format` selects, and moves its extension
/// origins to where the solve left the constraint points.
pub(crate) fn refresh_dynamic_dimension_texts(&mut self) {
let format = self.constraint_name_format;
let mut updates: Vec<(Handle, String)> = Vec::new();
let mut updates: Vec<(Handle, String, Option<(Vector3, Vector3)>)> = Vec::new();
// A reference (driven) constraint's parameter follows the geometry.
let mut followed: Vec<(String, f64)> = Vec::new();
for set in &self.parametric_constraints {
let table = if set.local_parameters.is_empty() {
let model_table = set.local_parameters.is_empty();
let table = if model_table {
&self.named_parameters
} else {
&set.local_parameters
@@ -1491,47 +1651,94 @@ impl super::Scene {
let Some(constraint) = set.get(*id) else {
continue;
};
let (name, source, value) = match &constraint.driving_param {
Some(DrivingValue::Named(name)) => (
name.clone(),
table
.get(name)
.map(|parameter| parameter.source.clone())
.unwrap_or_default(),
table.resolve(name).unwrap_or(f64::NAN),
),
Some(DrivingValue::Literal(value)) => {
(String::new(), measured_expression(*value), *value)
let world = |reference: &ParametricRef| {
let entity = self.document.get_entity(reference.entity)?;
resolve_point(entity, reference.marker?)
};
let points = match constraint.refs.as_slice() {
[first, second, ..] => world(first).zip(world(second)),
_ => None,
};
let reference = !constraint.enabled;
let measured = points.map(|(first, second)| {
let delta = second - first;
let axis = match self.document.get_entity(*dimension) {
Some(acadrust::EntityType::Dimension(
acadrust::entities::Dimension::Linear(linear),
)) => Some((linear.rotation.cos(), linear.rotation.sin())),
_ => None,
};
match (constraint.kind, axis) {
(ConstraintKind::DistanceX, _) => delta.x.abs(),
(ConstraintKind::DistanceY, _) => delta.y.abs(),
(ConstraintKind::DistanceDirected, Some((ax, ay))) => {
(delta.x * ax + delta.y * ay).abs()
}
_ => delta.length(),
}
});
let (name, value, source) = match &constraint.driving_param {
Some(DrivingValue::Named(name)) => {
let value = match (reference, measured) {
(true, Some(measured)) => {
if model_table {
followed.push((name.clone(), measured));
}
measured
}
_ => table.resolve(name).unwrap_or(f64::NAN),
};
let source = (!reference)
.then(|| table.get(name).map(|parameter| parameter.source.clone()))
.flatten();
(name.clone(), value, source)
}
Some(DrivingValue::Literal(value)) => (String::new(), *value, None),
None => continue,
};
// An annotational dimension shows the value at dimension
// precision, as the reference does.
let source = if self.dimension_is_annotational(*dimension) {
format!("{value:.4}")
} else {
source
};
let annotational = self.dimension_is_annotational(*dimension);
updates.push((
*dimension,
dynamic_dimension_text(&name, &source, value, format),
dynamic_dimension_text(
&name,
value,
format,
reference,
source.as_deref(),
annotational,
),
points,
));
}
}
for (handle, text) in updates {
for (name, measured) in followed {
let source = measured_expression(measured);
if self.named_parameters.get(&name).map(|p| p.source.as_str()) != Some(source.as_str()) {
let _ = self.named_parameters.set(&name, &source);
}
}
for (handle, text, points) 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;
let mut changed = false;
if let Some((first, second)) = points {
if dynamic_dimension_follow_points(&mut dimension, first, second) {
changed = true;
}
}
if dimension.base().user_text.as_deref() != Some(text.as_str()) {
crate::entities::dimension::set_dimension_text_override(
dimension.base_mut(),
Some(text),
);
changed = true;
}
if changed {
self.update_entity(acadrust::EntityType::Dimension(dimension));
}
crate::entities::dimension::set_dimension_text_override(
dimension.base_mut(),
Some(text),
);
self.update_entity(acadrust::EntityType::Dimension(dimension));
}
}
@@ -1602,6 +1809,19 @@ impl super::Scene {
ids.len()
}
/// Makes sure the reference's dynamic dimension layer exists: hidden
/// from the layer lists (the `*` prefix) and never plotted.
pub(crate) fn ensure_dynamic_dimension_layer(&mut self) {
if self.document.layers.contains(DYNAMIC_DIMENSION_LAYER) {
return;
}
let mut layer = acadrust::tables::Layer::new(DYNAMIC_DIMENSION_LAYER);
layer.color = acadrust::types::Color::from_index(7);
layer.is_plottable = false;
layer.handle = self.document.allocate_handle();
let _ = self.document.layers.add(layer);
}
/// True for a dynamic dimension of a dimensional constraint (not an
/// annotational one, which is an ordinary plotted dimension).
pub(crate) fn is_dynamic_dimension(&self, handle: Handle) -> bool {
@@ -1612,29 +1832,17 @@ impl super::Scene {
}
/// True when a dimensional constraint's dimension uses the annotational
/// form: drawn with its style, plotted, never rescaled to the screen.
/// form: on an ordinary layer instead of the reference's constraints
/// layer, drawn with its style, plotted, never rescaled to the screen.
pub(crate) fn dimension_is_annotational(&self, handle: Handle) -> bool {
self.document.get_entity(handle).is_some_and(|entity| {
entity
!entity
.common()
.extended_data
.get_record(ANNOTATIONAL_DIMENSION_APP)
.is_some()
.layer
.eq_ignore_ascii_case(DYNAMIC_DIMENSION_LAYER)
})
}
/// Marks a constraint dimension as annotational (DCFORM Annotational).
pub(crate) fn mark_dimension_annotational(&mut self, handle: Handle) {
crate::scene::view::dispatch::set_entity_xdata(
&mut self.document,
handle,
ANNOTATIONAL_DIMENSION_APP,
Some(vec![acadrust::xdata::XDataValue::String(
"ANNOTATIONAL".to_string(),
)]),
);
}
/// The document as written to a file: a dynamic dimension's screen-size
/// overrides are a display matter and stay out of the file.
pub(crate) fn document_for_save(&self) -> acadrust::CadDocument {
+42 -6
View File
@@ -993,9 +993,15 @@ fn resolved_target(params: &ParameterTable, constraint: &ParametricConstraint) -
if !value.is_finite() {
return None;
}
// A dimensional distance keeps its sign in the parameter but measures
// its magnitude, as the reference does (`d1=-50` shortens the line to
// 50; `0` folds the points together).
if constraint.kind == ConstraintKind::Distance {
return Some(value.abs());
}
let must_be_positive = matches!(
constraint.kind,
ConstraintKind::Distance | ConstraintKind::Radius | ConstraintKind::Diameter
ConstraintKind::Radius | ConstraintKind::Diameter
);
(!must_be_positive || value > 0.0).then_some(value)
}
@@ -1592,6 +1598,14 @@ fn build_constraint(
let Some(resolved) = resolved_target(params, c) else {
return Vec::new();
};
// A zero distance folds the points together; the distance
// residual has no gradient there, the coordinate equalities do.
if resolved.abs() <= f64::EPSILON {
return vec![
Rc::new(Equal::new(pa.x, pb.x, 1.0)),
Rc::new(Equal::new(pa.y, pb.y, 1.0)),
];
}
let target = sys.add_param(resolved, true);
vec![Rc::new(P2PDistance::new(pa, pb, target))]
}
@@ -1613,10 +1627,13 @@ fn build_constraint(
distance_direction_type::PARALLEL_TO_LINE
| distance_direction_type::PERPENDICULAR_TO_LINE
) {
if let Some(line) = direction_ref
.first()
.and_then(|reference| whole_line(sys, cache, *reference))
{
if let Some(line) = direction_ref.first().and_then(|reference| {
// A text baseline or an ellipse axis directs the
// distance the same way a line does.
whole_line(sys, cache, *reference).or_else(|| {
directional_line(sys, cache, *reference).map(|(line, _)| line)
})
}) {
let current = {
let store = sys.store();
let delta = [
@@ -3812,6 +3829,24 @@ impl Scene {
self.parametric_constraints[i].dof = None;
self.parametric_constraints[i].conflicts.clear();
}
// A dimensional constraint set to zero means the collapse.
let zero_collapse: HashSet<Handle> = {
let set = &self.parametric_constraints[i];
let params = if set.local_parameters.is_empty() {
&self.named_parameters
} else {
&set.local_parameters
};
set.constraints
.iter()
.filter(|c| {
c.enabled
&& c.kind == ConstraintKind::Distance
&& resolved_target(params, c).is_some_and(|v| v.abs() <= f64::EPSILON)
})
.flat_map(|c| c.refs.iter().map(|r| r.entity))
.collect()
};
for (handle, new_entity) in solved {
// An edit the constraints can only satisfy by collapsing the
// entity (a rotated line whose start is fixed and direction
@@ -3820,7 +3855,8 @@ impl Scene {
let new_entity = match originals.get(&handle) {
Some(original)
if collapsed_by_solve(&new_entity)
&& !collapsed_by_solve(original.as_ref()) =>
&& !collapsed_by_solve(original.as_ref())
&& !zero_collapse.contains(&handle) =>
{
original.as_ref().clone()
}