From e93815d0c52329c3a04dbfa675c75d2a2759b230 Mon Sep 17 00:00:00 2001 From: ramox81 <184937705+ramox81@users.noreply.github.com> Date: Tue, 25 Aug 2026 11:29:38 +0300 Subject: [PATCH 1/5] Complete angular dimension creation and associations --- src/app/command_driver.rs | 21 +- src/command.rs | 4 +- src/modules/annotate/angular_dim.rs | 691 +++++++++++++++++++++++----- src/modules/annotate/linear_dim.rs | 5 +- src/scene/dimension_assoc.rs | 171 +++++-- 5 files changed, 744 insertions(+), 148 deletions(-) diff --git a/src/app/command_driver.rs b/src/app/command_driver.rs index bf03b591f..1bff0d720 100644 --- a/src/app/command_driver.rs +++ b/src/app/command_driver.rs @@ -1229,17 +1229,24 @@ impl OpenCADStudio { self.commit_undo_delta(i, pd); } } - CmdResult::CommitAssociativeDimension { entity, source } => { - let label = self.history_label_from_active_cmd(i, "DIMLINEAR"); + CmdResult::CommitAssociativeDimension { entity, sources } => { + let label = self.history_label_from_active_cmd(i, "DIMENSION"); let pending = self.begin_undo(i, label, 1, false); if let Some(handle) = self.commit_entity_handle(entity) { self.tabs[i] .scene - .attach_linear_dimension_association(handle, [Some(source), Some(source)]); - self.tabs[i].scene.bump_entities(&[ - (handle, crate::scene::ChangeKind::Modified), - (source, crate::scene::ChangeKind::Modified), - ]); + .attach_dimension_association( + handle, + sources.iter().copied().map(Some).collect(), + ); + let mut changed = vec![(handle, crate::scene::ChangeKind::Modified)]; + changed.extend( + sources + .iter() + .copied() + .map(|source| (source, crate::scene::ChangeKind::Modified)), + ); + self.tabs[i].scene.bump_entities(&changed); } self.tabs[i].dirty = true; self.tabs[i].scene.clear_preview_wire(); diff --git a/src/command.rs b/src/command.rs index 89b8d0382..b8dbdb6fc 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1212,10 +1212,10 @@ pub enum CmdResult { CommitEntitiesAndExit(Vec), /// Commit an acadrust entity to the document and end the command. CommitAndExit(EntityType), - /// Commit an object-selected linear dimension and retain its source link. + /// Commit an object-selected dimension and retain its source links. CommitAssociativeDimension { entity: EntityType, - source: Handle, + sources: Vec, }, /// Commit a Model-tab 3D solid: the acadrust entity (for selection / /// persistence) plus its B-rep (cached for boolean ops + shaded diff --git a/src/modules/annotate/angular_dim.rs b/src/modules/annotate/angular_dim.rs index 36a917e45..d6e9edf97 100644 --- a/src/modules/annotate/angular_dim.rs +++ b/src/modules/annotate/angular_dim.rs @@ -1,12 +1,12 @@ -use acadrust::entities::{Dimension, DimensionAngular3Pt}; -use acadrust::types::Vector3; +use acadrust::entities::{Dimension, DimensionAngular2Ln, DimensionAngular3Pt}; +use acadrust::types::{Handle, Vector3}; use acadrust::EntityType; use crate::command::{CadCommand, CmdResult, WorkingPlane}; use crate::modules::{IconKind, ModuleEvent, ToolDef}; use crate::scene::model::wire_model::WireModel; -use glam::{DVec3, Vec3}; use crate::t; +use glam::DVec3; pub const ICON: IconKind = IconKind::Svg(include_bytes!("../../../assets/icons/dim_angular.svg")); @@ -22,20 +22,55 @@ pub fn tool() -> ToolDef { enum Step { Vertex, FirstRay(DVec3), - SecondRay { + SecondRay { vertex: DVec3, first: DVec3 }, + CircleSecondRay { vertex: DVec3, first: DVec3, + radius: f64, + source: Handle, }, - ArcPoint { + SecondLine { + first_start: DVec3, + first_end: DVec3, + first_source: Handle, + }, + ArcPoint3 { vertex: DVec3, first: DVec3, second: DVec3, }, + ArcPoint2 { + first_start: DVec3, + first_end: DVec3, + second_start: DVec3, + second_end: DVec3, + }, +} + +enum PickedCurve { + Line(DVec3, DVec3), + Arc { + center: DVec3, + first: DVec3, + second: DVec3, + }, + Circle { + center: DVec3, + radius: f64, + }, } pub struct AngularDimensionCommand { step: Step, plane: WorkingPlane, + selecting_object: bool, + picked_entity: Option, + source_handles: Vec, + text_override: Option, + awaiting_text: bool, + mtext_override: bool, + text_angle: Option, + awaiting_angle: bool, } impl AngularDimensionCommand { @@ -43,8 +78,92 @@ impl AngularDimensionCommand { Self { step: Step::Vertex, plane: WorkingPlane::default(), + selecting_object: false, + picked_entity: None, + source_handles: Vec::new(), + text_override: None, + awaiting_text: false, + mtext_override: false, + text_angle: None, + awaiting_angle: false, } } + + fn finish_three_point( + &self, + vertex: DVec3, + first: DVec3, + second: DVec3, + arc_point: DVec3, + ) -> CmdResult { + let vertex = self.plane.to_local(vertex); + let first = self.plane.to_local(first); + let second = self.plane.to_local(second); + let arc_point = self.plane.to_local(arc_point); + let mut dim = DimensionAngular3Pt::new(v3(vertex), v3(first), v3(second)); + dim.definition_point = v3(arc_point); + dim.base.definition_point = dim.definition_point; + dim.base.text_middle_point = dim.definition_point; + dim.base.insertion_point = dim.definition_point; + dim.base.actual_measurement = dim.measurement_degrees(); + crate::entities::dimension::set_dimension_text_override( + &mut dim.base, + self.text_override.clone(), + ); + if let Some(angle) = self.text_angle { + dim.base.text_rotation = angle; + } + self.commit(Dimension::Angular3Pt(dim)) + } + + fn finish_two_line( + &self, + first_start: DVec3, + first_end: DVec3, + second_start: DVec3, + second_end: DVec3, + arc_point: DVec3, + ) -> CmdResult { + let first_start = self.plane.to_local(first_start); + let first_end = self.plane.to_local(first_end); + let second_start = self.plane.to_local(second_start); + let second_end = self.plane.to_local(second_end); + let arc_point = self.plane.to_local(arc_point); + let mut dim = DimensionAngular2Ln::default(); + dim.first_point = v3(first_start); + dim.second_point = v3(first_end); + dim.angle_vertex = v3(second_start); + dim.definition_point = v3(second_end); + dim.dimension_arc = v3(arc_point); + dim.base.definition_point = dim.dimension_arc; + dim.base.text_middle_point = dim.dimension_arc; + dim.base.insertion_point = dim.dimension_arc; + dim.base.actual_measurement = dim.measurement_degrees(); + crate::entities::dimension::set_dimension_text_override( + &mut dim.base, + self.text_override.clone(), + ); + if let Some(angle) = self.text_angle { + dim.base.text_rotation = angle; + } + self.commit(Dimension::Angular2Ln(dim)) + } + + fn commit(&self, dimension: Dimension) -> CmdResult { + let entity = self.plane.place_entity(EntityType::Dimension(dimension)); + if self.source_handles.is_empty() { + CmdResult::CommitAndExit(entity) + } else { + CmdResult::CommitAssociativeDimension { + entity, + sources: self.source_handles.clone(), + } + } + } + + fn placement_step(&self) -> bool { + matches!(self.step, Step::ArcPoint3 { .. } | Step::ArcPoint2 { .. }) + } } impl CadCommand for AngularDimensionCommand { @@ -57,59 +176,102 @@ impl CadCommand for AngularDimensionCommand { } fn prompt(&self) -> String { + if self.awaiting_text { + return if self.mtext_override { + t!("DIMANGULAR Enter formatted dimension text (blank = measured value):") + .into_owned() + } else { + t!("DIMANGULAR Enter dimension text (blank = measured value):").into_owned() + }; + } + if self.awaiting_angle { + return t!("DIMANGULAR Specify text angle (degrees):").into_owned(); + } + if self.selecting_object { + return match self.step { + Step::SecondLine { .. } => t!("DIMANGULAR Select second line:").into_owned(), + _ => t!("DIMANGULAR Select arc, circle, line, or polyline arc:").into_owned(), + }; + } match self.step { - Step::Vertex => t!("DIMANGULAR Specify angle vertex:").into_owned(), + Step::Vertex => t!( + "DIMANGULAR Specify angle vertex or press Enter to select an object:" + ) + .into_owned(), Step::FirstRay(_) => { t!("DIMANGULAR Specify first extension line point:").into_owned() } - Step::SecondRay { .. } => { + Step::SecondRay { .. } | Step::CircleSecondRay { .. } => { t!("DIMANGULAR Specify second extension line point:").into_owned() } - Step::ArcPoint { .. } => t!("DIMANGULAR Specify dimension arc location:").into_owned(), + Step::SecondLine { .. } => t!("DIMANGULAR Select second line:").into_owned(), + Step::ArcPoint3 { .. } | Step::ArcPoint2 { .. } => t!( + "DIMANGULAR Specify dimension arc location [Mtext/Text/Angle/Quadrant]:" + ) + .into_owned(), } } - fn on_point(&mut self, pt: DVec3) -> CmdResult { + fn on_point(&mut self, point: DVec3) -> CmdResult { match self.step { Step::Vertex => { - self.step = Step::FirstRay(pt); + self.step = Step::FirstRay(point); CmdResult::NeedPoint } Step::FirstRay(vertex) => { - self.step = Step::SecondRay { vertex, first: pt }; + if point.distance_squared(vertex) <= 1.0e-24 { + return CmdResult::NeedPoint; + } + self.step = Step::SecondRay { vertex, first: point }; CmdResult::NeedPoint } Step::SecondRay { vertex, first } => { - self.step = Step::ArcPoint { - vertex, - first, - second: pt, - }; + if point.distance_squared(vertex) <= 1.0e-24 { + return CmdResult::NeedPoint; + } + self.step = Step::ArcPoint3 { vertex, first, second: point }; CmdResult::NeedPoint } - Step::ArcPoint { - vertex, - first, - second, - } => { - let vertex = self.plane.to_local(vertex); - let first = self.plane.to_local(first); - let second = self.plane.to_local(second); - let pt = self.plane.to_local(pt); - let mut dim = DimensionAngular3Pt::new(v3(vertex), v3(first), v3(second)); - dim.definition_point = v3(pt); - dim.base.definition_point = v3(pt); - dim.base.text_middle_point = v3(pt); - dim.base.insertion_point = v3(pt); - dim.base.actual_measurement = dim.measurement_degrees(); - CmdResult::CommitAndExit(self.plane.place_entity(EntityType::Dimension( - Dimension::Angular3Pt(dim), - ))) + Step::CircleSecondRay { vertex, first, radius, source } => { + let Some(second) = project_to_radius(vertex, point, radius) else { + return CmdResult::NeedPoint; + }; + self.source_handles = vec![source, source, source]; + self.step = Step::ArcPoint3 { vertex, first, second }; + CmdResult::NeedPoint } + Step::SecondLine { .. } => CmdResult::NeedPoint, + Step::ArcPoint3 { vertex, first, second } => { + self.finish_three_point(vertex, first, second, point) + } + Step::ArcPoint2 { + first_start, + first_end, + second_start, + second_end, + } => self.finish_two_line( + first_start, + first_end, + second_start, + second_end, + point, + ), } } fn on_enter(&mut self) -> CmdResult { + if self.awaiting_text { + self.awaiting_text = false; + return CmdResult::NeedPoint; + } + if self.awaiting_angle { + self.awaiting_angle = false; + return CmdResult::NeedPoint; + } + if matches!(self.step, Step::Vertex) { + self.selecting_object = true; + return CmdResult::NeedPoint; + } CmdResult::Cancel } @@ -117,49 +279,392 @@ impl CadCommand for AngularDimensionCommand { CmdResult::Cancel } - fn on_mouse_move(&mut self, pt: DVec3) -> Option { - let pt = pt.as_vec3(); - match self.step { - Step::Vertex => None, - Step::FirstRay(vertex) => Some(preview_wire(vec![vertex.as_vec3(), pt])), - Step::SecondRay { vertex, first } => Some(preview_wire(vec![ - vertex.as_vec3(), - first.as_vec3(), - Vec3::new(f32::NAN, f32::NAN, f32::NAN), - vertex.as_vec3(), - pt, - ])), - Step::ArcPoint { - vertex, - first, - second, - } => { - let points = angular_preview( - self.plane.to_local(vertex).as_vec3(), - self.plane.to_local(first).as_vec3(), - self.plane.to_local(second).as_vec3(), - self.plane.to_local(pt.as_dvec3()).as_vec3(), - ) - .into_iter() - .map(|point| { - if point.x.is_nan() { - point - } else { - self.plane.to_world(point.as_dvec3()).as_vec3() - } - }) - .collect(); - Some(preview_wire(points)) - } + fn wants_text_input(&self) -> bool { + true + } + + fn wants_text_with_spaces(&self) -> bool { + self.awaiting_text + } + + fn point_step_accepts_keywords(&self) -> bool { + self.placement_step() && !self.awaiting_text && !self.awaiting_angle + } + + fn on_text_input(&mut self, text: &str) -> Option { + if self.awaiting_text { + let value = text.trim(); + self.text_override = if value.is_empty() || value == "<>" { + None + } else { + Some(value.to_string()) + }; + self.awaiting_text = false; + return Some(CmdResult::NeedPoint); } + if self.awaiting_angle { + self.text_angle = if text.trim().is_empty() { + None + } else { + crate::entities::common::parse_typed_angle(text.trim()) + }; + self.awaiting_angle = false; + return Some(CmdResult::NeedPoint); + } + if !self.placement_step() { + return None; + } + match text.trim().to_ascii_uppercase().as_str() { + "T" | "TEXT" => { + self.mtext_override = false; + self.awaiting_text = true; + Some(CmdResult::NeedPoint) + } + "M" | "MTEXT" => { + self.mtext_override = true; + self.awaiting_text = true; + Some(CmdResult::NeedPoint) + } + "A" | "ANGLE" => { + self.awaiting_angle = true; + Some(CmdResult::NeedPoint) + } + "Q" | "QUADRANT" => Some(CmdResult::NeedPoint), + _ => None, + } + } + + fn needs_entity_pick(&self) -> bool { + self.selecting_object + } + + 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 { + if handle.is_null() { + return CmdResult::NeedPoint; + } + let Some(entity) = self.picked_entity.take() else { + return CmdResult::NeedPoint; + }; + let Some(curve) = picked_curve(&entity, point) else { + return CmdResult::NeedPoint; + }; + + match (&self.step, curve) { + ( + Step::SecondLine { first_start, first_end, first_source }, + PickedCurve::Line(second_start, second_end), + ) if *first_source != handle => { + self.source_handles = vec![*first_source, *first_source, handle, handle]; + self.selecting_object = false; + self.step = Step::ArcPoint2 { + first_start: *first_start, + first_end: *first_end, + second_start, + second_end, + }; + CmdResult::NeedPoint + } + (Step::Vertex, PickedCurve::Line(first_start, first_end)) => { + self.step = Step::SecondLine { + first_start, + first_end, + first_source: handle, + }; + CmdResult::NeedPoint + } + (Step::Vertex, PickedCurve::Arc { center, first, second }) => { + self.source_handles = vec![handle, handle, handle]; + self.selecting_object = false; + self.step = Step::ArcPoint3 { vertex: center, first, second }; + CmdResult::NeedPoint + } + (Step::Vertex, PickedCurve::Circle { center, radius }) => { + let Some(first) = project_to_radius(center, point, radius) else { + return CmdResult::NeedPoint; + }; + self.selecting_object = false; + self.step = Step::CircleSecondRay { + vertex: center, + first, + radius, + source: handle, + }; + CmdResult::NeedPoint + } + _ => CmdResult::NeedPoint, + } + } + + fn on_mouse_move(&mut self, point: DVec3) -> Option { + let points = match self.step { + Step::Vertex | Step::SecondLine { .. } => return None, + Step::FirstRay(vertex) => vec![vertex, point], + Step::SecondRay { vertex, first } => vec![vertex, first, nan(), vertex, point], + Step::CircleSecondRay { vertex, first, radius, .. } => { + let second = project_to_radius(vertex, point, radius).unwrap_or(point); + vec![vertex, first, nan(), vertex, second] + } + Step::ArcPoint3 { vertex, first, second } => { + angular_preview(vertex, first, second, point) + } + Step::ArcPoint2 { + first_start, + first_end, + second_start, + second_end, + } => two_line_preview( + first_start, + first_end, + second_start, + second_end, + point, + ), + }; + Some(preview_wire(points)) } } -fn v3(pt: DVec3) -> Vector3 { - Vector3::new(pt.x, pt.y, pt.z) +fn picked_curve(entity: &EntityType, click: DVec3) -> Option { + let point = |value: Vector3| DVec3::new(value.x, value.y, value.z); + match entity { + EntityType::Line(line) => Some(PickedCurve::Line(point(line.start), point(line.end))), + EntityType::Arc(arc) => Some(PickedCurve::Arc { + center: point(arc.center_wcs()), + first: point(arc.start_point_wcs()), + second: point(arc.end_point_wcs()), + }), + EntityType::Circle(circle) => Some(PickedCurve::Circle { + center: point(circle.center_wcs()), + radius: circle.radius, + }), + EntityType::LwPolyline(polyline) => { + let click = crate::scene::view::transform::wcs_point_to_ocs( + (click.x, click.y, click.z), + (polyline.normal.x, polyline.normal.y, polyline.normal.z), + ); + let segment = nearest_segment_index( + polyline.vertices.iter().map(|vertex| [vertex.location.x, vertex.location.y]).collect(), + polyline.is_closed, + [click.0, click.1], + )?; + let first = polyline.vertices[segment]; + let second = polyline.vertices[(segment + 1) % polyline.vertices.len()]; + polyline_segment( + [first.location.x, first.location.y], + [second.location.x, second.location.y], + first.bulge, + polyline.elevation, + polyline.normal, + ) + } + EntityType::Polyline2D(polyline) => { + let vertices = crate::entities::polyline::drawn_vertices2d(polyline) + .unwrap_or_else(|| polyline.vertices.clone()); + let click = crate::scene::view::transform::wcs_point_to_ocs( + (click.x, click.y, click.z), + (polyline.normal.x, polyline.normal.y, polyline.normal.z), + ); + let segment = nearest_segment_index( + vertices.iter().map(|vertex| [vertex.location.x, vertex.location.y]).collect(), + polyline.is_closed(), + [click.0, click.1], + )?; + let first = &vertices[segment]; + let second = &vertices[(segment + 1) % vertices.len()]; + polyline_segment( + [first.location.x, first.location.y], + [second.location.x, second.location.y], + first.bulge, + polyline.elevation, + polyline.normal, + ) + } + _ => None, + } } -fn preview_wire(points: Vec) -> WireModel { +fn nearest_segment_index(points: Vec<[f64; 2]>, closed: bool, click: [f64; 2]) -> Option { + if points.len() < 2 { + return None; + } + let count = if closed { points.len() } else { points.len() - 1 }; + (0..count).min_by(|first, second| { + segment_distance_squared(points[*first], points[(*first + 1) % points.len()], click) + .total_cmp(&segment_distance_squared( + points[*second], + points[(*second + 1) % points.len()], + click, + )) + }) +} + +fn segment_distance_squared(first: [f64; 2], second: [f64; 2], point: [f64; 2]) -> f64 { + let dx = second[0] - first[0]; + let dy = second[1] - first[1]; + let length_squared = dx * dx + dy * dy; + if length_squared <= 1.0e-24 { + return (point[0] - first[0]).powi(2) + (point[1] - first[1]).powi(2); + } + let t = (((point[0] - first[0]) * dx + (point[1] - first[1]) * dy) / length_squared) + .clamp(0.0, 1.0); + let x = first[0] + dx * t; + let y = first[1] + dy * t; + (point[0] - x).powi(2) + (point[1] - y).powi(2) +} + +fn polyline_segment( + first: [f64; 2], + second: [f64; 2], + bulge: f64, + elevation: f64, + normal: Vector3, +) -> Option { + let to_world = |point: [f64; 2]| { + let value = crate::scene::view::transform::ocs_point_to_wcs( + (point[0], point[1], elevation), + (normal.x, normal.y, normal.z), + ); + DVec3::new(value.0, value.1, value.2) + }; + let first_world = to_world(first); + let second_world = to_world(second); + if bulge.abs() <= 1.0e-12 { + return Some(PickedCurve::Line(first_world, second_world)); + } + let dx = second[0] - first[0]; + let dy = second[1] - first[1]; + let chord = (dx * dx + dy * dy).sqrt(); + if chord <= 1.0e-12 { + return None; + } + let midpoint = [(first[0] + second[0]) * 0.5, (first[1] + second[1]) * 0.5]; + let center_offset = chord * (1.0 - bulge * bulge) / (4.0 * bulge); + let center = [ + midpoint[0] - dy / chord * center_offset, + midpoint[1] + dx / chord * center_offset, + ]; + Some(PickedCurve::Arc { + center: to_world(center), + first: first_world, + second: second_world, + }) +} + +fn project_to_radius(center: DVec3, point: DVec3, radius: f64) -> Option { + let direction = (point - center).normalize_or_zero(); + (direction.length_squared() > 0.0).then_some(center + direction * radius) +} + +fn two_line_frame( + first_start: DVec3, + first_end: DVec3, + second_start: DVec3, + second_end: DVec3, + arc_point: DVec3, +) -> Option<(DVec3, f64, f64)> { + let first_direction = first_end - first_start; + let second_direction = second_end - second_start; + let denominator = first_direction.x * second_direction.y - first_direction.y * second_direction.x; + if denominator.abs() + <= 1.0e-12 * first_direction.length().max(second_direction.length()).max(1.0) + { + return None; + } + let offset = second_start - first_start; + let t = (offset.x * second_direction.y - offset.y * second_direction.x) / denominator; + let vertex = first_start + first_direction * t; + let target = (arc_point.y - vertex.y).atan2(arc_point.x - vertex.x); + let mut best: Option<(f64, f64, f64)> = None; + for first_sign in [1.0, -1.0] { + for second_sign in [1.0, -1.0] { + let first = first_direction * first_sign; + let second = second_direction * second_sign; + for (start, end) in [ + (first.y.atan2(first.x), second.y.atan2(second.x)), + (second.y.atan2(second.x), first.y.atan2(first.x)), + ] { + let sweep = (end - start).rem_euclid(std::f64::consts::TAU); + if sweep <= 1.0e-9 || sweep > std::f64::consts::PI { + continue; + } + let selected = (target - start).rem_euclid(std::f64::consts::TAU); + if selected <= sweep + 1.0e-9 && best.is_none_or(|known| sweep < known.2) { + best = Some((start, start + sweep, sweep)); + } + } + } + } + best.map(|(start, end, _)| (vertex, start, end)) +} + +fn angular_preview(vertex: DVec3, first: DVec3, second: DVec3, arc_point: DVec3) -> Vec { + let Some((_, start, end)) = two_line_frame(vertex, first, vertex, second, arc_point) else { + return vec![vertex, first, nan(), vertex, second]; + }; + angular_preview_with_frame(vertex, first, second, arc_point, start, end) +} + +fn two_line_preview( + first_start: DVec3, + first_end: DVec3, + second_start: DVec3, + second_end: DVec3, + arc_point: DVec3, +) -> Vec { + let Some((vertex, start, end)) = two_line_frame( + first_start, + first_end, + second_start, + second_end, + arc_point, + ) else { + return vec![first_start, first_end, nan(), second_start, second_end]; + }; + angular_preview_with_frame(vertex, first_start, second_start, arc_point, start, end) +} + +fn angular_preview_with_frame( + vertex: DVec3, + first: DVec3, + second: DVec3, + arc_point: DVec3, + start: f64, + end: f64, +) -> Vec { + let radius = vertex.distance(arc_point); + let first_end = vertex + DVec3::new(start.cos(), start.sin(), 0.0) * radius; + let second_end = vertex + DVec3::new(end.cos(), end.sin(), 0.0) * radius; + let mut points = vec![first, first_end, nan(), second, second_end, nan()]; + let sweep = end - start; + let steps = ((sweep.abs() / std::f64::consts::PI * 90.0).ceil() as usize).clamp(8, 720); + for index in 0..=steps { + let angle = start + sweep * index as f64 / steps as f64; + points.push(vertex + DVec3::new(angle.cos() * radius, angle.sin() * radius, 0.0)); + } + points +} + +fn v3(point: DVec3) -> Vector3 { + Vector3::new(point.x, point.y, point.z) +} + +fn nan() -> DVec3 { + DVec3::splat(f64::NAN) +} + +fn preview_wire(points: Vec) -> WireModel { WireModel { point_marker: None, taper_widths: Vec::new(), @@ -173,11 +678,11 @@ fn preview_wire(points: Vec) -> WireModel { render_instance: None, pick_tris: Vec::new(), pick_tris_low: Vec::new(), - dash_from_start: false, - dash_align_end: None, - text_verts: Vec::new(), + dash_from_start: false, + dash_align_end: None, + text_verts: Vec::new(), name: "dimangular_preview".to_string(), - points: points.into_iter().map(|p| [p.x, p.y, p.z]).collect(), + points: points.into_iter().map(|point| [point.x as f32, point.y as f32, point.z as f32]).collect(), points_low: Vec::new(), color: WireModel::CYAN, selected: false, @@ -195,38 +700,4 @@ fn preview_wire(points: Vec) -> WireModel { } } -fn angular_preview(vertex: Vec3, first: Vec3, second: Vec3, arc_pt: Vec3) -> Vec { - let mut points = vec![ - vertex, - first, - Vec3::new(f32::NAN, f32::NAN, f32::NAN), - vertex, - second, - Vec3::new(f32::NAN, f32::NAN, f32::NAN), - ]; - let r = vertex.distance(arc_pt); - if r <= 1e-6 { - return points; - } - let a0 = (first.y - vertex.y).atan2(first.x - vertex.x); - let mut a1 = (second.y - vertex.y).atan2(second.x - vertex.x); - let mut delta = a1 - a0; - while delta <= 0.0 { - delta += std::f32::consts::TAU; - } - if delta > std::f32::consts::PI { - a1 -= std::f32::consts::TAU; - delta = a1 - a0; - } - let steps = 24; - for i in 0..=steps { - let t = i as f32 / steps as f32; - let a = a0 + delta * t; - points.push(vertex + Vec3::new(a.cos() * r, a.sin() * r, 0.0)); - } - points -} - - -// ── Autocomplete registry ───────────────────────────────── -inventory::submit!(crate::command::CommandRegistration { names: &["DIMANGULAR"] }); // AngularDimensionCommand +inventory::submit!(crate::command::CommandRegistration { names: &["DIMANGULAR"] }); diff --git a/src/modules/annotate/linear_dim.rs b/src/modules/annotate/linear_dim.rs index a3768011c..4f0458441 100644 --- a/src/modules/annotate/linear_dim.rs +++ b/src/modules/annotate/linear_dim.rs @@ -194,7 +194,10 @@ impl CadCommand for LinearDimensionCommand { Dimension::Linear(dim), )); if let Some(source) = self.source_handle { - CmdResult::CommitAssociativeDimension { entity, source } + CmdResult::CommitAssociativeDimension { + entity, + sources: vec![source, source], + } } else { CmdResult::CommitAndExit(entity) } diff --git a/src/scene/dimension_assoc.rs b/src/scene/dimension_assoc.rs index bda8f168e..853d40092 100644 --- a/src/scene/dimension_assoc.rs +++ b/src/scene/dimension_assoc.rs @@ -27,6 +27,7 @@ fn source_points(entity: &EntityType) -> Vec { match entity { EntityType::Line(line) => vec![line.start, line.end], EntityType::Arc(arc) => vec![arc.start_point_wcs(), arc.end_point_wcs()], + EntityType::Circle(_) => Vec::new(), EntityType::LwPolyline(polyline) => polyline .vertices .iter() @@ -55,6 +56,37 @@ fn source_points(entity: &EntityType) -> Vec { } } +fn source_reference(entity: &EntityType, point: Vector3) -> Option<(i32, f64)> { + let curve_parameter = match entity { + EntityType::Circle(circle) => { + let center = circle.center_wcs(); + if point_distance_squared(center, point) <= 1e-16 { + return Some((-3, 0.0)); + } + let (axis_x, axis_y) = circle.axes_wcs(); + let offset = point - center; + Some(offset.dot(&axis_y).atan2(offset.dot(&axis_x))) + } + EntityType::Arc(arc) => { + let local = crate::scene::view::transform::wcs_point_to_ocs( + (point.x, point.y, point.z), + (arc.normal.x, arc.normal.y, arc.normal.z), + ); + let dx = local.0 - arc.center.x; + let dy = local.1 - arc.center.y; + if dx * dx + dy * dy <= 1e-16 { + return Some((-3, 0.0)); + } + Some(dy.atan2(dx)) + } + _ => None, + }; + if let Some(parameter) = curve_parameter { + return Some((-2, parameter)); + } + source_marker(entity, point).map(|marker| (marker, 0.0)) +} + fn source_marker(entity: &EntityType, point: Vector3) -> Option { source_points(entity) .into_iter() @@ -69,11 +101,45 @@ fn source_marker(entity: &EntityType, point: Vector3) -> Option { fn resolve_reference(scene: &Scene, reference: &AssocDimensionReference) -> Option { let source = *reference.xrefs.first()?; let entity = scene.document.get_entity(source)?; + if reference.main_gs_marker == -3 { + return match entity { + EntityType::Circle(circle) => Some(circle.center_wcs()), + EntityType::Arc(arc) => Some(arc.center_wcs()), + _ => None, + }; + } + if reference.main_gs_marker == -2 { + return match entity { + EntityType::Circle(circle) => { + Some(circle.point_at_angle_wcs(reference.osnap_distance)) + } + EntityType::Arc(arc) => Some(arc.point_at_angle_wcs(reference.osnap_distance)), + _ => None, + }; + } source_points(entity) .get(reference.main_gs_marker.max(0) as usize) .copied() } +fn dimension_reference_points(dimension: &Dimension) -> Vec { + match dimension { + Dimension::Linear(linear) => vec![linear.first_point, linear.second_point], + Dimension::Angular3Pt(angular) => vec![ + angular.angle_vertex, + angular.first_point, + angular.second_point, + ], + Dimension::Angular2Ln(angular) => vec![ + angular.first_point, + angular.second_point, + angular.angle_vertex, + angular.definition_point, + ], + _ => Vec::new(), + } +} + pub(crate) fn dimension_is_associative( document: &acadrust::CadDocument, dimension: Handle, @@ -97,34 +163,41 @@ pub(crate) fn dimension_is_associative( } impl Scene { - pub(crate) fn attach_linear_dimension_association( + pub(crate) fn attach_dimension_association( &mut self, dimension: Handle, - sources: [Option; 2], + sources: Vec>, ) { - let Some(EntityType::Dimension(Dimension::Linear(linear))) = + let Some(EntityType::Dimension(dimension_entity)) = self.document.get_entity(dimension) else { return; }; - let first_point = linear.first_point; - let second_point = linear.second_point; - let source_data = [first_point, second_point].map(|point| point); - let resolved: [Option<(Handle, i32)>; 2] = std::array::from_fn(|index| { - let source = sources[index]?; + let source_data = dimension_reference_points(dimension_entity); + if source_data.is_empty() { + return; + } + let resolved: Vec> = source_data + .iter() + .enumerate() + .map(|(index, point)| { + let source = sources.get(index).copied().flatten()?; let entity = self.document.get_entity(source)?; - source_marker(entity, source_data[index]).map(|marker| (source, marker)) - }); + source_reference(entity, *point) + .map(|(marker, parameter)| (source, marker, parameter)) + }) + .collect(); if resolved.iter().all(Option::is_none) { return; } - let reference = |source: Handle, marker: i32, point: Vector3| AssocDimensionReference { + let reference = |source: Handle, marker: i32, parameter: f64, point: Vector3| AssocDimensionReference { class_name: "AcDbOsnapPointRef".to_string(), osnap_type: 1, xrefs: vec![source], main_subent_type: 1, main_gs_marker: marker, + osnap_distance: parameter, osnap_point: point, ..AssocDimensionReference::default() }; @@ -132,9 +205,12 @@ impl Scene { std::array::from_fn(|_| Vec::new()); let mut associativity = 0; for (index, resolved) in resolved.into_iter().enumerate() { - if let Some((source, marker)) = resolved { + if index >= references.len() { + break; + } + if let Some((source, marker, parameter)) = resolved { associativity |= 1 << index; - references[index].push(reference(source, marker, source_data[index])); + references[index].push(reference(source, marker, parameter, source_data[index])); } } @@ -165,6 +241,14 @@ impl Scene { } } + pub(crate) fn attach_linear_dimension_association( + &mut self, + dimension: Handle, + sources: [Option; 2], + ) { + self.attach_dimension_association(dimension, sources.into_iter().collect()); + } + pub(crate) fn infer_linear_dimension_sources( &self, dimension: Handle, @@ -222,26 +306,57 @@ impl Scene { let mut refreshed = Vec::new(); for association in associations { - let first = association.references[0] - .first() - .and_then(|reference| resolve_reference(self, reference)); - let second = association.references[1] - .first() - .and_then(|reference| resolve_reference(self, reference)); - if first.is_none() && second.is_none() { + let resolved: [Option; 4] = std::array::from_fn(|index| { + association.references[index] + .first() + .and_then(|reference| resolve_reference(self, reference)) + }); + if resolved.iter().all(Option::is_none) { continue; } - if let Some(EntityType::Dimension(Dimension::Linear(linear))) = + if let Some(EntityType::Dimension(dimension)) = self.document.get_entity_mut(association.dimension) { - if let Some(first) = first { - linear.first_point = first; + match dimension { + Dimension::Linear(linear) => { + if let Some(point) = resolved[0] { + linear.first_point = point; + } + if let Some(point) = resolved[1] { + linear.second_point = point; + } + linear.base.definition_point = linear.definition_point; + } + Dimension::Angular3Pt(angular) => { + if let Some(point) = resolved[0] { + angular.angle_vertex = point; + } + if let Some(point) = resolved[1] { + angular.first_point = point; + } + if let Some(point) = resolved[2] { + angular.second_point = point; + } + angular.base.definition_point = angular.definition_point; + } + Dimension::Angular2Ln(angular) => { + if let Some(point) = resolved[0] { + angular.first_point = point; + } + if let Some(point) = resolved[1] { + angular.second_point = point; + } + if let Some(point) = resolved[2] { + angular.angle_vertex = point; + } + if let Some(point) = resolved[3] { + angular.definition_point = point; + } + angular.base.definition_point = angular.dimension_arc; + } + _ => continue, } - if let Some(second) = second { - linear.second_point = second; - } - linear.base.actual_measurement = linear.measurement(); - linear.base.definition_point = linear.definition_point; + dimension.base_mut().actual_measurement = dimension.measurement(); refreshed.push((association.dimension, ChangeKind::Modified)); } } From 04d824974d7c296abe19832054d25d05c627aa4e Mon Sep 17 00:00:00 2001 From: ramox81 <184937705+ramox81@users.noreply.github.com> Date: Tue, 25 Aug 2026 11:29:39 +0300 Subject: [PATCH 2/5] Align angular dimension properties and rendering --- src/app/update/command.rs | 31 +++- src/entities/dim_override.rs | 14 ++ src/entities/dimension.rs | 272 +++++++++++++++++++++++++++++------ 3 files changed, 269 insertions(+), 48 deletions(-) diff --git a/src/app/update/command.rs b/src/app/update/command.rs index ab25667d6..76a545e79 100644 --- a/src/app/update/command.rs +++ b/src/app/update/command.rs @@ -1144,6 +1144,31 @@ pub(super) fn on_tab_close(&mut self, idx: usize) -> Task { | GripMenuAction::MoveWithLeader | GripMenuAction::MoveIndependent ) { + let is_dimension = matches!( + self.tabs[i].scene.document.get_entity(popup.handle), + Some(acadrust::EntityType::Dimension(_)) + ); + if is_dimension { + let movement = match item.action { + GripMenuAction::MoveWithDimLine => Some("Keep dim line with text"), + GripMenuAction::MoveWithLeader => Some("Move text, add leader"), + GripMenuAction::MoveIndependent => Some("Move text, no leader"), + _ => None, + }; + if let Some(movement) = movement { + crate::entities::dim_override::set_property( + &mut self.tabs[i].scene.document, + popup.handle, + "dim_text_movement", + movement, + ); + self.tabs[i].dirty = true; + self.tabs[i].scene.bump_entities(&[( + popup.handle, + crate::scene::ChangeKind::Modified, + )]); + } + } // Stretch / Move = grab this grip. Engage it so the next // click places it (click-move-click) — same as picking the // grip directly in the viewport. Without this the menu just @@ -1157,10 +1182,12 @@ pub(super) fn on_tab_close(&mut self, idx: usize) -> Task { // "Move with Leader" drags the whole multileader; the // others move just the picked grip. let (grip_id, is_translate) = - if matches!(item.action, GripMenuAction::MoveWithLeader) { + if matches!(item.action, GripMenuAction::MoveWithLeader) + && !is_dimension + { (crate::entities::multileader::MOVE_ALL_GRIP, true) } else { - (popup.grip_id, g.is_midpoint) + (popup.grip_id, if is_dimension { false } else { g.is_midpoint }) }; self.tabs[i].active_grip = Some(GripEdit::single( popup.handle, diff --git a/src/entities/dim_override.rs b/src/entities/dim_override.rs index 13ce51b8a..aa568dcb4 100644 --- a/src/entities/dim_override.rs +++ b/src/entities/dim_override.rs @@ -274,6 +274,8 @@ pub fn property_int_code(field: &str) -> Option { "dim_line_inside" => DIMSOXD, "dim_units" => DIMLUNIT, "dim_precision" => DIMDEC, + "dim_angle_units" => DIMAUNIT, + "dim_angle_precision" => DIMADEC, "dim_decimal_separator" => DIMDSEP, "dim_fractional_type" => DIMFRAC, "dim_text_view_direction" => DIMTXTDIRECTION, @@ -330,6 +332,9 @@ fn inherited_int(doc: &CadDocument, handle: Handle, code: i16) -> i16 { DIMTOL => style.dimtol as i16, DIMLIM => style.dimlim as i16, DIMALT => style.dimalt as i16, + DIMAZIN => style.dimazin, + DIMAUNIT => style.dimaunit, + DIMADEC => style.dimadec, DIMTFILL => style.dimtfill, DIMTALN => 0, _ => 0, @@ -451,6 +456,8 @@ pub fn set_property( "dim_tolerance_suppress_trailing_zeros" => Some((DIMTZIN, 8)), "dim_alt_tolerance_suppress_leading_zeros" => Some((DIMALTTZ, 4)), "dim_alt_tolerance_suppress_trailing_zeros" => Some((DIMALTTZ, 8)), + "dim_angle_suppress_leading_zeros" => Some((DIMAZIN, 1)), + "dim_angle_suppress_trailing_zeros" => Some((DIMAZIN, 2)), _ => None, }; if let Some((code, bit)) = bit_field { @@ -624,6 +631,13 @@ pub fn set_property( "desktop" => Some(6), _ => trimmed.parse().ok(), }, + "dim_angle_units" => match trimmed.to_ascii_lowercase().as_str() { + "decimal degrees" => Some(0), + "degrees/minutes/seconds" => Some(1), + "gradians" => Some(2), + "radians" => Some(3), + _ => trimmed.parse().ok(), + }, "dim_fractional_type" => match trimmed.to_ascii_lowercase().as_str() { "horizontal" => Some(0), "diagonal" => Some(1), diff --git a/src/entities/dimension.rs b/src/entities/dimension.rs index ad6cd235a..0e0d8123a 100644 --- a/src/entities/dimension.rs +++ b/src/entities/dimension.rs @@ -32,7 +32,7 @@ fn dimension_definition_point(dim: &Dimension) -> acadrust::types::Vector3 { Dimension::Linear(d) => d.definition_point, Dimension::Radius(d) => d.definition_point, Dimension::Diameter(d) => d.definition_point, - Dimension::Angular2Ln(d) => d.definition_point, + Dimension::Angular2Ln(d) => d.dimension_arc, Dimension::Angular3Pt(d) => d.definition_point, Dimension::Ordinate(d) => d.definition_point, Dimension::Arc(d) => d.definition_point, @@ -107,6 +107,18 @@ fn properties(dim: &Dimension) -> Vec { ], }]; } + if matches!(dim, Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_)) { + return vec![PropSection { + title: t!("Misc").into_owned(), + props: vec![crate::scene::model::object::Property { + label: t!("Dimension style").into_owned(), + field: "style_name", + value: crate::scene::model::object::PropValue::PlainText( + dim.base().style_name.clone(), + ), + }], + }]; + } let mut props = base_props(dim.base()); match dim { Dimension::Aligned(d) => { @@ -1024,6 +1036,12 @@ fn restore_dim_text_relative_position( } fn dimension_line_grip_position(dim: &Dimension) -> Option { + match dim { + Dimension::Angular2Ln(d) => return Some(dv3(&d.dimension_arc)), + Dimension::Angular3Pt(d) => return Some(dv3(&d.definition_point)), + Dimension::Arc(d) => return Some(dv3(&d.definition_point)), + _ => {} + } let (first, second, defpt, ax, ay) = match dim { Dimension::Linear(d) => ( d.first_point, @@ -1139,11 +1157,12 @@ impl Grippable for Dimension { center_grip(2, text), ], Dimension::Angular2Ln(d) => vec![ - square_grip(0, dv3(&d.angle_vertex)), - center_grip(1, dv3(&d.first_point)), - center_grip(2, dv3(&d.second_point)), + square_grip(0, dv3(&d.first_point)), + center_grip(1, dv3(&d.second_point)), + center_grip(2, dv3(&d.angle_vertex)), center_grip(3, dv3(&d.definition_point)), - center_grip(4, text), + center_grip(4, dv3(&d.dimension_arc)), + center_grip(5, text), ], Dimension::Angular3Pt(d) => vec![ square_grip(0, dv3(&d.angle_vertex)), @@ -1191,7 +1210,8 @@ impl Grippable for Dimension { let text_grip = match self { Dimension::Linear(_) | Dimension::Aligned(_) => 3, Dimension::Radius(_) | Dimension::Diameter(_) => 2, - Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_) => 4, + Dimension::Angular2Ln(_) => 5, + Dimension::Angular3Pt(_) => 4, Dimension::Ordinate(_) => 3, Dimension::Arc(d) => if d.has_leader { 6 } else { 4 }, Dimension::LargeRadial(_) => 4, @@ -1234,10 +1254,11 @@ impl Grippable for Dimension { _ => {} }, Dimension::Angular2Ln(d) => match grip_id { - 0 => apply_to_v3(&mut d.angle_vertex, &apply), - 1 => apply_to_v3(&mut d.first_point, &apply), - 2 => apply_to_v3(&mut d.second_point, &apply), + 0 => apply_to_v3(&mut d.first_point, &apply), + 1 => apply_to_v3(&mut d.second_point, &apply), + 2 => apply_to_v3(&mut d.angle_vertex, &apply), 3 => apply_to_v3(&mut d.definition_point, &apply), + 4 => apply_to_v3(&mut d.dimension_arc, &apply), _ => {} }, Dimension::Angular3Pt(d) => match grip_id { @@ -1285,7 +1306,8 @@ impl Grippable for Dimension { let (dim_line_grip, text_grip) = match self { Dimension::Linear(_) | Dimension::Aligned(_) => (2, 3), Dimension::Radius(_) | Dimension::Diameter(_) => (1, 2), - Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_) => (3, 4), + Dimension::Angular2Ln(_) => (4, 5), + Dimension::Angular3Pt(_) => (3, 4), Dimension::Ordinate(_) => (0, 3), Dimension::Arc(d) => (3, if d.has_leader { 6 } else { 4 }), Dimension::LargeRadial(_) => (3, 4), @@ -1353,7 +1375,8 @@ impl Grippable for Dimension { let (_dim_line_grip, text_grip) = match self { Dimension::Linear(_) | Dimension::Aligned(_) => (2, 3), Dimension::Radius(_) | Dimension::Diameter(_) => (1, 2), - Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_) => (3, 4), + Dimension::Angular2Ln(_) => (4, 5), + Dimension::Angular3Pt(_) => (3, 4), Dimension::Ordinate(_) => (0, 3), Dimension::Arc(d) => (3, if d.has_leader { 6 } else { 4 }), Dimension::LargeRadial(_) => (3, 4), @@ -1400,7 +1423,8 @@ impl Grippable for Dimension { let text_grip = match self { Dimension::Linear(_) | Dimension::Aligned(_) => 3, Dimension::Radius(_) | Dimension::Diameter(_) => 2, - Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_) => 4, + Dimension::Angular2Ln(_) => 5, + Dimension::Angular3Pt(_) => 4, Dimension::Ordinate(_) => 3, Dimension::Arc(d) => if d.has_leader { 6 } else { 4 }, Dimension::LargeRadial(_) => 4, @@ -1641,7 +1665,7 @@ pub fn style_sections( _ => choice_value("None", &["None", "Background", "Color"]), }; - vec![ + let mut sections = vec![ PropSection { title: t!("Lines & Arrows").into_owned(), props: vec![ @@ -1968,19 +1992,19 @@ pub fn style_sections( text( t!("Decimal separator").as_ref(), "dim_decimal_separator", - decimal_separator, + decimal_separator.clone(), true, ), text( t!("Dim prefix").as_ref(), "dim_prefix", - dim_prefix, + dim_prefix.clone(), true, ), text( t!("Dim suffix").as_ref(), "dim_suffix", - dim_suffix, + dim_suffix.clone(), true, ), text( @@ -2271,7 +2295,81 @@ pub fn style_sections( ), ], }, - ] + ]; + + if matches!(dimension, Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_)) { + if let Some(text_section) = sections + .iter_mut() + .find(|section| section.title == t!("Text").as_ref()) + { + text_section + .props + .retain(|property| property.field != "dim_fractional_type"); + } + + let angle_zero_suppression = int(ov::DIMAZIN, s.dimazin); + let angle_unit = int(ov::DIMAUNIT, s.dimaunit); + if let Some(primary_units) = sections + .iter_mut() + .find(|section| section.title == t!("Primary Units").as_ref()) + { + primary_units.props = vec![ + text( + t!("Decimal separator").as_ref(), + "dim_decimal_separator", + decimal_separator, + true, + ), + text(t!("Dim prefix").as_ref(), "dim_prefix", dim_prefix, true), + text(t!("Dim suffix").as_ref(), "dim_suffix", dim_suffix, true), + choice( + t!("Angle format").as_ref(), + "dim_angle_units", + angular_unit_label(angle_unit), + &[ + "Decimal degrees", + "Degrees/minutes/seconds", + "Gradians", + "Radians", + ], + true, + ), + choice( + t!("Suppress leading zeros").as_ref(), + "dim_angle_suppress_leading_zeros", + yes(angle_zero_suppression & 1 != 0), + &["Yes", "No"], + true, + ), + choice( + t!("Suppress trailing zeros").as_ref(), + "dim_angle_suppress_trailing_zeros", + yes(angle_zero_suppression & 2 != 0), + &["Yes", "No"], + true, + ), + property( + t!("Precision").as_ref(), + "dim_angle_precision", + PropValue::Choice { + selected: int(ov::DIMADEC, s.dimadec).to_string(), + options: (0..=8).map(|value| value.to_string()).collect(), + }, + ), + ]; + } + sections.retain(|section| section.title != t!("Alternate Units").as_ref()); + if let Some(tolerances) = sections + .iter_mut() + .find(|section| section.title == t!("Tolerances").as_ref()) + { + tolerances + .props + .retain(|property| !property.field.starts_with("dim_alt_tolerance_")); + } + } + + sections } fn property(label: &str, field: &'static str, value: PropValue) -> Property { @@ -2355,6 +2453,15 @@ fn alternate_unit_label(value: i16) -> &'static str { } } +fn angular_unit_label(value: i16) -> &'static str { + match value { + 1 => "Degrees/minutes/seconds", + 2 => "Gradians", + 3 => "Radians", + _ => "Decimal degrees", + } +} + fn tolerance_vertical_label(value: i16) -> &'static str { match value { 0 => "Bottom", @@ -3369,6 +3476,8 @@ fn dimtmove_leader_endpoints(dim: &Dimension) -> Option<(Vec3, Vec3)> { } Dimension::Radius(d) => lv(d.definition_point), Dimension::Diameter(d) => (lv(d.angle_vertex) + lv(d.definition_point)) * 0.5, + Dimension::Angular2Ln(d) => lv(d.dimension_arc), + Dimension::Angular3Pt(d) => lv(d.definition_point), _ => return None, }; Some((anchor, lv(txt))) @@ -3566,7 +3675,12 @@ fn dimension_geometry( // ten degrees came out as two hundred and seventy. let (p1, p2) = (lv(d.first_point), lv(d.second_point)); let (p3, p4) = (lv(d.angle_vertex), lv(d.definition_point)); - let arc_point = lv(d.dimension_arc); + let stored_arc = if d.dimension_arc.length_squared() > 1.0e-18 { + d.dimension_arc + } else { + d.base.definition_point + }; + let arc_point = lv(stored_arc); match two_line_angle_frame(p1, p2, p3, p4, arc_point) { Some((vertex, start, end)) => append_angular_dimension( &mut g, @@ -3577,6 +3691,8 @@ fn dimension_geometry( arrow1, arrow2, Some((start, end)), + params, + suppress, ), // Parallel lines have no vertex and so no angle to draw; the // extension lines alone say where the dimension was. @@ -3587,15 +3703,29 @@ fn dimension_geometry( } } Dimension::Angular3Pt(d) => { + let vertex = lv(d.angle_vertex); + let first = lv(d.first_point); + let second = lv(d.second_point); + let arc_point = lv(d.definition_point); + let explicit_sweep = two_line_angle_frame( + vertex, + first, + vertex, + second, + arc_point, + ) + .map(|(_, start, end)| (start, end)); append_angular_dimension( &mut g, - lv(d.angle_vertex), - lv(d.first_point), - lv(d.second_point), - lv(d.definition_point), + vertex, + first, + second, + arc_point, arrow1, arrow2, - None, + explicit_sweep, + params, + suppress, ); } Dimension::Ordinate(d) => { @@ -3623,6 +3753,8 @@ fn dimension_geometry( d.arc_start_parameter as f32, d.arc_end_parameter as f32, )), + params, + suppress, ); if d.has_leader { add_segment( @@ -3933,6 +4065,8 @@ fn append_angular_dimension( arrow1: &ArrowKind, arrow2: &ArrowKind, explicit_sweep: Option<(f32, f32)>, + params: DimLineParams, + suppress: SuppressFlags, ) { let radius = vertex.distance(arc_point); if radius <= 1e-6 { @@ -3947,8 +4081,30 @@ fn append_angular_dimension( let (start, mut end) = explicit_sweep.unwrap_or((measured_start, measured_end)); let dir1 = Vec3::new(start.cos(), start.sin(), 0.0); let dir2 = Vec3::new(end.cos(), end.sin(), 0.0); - add_segment(&mut g.ext_lines, first, vertex + dir1 * radius); - add_segment(&mut g.ext_lines, second, vertex + dir2 * radius); + let arc_start = vertex + dir1 * radius; + let arc_end = vertex + dir2 * radius; + let extension = |origin: Vec3, endpoint: Vec3, direction: Vec3| { + if params.dimfxlon { + ( + endpoint - direction * params.dimfxl.max(0.0), + endpoint + direction * params.dimexe, + ) + } else { + let toward_arc = normalized_or(endpoint - origin, direction); + ( + origin + toward_arc * params.dimexo, + endpoint + toward_arc * params.dimexe, + ) + } + }; + let (ext1_start, ext1_end) = extension(first, arc_start, dir1); + let (ext2_start, ext2_end) = extension(second, arc_end, dir2); + if !suppress.ext1 { + add_segment(&mut g.ext_lines, ext1_start, ext1_end); + } + if !suppress.ext2 { + add_segment(&mut g.ext_lines, ext2_start, ext2_end); + } let mut delta = end - start; // Wrap a negative sweep forwards, but leave a zero one alone: two rays that @@ -3965,14 +4121,28 @@ fn append_angular_dimension( delta = end - start; } - let steps = 32; + let arc_extension = if params.ticks && radius > 1.0e-6 { + params.dimdle / radius + } else { + 0.0 + }; + let direction = delta.signum(); + let draw_start = start - direction * arc_extension; + let draw_delta = delta + direction * arc_extension * 2.0; + let steps = angular_arc_steps(draw_delta); let mut arc_pts = Vec::with_capacity((steps + 1) as usize); for i in 0..=steps { let t = i as f32 / steps as f32; - let a = start + delta * t; + let a = draw_start + draw_delta * t; arc_pts.push(vertex + Vec3::new(a.cos() * radius, a.sin() * radius, 0.0)); } - add_polyline(&mut g.dim_lines, &arc_pts); + let midpoint = arc_pts.len() / 2; + if !suppress.dim1 && midpoint > 0 { + add_polyline(&mut g.dim_lines, &arc_pts[..=midpoint]); + } + if !suppress.dim2 && midpoint + 1 < arc_pts.len() { + add_polyline(&mut g.dim_lines, &arc_pts[midpoint..]); + } if arc_pts.len() >= 2 { append_arrow( @@ -3991,6 +4161,10 @@ fn append_angular_dimension( } } +fn angular_arc_steps(sweep: f32) -> u32 { + ((sweep.abs() / std::f32::consts::PI * 90.0).ceil() as u32).clamp(8, 720) +} + fn dimension_snap_pts(dim: &Dimension) -> Vec<(glam::DVec3, SnapHint)> { let lv = |v: acadrust::types::Vector3| glam::DVec3::new(v.x, v.y, v.z); let node = |v: acadrust::types::Vector3| (lv(v), SnapHint::Node); @@ -4008,10 +4182,11 @@ fn dimension_snap_pts(dim: &Dimension) -> Vec<(glam::DVec3, SnapHint)> { Dimension::Radius(d) => vec![node(d.angle_vertex), node(d.definition_point)], Dimension::Diameter(d) => vec![node(d.angle_vertex), node(d.definition_point)], Dimension::Angular2Ln(d) => vec![ - node(d.angle_vertex), node(d.first_point), node(d.second_point), + node(d.angle_vertex), node(d.definition_point), + node(d.dimension_arc), ], Dimension::Angular3Pt(d) => vec![ node(d.angle_vertex), @@ -4771,35 +4946,44 @@ fn reduce_fraction(mut n: u64, mut d: u64) -> String { /// Format an angular measurement (input in degrees as Dimension::measurement /// returns for angular variants) honouring DIMAUNIT, DIMADEC, DIMAZIN. fn format_angular_value(measurement_deg: f64, style: Option<&DimStyle>) -> String { - let (aunit, adec, azin) = style - .map(|s| (s.dimaunit, s.dimadec, s.dimazin)) - .unwrap_or((0, 2, 0)); + let (aunit, adec, azin, decimal_separator) = style + .map(|s| (s.dimaunit, s.dimadec, s.dimazin, s.dimdsep)) + .unwrap_or((0, 2, 0, b'.' as i16)); let adec = adec.max(0) as usize; match aunit { // 1 = Degrees / Minutes / Seconds - 1 => format_dms(measurement_deg, adec, azin), + 1 => format_dms(measurement_deg, adec, azin, decimal_separator), // 2 = Gradians 2 => { let g = measurement_deg / 0.9; let raw = format!("{:.*}", adec, g); - format!("{}g", apply_angular_zero_suppression(&raw, azin)) + format!( + "{}g", + swap_decimal_sep(&apply_angular_zero_suppression(&raw, azin), decimal_separator) + ) } // 3 = Radians 3 => { let r = measurement_deg.to_radians(); let raw = format!("{:.*}", adec, r); - format!("{}r", apply_angular_zero_suppression(&raw, azin)) + format!( + "{}r", + swap_decimal_sep(&apply_angular_zero_suppression(&raw, azin), decimal_separator) + ) } // 0 or unknown = Decimal Degrees _ => { let raw = format!("{:.*}", adec, measurement_deg); - format!("{}°", apply_angular_zero_suppression(&raw, azin)) + format!( + "{}°", + swap_decimal_sep(&apply_angular_zero_suppression(&raw, azin), decimal_separator) + ) } } } -fn format_dms(deg: f64, sec_dec: usize, azin: i16) -> String { +fn format_dms(deg: f64, sec_dec: usize, azin: i16, decimal_separator: i16) -> String { let sign = if deg < 0.0 { "-" } else { "" }; let abs = deg.abs(); let d = abs.floor(); @@ -4807,15 +4991,11 @@ fn format_dms(deg: f64, sec_dec: usize, azin: i16) -> String { let m = m_full.floor(); let s = (m_full - m) * 60.0; let s_str = format!("{:.*}", sec_dec, s); - let mut out = format!("{}{:.0}°{:.0}'{}\"", sign, d, m, s_str); - if azin & 4 != 0 { - // suppress 0° / 0' parts - if d == 0.0 { - out = out.trim_start_matches('0').to_string(); - out = out.replacen("°", "", 1); - } - } - out + let s_str = swap_decimal_sep( + &apply_angular_zero_suppression(&s_str, azin), + decimal_separator, + ); + format!("{}{:.0}°{:.0}'{}\"", sign, d, m, s_str) } /// Apply DIMZIN bit flags to a formatted linear value. From a8f05716cff05b63bcc77ee7b06f0013a5a70bd6 Mon Sep 17 00:00:00 2001 From: ramox81 <184937705+ramox81@users.noreply.github.com> Date: Tue, 25 Aug 2026 11:29:39 +0300 Subject: [PATCH 3/5] Use corrected angular dimension data model --- Cargo.lock | 2 +- Cargo.toml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 808da0125..1e6798896 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,7 +72,7 @@ checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" [[package]] name = "acadrust" version = "0.4.1" -source = "git+https://git@github.com/HakanSeven12/cadcodec.git?rev=5b2ae66#5b2ae66d0bd7b0da2d13392d3c3332f8a39caa1f" +source = "git+https://git@github.com/HakanSeven12/cadcodec.git?rev=aa527f3#aa527f35399cba500b0c923d1e15f52286820565" dependencies = [ "ahash 0.8.12", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index dc49bfb1c..4768d3156 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ glam = { version = "0.33", features = ["bytemuck"] } rfd = "0.17" clap = { version = "4", features = ["derive"] } env_logger = "0.11" -acadrust = { git = "https://github.com/HakanSeven12/cadcodec.git", rev = "5b2ae66", features = ["serde"] } +acadrust = { git = "https://github.com/HakanSeven12/cadcodec.git", rev = "aa527f3", features = ["serde"] } cadkernel = { git = "https://github.com/HakanSeven12/cadkernel.git", rev = "b2b1d4b", features = ["acis", "offset"] } dwg-thumbnailer = { path = "crates/dwg-thumbnailer" } flate2 = "1" @@ -61,7 +61,7 @@ iced_core = { git = "https://github.com/iced-rs/iced.git", rev = "23604ff22ab0aa iced_widget = { git = "https://github.com/iced-rs/iced.git", rev = "23604ff22ab0aad9e00b9327cb7b8546ed84db39" } [patch."https://github.com/HakanSeven12/cadcodec.git"] -acadrust = { git = "https://git@github.com/HakanSeven12/cadcodec.git", rev = "5b2ae66" } +acadrust = { git = "https://git@github.com/HakanSeven12/cadcodec.git", rev = "aa527f3" } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] ocs_plugin_api = { path = "crates/ocs_plugin_api", features = ["host"] } From 24b344b2b2f40148b8f68c9111b5cdea126f6212 Mon Sep 17 00:00:00 2001 From: ramox81 <184937705+ramox81@users.noreply.github.com> Date: Tue, 25 Aug 2026 12:23:21 +0300 Subject: [PATCH 4/5] Complete angular dimension interaction and associations --- src/app/command_driver.rs | 67 +++ src/app/mod.rs | 6 + src/app/mtext_editor.rs | 12 + src/app/update/file.rs | 7 + src/command.rs | 51 +++ src/modules/annotate/angular_dim.rs | 620 ++++++++++++++++++++++++---- src/scene/dimension_assoc.rs | 89 +++- 7 files changed, 777 insertions(+), 75 deletions(-) diff --git a/src/app/command_driver.rs b/src/app/command_driver.rs index 1bff0d720..6845b7772 100644 --- a/src/app/command_driver.rs +++ b/src/app/command_driver.rs @@ -581,6 +581,36 @@ impl OpenCADStudio { let _ = self.apply_cmd_result(r); return; } + let accepts_points = self.tabs[i] + .active_cmd + .as_ref() + .is_some_and(|command| command.entity_pick_accepts_points()); + if accepts_points { + if let Some((coord, kind)) = super::helpers::parse_coord(token) { + let ucs = self.tabs[i].active_ucs.clone(); + let wcs = match ( + matches!(kind, super::helpers::CoordKind::Relative), + self.last_point, + ) { + (true, Some(base)) => { + base + match &ucs { + Some(value) => super::helpers::ucs_rotate_vec(coord, value), + None => coord, + } + } + _ => match &ucs { + Some(value) => super::helpers::ucs_to_wcs(coord, value), + None => coord, + }, + }; + if self.command_point_allowed(i, wcs) { + self.last_point = Some(wcs); + self.push_ucs_to_cmd(i); + let _ = self.feed_command(StepInput::Point(wcs)); + } + return; + } + } if let Ok(v) = u64::from_str_radix(token.trim_start_matches("0x"), 16) { let handle = Handle::new(v); let pt = self.tabs[i] @@ -1257,6 +1287,30 @@ impl OpenCADStudio { self.commit_undo_delta(i, pending); } } + CmdResult::CommitAssociativeDimensionDetailed { entity, sources } => { + let label = self.history_label_from_active_cmd(i, "DIMENSION"); + let pending = self.begin_undo(i, label, 1, false); + if let Some(handle) = self.commit_entity_handle(entity) { + self.tabs[i] + .scene + .attach_dimension_association_sources(handle, sources.clone()); + let mut changed = vec![(handle, crate::scene::ChangeKind::Modified)]; + changed.extend(sources.iter().flatten().map(|source| { + (source.handle, crate::scene::ChangeKind::Modified) + })); + changed.sort_by_key(|(handle, _)| handle.value()); + changed.dedup_by_key(|(handle, _)| handle.value()); + self.tabs[i].scene.bump_entities(&changed); + } + self.tabs[i].dirty = true; + self.tabs[i].scene.clear_preview_wire(); + self.tabs[i].active_cmd = None; + self.tabs[i].snap_result = None; + self.restore_pre_cmd_tangent(); + if let Some(pending) = pending { + self.commit_undo_delta(i, pending); + } + } CmdResult::CommitSolid { entity, solid, @@ -3572,6 +3626,19 @@ impl OpenCADStudio { self.tabs[i].snap_result = None; self.open_mtext_editor(pos, handle, &initial, height); } + CmdResult::SuspendForMTextInput { + pos, + initial, + height, + } => { + self.tabs[i].suspended_cmd = self.tabs[i].active_cmd.take(); + self.tabs[i].snap_result = None; + self.tabs[i].scene.clear_preview_wire(); + self.restore_pre_cmd_tangent(); + self.command_mtext_input = true; + self.pending_command_editor_text = None; + self.open_mtext_editor(pos, None, &initial, height); + } CmdResult::OpenTextEditor { pos, handle, diff --git a/src/app/mod.rs b/src/app/mod.rs index 3830c21dc..927a40bf6 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -764,6 +764,10 @@ pub(super) struct OpenCADStudio { ctrl_down: bool, /// Open in-place MText editor (toolbar + text area + live preview), if any. mtext_editor: Option, + /// The current rich-text editor belongs to a suspended drawing command and + /// must return text instead of creating a standalone MText entity. + command_mtext_input: bool, + pending_command_editor_text: Option, /// Open in-place single-line TEXT editor (plain text-entry box), if any. text_inline: Option, /// Cursor-anchored one-shot snap override menu (Shift+RMB): the canvas @@ -3252,6 +3256,8 @@ impl OpenCADStudio { ctrl_down: false, cont_anchor: None, mtext_editor: None, + command_mtext_input: false, + pending_command_editor_text: None, text_inline: None, snap_override_popup: None, axis_lock_dir: None, diff --git a/src/app/mtext_editor.rs b/src/app/mtext_editor.rs index f4566d813..f5dae78ee 100644 --- a/src/app/mtext_editor.rs +++ b/src/app/mtext_editor.rs @@ -1209,6 +1209,12 @@ impl super::OpenCADStudio { pub(super) fn mtext_commit(&mut self) -> bool { let i = self.active_tab; let Some(ed) = self.mtext_editor.take() else { return false }; + if self.command_mtext_input { + self.pending_command_editor_text = Some(ed.build_mtext().value); + self.command_mtext_input = false; + self.refresh_properties(); + return true; + } let body_empty = ed.content.text().trim().is_empty(); let mut mt = ed.build_mtext(); let annotative = ed.editing.is_none() @@ -1302,6 +1308,10 @@ impl super::OpenCADStudio { /// then updated in place on later applies, so repeated Apply never leaves /// duplicate entities behind. pub(super) fn mtext_apply(&mut self) { + if self.command_mtext_input { + self.rebuild_mtext_preview(); + return; + } let i = self.active_tab; let (mut mt, editing, body_empty) = match self.mtext_editor.as_ref() { Some(ed) => ( @@ -1398,6 +1408,8 @@ impl super::OpenCADStudio { /// Discard the editor without changing the drawing. pub(super) fn mtext_cancel(&mut self) { self.mtext_editor = None; + self.command_mtext_input = false; + self.pending_command_editor_text = None; self.reset_modal_geometry(); } } diff --git a/src/app/update/file.rs b/src/app/update/file.rs index 8615be0e8..10a95940e 100644 --- a/src/app/update/file.rs +++ b/src/app/update/file.rs @@ -492,6 +492,13 @@ impl OpenCADStudio { self.reset_modal_geometry(); let i = self.active_tab; if let Some(mut cmd) = self.tabs[i].suspended_cmd.take() { + if committed { + if let Some(value) = self.pending_command_editor_text.take() { + cmd.on_editor_text(value); + } + } else { + self.pending_command_editor_text = None; + } let res = cmd.on_editor_closed(committed); self.tabs[i].active_cmd = Some(cmd); self.apply_cmd_result(res) diff --git a/src/command.rs b/src/command.rs index b8dbdb6fc..22440bcaf 100644 --- a/src/command.rs +++ b/src/command.rs @@ -169,6 +169,34 @@ pub struct SelectionEntity { pub surface_area: Option, } +/// One source point used by an associative dimension. A missing marker asks +/// the scene to infer the closest stable sub-entity; an explicit marker keeps +/// segment-level references intact. +#[derive(Clone, Copy, Debug)] +pub struct DimensionAssociationSource { + pub handle: Handle, + pub marker: Option, + pub parameter: f64, +} + +impl DimensionAssociationSource { + pub const fn inferred(handle: Handle) -> Self { + Self { + handle, + marker: None, + parameter: 0.0, + } + } + + pub const fn explicit(handle: Handle, marker: i32, parameter: f64) -> Self { + Self { + handle, + marker: Some(marker), + parameter, + } + } +} + #[derive(Clone)] pub enum AreaPreviewSource { Handles(Vec), @@ -1217,6 +1245,12 @@ pub enum CmdResult { entity: EntityType, sources: Vec, }, + /// Commit a dimension whose definition points carry explicit sub-entity + /// references. `None` leaves that definition point independent. + CommitAssociativeDimensionDetailed { + entity: EntityType, + sources: Vec>, + }, /// Commit a Model-tab 3D solid: the acadrust entity (for selection / /// persistence) plus its B-rep (cached for boolean ops + shaded /// rendering). Ends the command. @@ -1396,6 +1430,13 @@ pub enum CmdResult { initial: String, height: f64, }, + /// Temporarily suspend the active command and collect formatted text in the + /// rich editor without creating a standalone MText entity. + SuspendForMTextInput { + pos: DVec3, + initial: String, + height: f64, + }, /// Open the in-place single-line TEXT editor (a plain text-entry box, no /// formatting toolbar). `handle` is `Some` when editing an existing Text, /// `None` when creating a new one at `pos`. @@ -1777,6 +1818,12 @@ pub trait CadCommand: Send { false } + /// Allow typed coordinates while object picking is active. Commands whose + /// first prompt accepts either an object or a point opt in explicitly. + fn entity_pick_accepts_points(&self) -> bool { + false + } + /// Include filled hatch / DXF SOLID regions in the entity hit-test. /// /// Most entity-pick commands operate on curve geometry and intentionally @@ -1805,6 +1852,10 @@ pub trait CadCommand: Send { CmdResult::Cancel } + /// Supplies formatted text collected by `SuspendForMTextInput` before the + /// command is resumed through `on_editor_closed`. + fn on_editor_text(&mut self, _value: String) {} + /// Called when the user clicks and `needs_entity_pick()` is true. /// `handle` is the nearest wire's entity handle (Handle::NULL if nothing found). fn on_entity_pick(&mut self, _handle: Handle, _pt: DVec3) -> CmdResult { diff --git a/src/modules/annotate/angular_dim.rs b/src/modules/annotate/angular_dim.rs index d6e9edf97..4b7dc3fb9 100644 --- a/src/modules/annotate/angular_dim.rs +++ b/src/modules/annotate/angular_dim.rs @@ -2,7 +2,9 @@ use acadrust::entities::{Dimension, DimensionAngular2Ln, DimensionAngular3Pt}; use acadrust::types::{Handle, Vector3}; use acadrust::EntityType; -use crate::command::{CadCommand, CmdResult, WorkingPlane}; +use crate::command::{ + CadCommand, CmdOption, CmdResult, DimensionAssociationSource, WorkingPlane, +}; use crate::modules::{IconKind, ModuleEvent, ToolDef}; use crate::scene::model::wire_model::WireModel; use crate::t; @@ -26,13 +28,13 @@ enum Step { CircleSecondRay { vertex: DVec3, first: DVec3, - radius: f64, source: Handle, }, SecondLine { first_start: DVec3, first_end: DVec3, first_source: Handle, + first_refs: [SourceLocator; 2], }, ArcPoint3 { vertex: DVec3, @@ -47,16 +49,44 @@ enum Step { }, } +#[derive(Clone, Copy, Debug, PartialEq)] +struct SourceLocator { + marker: Option, + parameter: f64, +} + +impl SourceLocator { + const INFERRED: Self = Self { marker: None, parameter: 0.0 }; + + const fn explicit(marker: i32, parameter: f64) -> Self { + Self { marker: Some(marker), parameter } + } + + fn bind(self, handle: Handle) -> DimensionAssociationSource { + match self.marker { + Some(marker) => DimensionAssociationSource::explicit(handle, marker, self.parameter), + None => DimensionAssociationSource::inferred(handle), + } + } +} + enum PickedCurve { - Line(DVec3, DVec3), + Line { + start: DVec3, + end: DVec3, + refs: [SourceLocator; 2], + normal: Option, + }, Arc { center: DVec3, first: DVec3, second: DVec3, + refs: [SourceLocator; 3], + normal: DVec3, }, Circle { center: DVec3, - radius: f64, + normal: DVec3, }, } @@ -65,12 +95,15 @@ pub struct AngularDimensionCommand { plane: WorkingPlane, selecting_object: bool, picked_entity: Option, - source_handles: Vec, + source_refs: Vec>, text_override: Option, awaiting_text: bool, mtext_override: bool, text_angle: Option, awaiting_angle: bool, + angle_origin: Option, + awaiting_quadrant: bool, + quadrant_lock: Option<(f64, f64)>, } impl AngularDimensionCommand { @@ -78,14 +111,17 @@ impl AngularDimensionCommand { Self { step: Step::Vertex, plane: WorkingPlane::default(), - selecting_object: false, + selecting_object: true, picked_entity: None, - source_handles: Vec::new(), + source_refs: Vec::new(), text_override: None, awaiting_text: false, mtext_override: false, text_angle: None, awaiting_angle: false, + angle_origin: None, + awaiting_quadrant: false, + quadrant_lock: None, } } @@ -99,12 +135,23 @@ impl AngularDimensionCommand { let vertex = self.plane.to_local(vertex); let first = self.plane.to_local(first); let second = self.plane.to_local(second); - let arc_point = self.plane.to_local(arc_point); + let picked_text = self.plane.to_local(arc_point); + let arc_point = locked_arc_point(vertex, picked_text, self.quadrant_lock); + if two_line_frame(vertex, first, vertex, second, arc_point).is_none() { + return CmdResult::NeedPoint; + } let mut dim = DimensionAngular3Pt::new(v3(vertex), v3(first), v3(second)); dim.definition_point = v3(arc_point); dim.base.definition_point = dim.definition_point; dim.base.text_middle_point = dim.definition_point; dim.base.insertion_point = dim.definition_point; + if self.quadrant_lock.is_some_and(|frame| { + !point_angle_in_frame(vertex, picked_text, frame) + }) { + dim.base.text_middle_point = v3(picked_text); + dim.base.insertion_point = dim.base.text_middle_point; + dim.base.text_user_positioned = true; + } dim.base.actual_measurement = dim.measurement_degrees(); crate::entities::dimension::set_dimension_text_override( &mut dim.base, @@ -128,7 +175,28 @@ impl AngularDimensionCommand { let first_end = self.plane.to_local(first_end); let second_start = self.plane.to_local(second_start); let second_end = self.plane.to_local(second_end); - let arc_point = self.plane.to_local(arc_point); + let picked_text = self.plane.to_local(arc_point); + let Some((vertex, _, _)) = two_line_frame( + first_start, + first_end, + second_start, + second_end, + picked_text, + ) else { + return CmdResult::NeedPoint; + }; + let arc_point = locked_arc_point(vertex, picked_text, self.quadrant_lock); + if two_line_frame( + first_start, + first_end, + second_start, + second_end, + arc_point, + ) + .is_none() + { + return CmdResult::NeedPoint; + } let mut dim = DimensionAngular2Ln::default(); dim.first_point = v3(first_start); dim.second_point = v3(first_end); @@ -138,6 +206,13 @@ impl AngularDimensionCommand { dim.base.definition_point = dim.dimension_arc; dim.base.text_middle_point = dim.dimension_arc; dim.base.insertion_point = dim.dimension_arc; + if self.quadrant_lock.is_some_and(|frame| { + !point_angle_in_frame(vertex, picked_text, frame) + }) { + dim.base.text_middle_point = v3(picked_text); + dim.base.insertion_point = dim.base.text_middle_point; + dim.base.text_user_positioned = true; + } dim.base.actual_measurement = dim.measurement_degrees(); crate::entities::dimension::set_dimension_text_override( &mut dim.base, @@ -151,12 +226,12 @@ impl AngularDimensionCommand { fn commit(&self, dimension: Dimension) -> CmdResult { let entity = self.plane.place_entity(EntityType::Dimension(dimension)); - if self.source_handles.is_empty() { + if self.source_refs.iter().all(Option::is_none) { CmdResult::CommitAndExit(entity) } else { - CmdResult::CommitAssociativeDimension { + CmdResult::CommitAssociativeDimensionDetailed { entity, - sources: self.source_handles.clone(), + sources: self.source_refs.clone(), } } } @@ -164,6 +239,81 @@ impl AngularDimensionCommand { fn placement_step(&self) -> bool { matches!(self.step, Step::ArcPoint3 { .. } | Step::ArcPoint2 { .. }) } + + fn editor_anchor(&self) -> DVec3 { + match self.step { + Step::ArcPoint3 { vertex, first, second } => { + let radius = vertex.distance(first).max(vertex.distance(second)).max(1.0); + let first_angle = self.plane.angle(vertex, first).unwrap_or(0.0); + let second_angle = self.plane.angle(vertex, second).unwrap_or(first_angle); + let sweep = (second_angle - first_angle).rem_euclid(std::f64::consts::TAU); + let angle = first_angle + sweep * 0.5; + self.plane.to_world( + self.plane.to_local(vertex) + + DVec3::new(angle.cos() * radius, angle.sin() * radius, 0.0), + ) + } + Step::ArcPoint2 { + first_start, + first_end, + second_start, + second_end, + } => { + let first_start = self.plane.to_local(first_start); + let first_end = self.plane.to_local(first_end); + let second_start = self.plane.to_local(second_start); + let second_end = self.plane.to_local(second_end); + two_line_frame( + first_start, + first_end, + second_start, + second_end, + (first_start + second_start) * 0.5, + ) + .map(|(vertex, start, end)| { + self.plane.to_world(vertex + DVec3::new( + ((start + end) * 0.5).cos(), + ((start + end) * 0.5).sin(), + 0.0, + )) + }) + .unwrap_or_else(|| self.plane.to_world(first_start)) + } + _ => self.plane.origin, + } + } + + fn set_quadrant_from_point(&mut self, point: DVec3) -> bool { + let point = self.plane.to_local(point); + let frame = match self.step { + Step::ArcPoint3 { vertex, first, second } => two_line_frame( + self.plane.to_local(vertex), + self.plane.to_local(first), + self.plane.to_local(vertex), + self.plane.to_local(second), + point, + ), + Step::ArcPoint2 { + first_start, + first_end, + second_start, + second_end, + } => two_line_frame( + self.plane.to_local(first_start), + self.plane.to_local(first_end), + self.plane.to_local(second_start), + self.plane.to_local(second_end), + point, + ), + _ => None, + }; + if let Some((_, start, end)) = frame { + self.quadrant_lock = Some((start, end)); + true + } else { + false + } + } } impl CadCommand for AngularDimensionCommand { @@ -176,6 +326,9 @@ impl CadCommand for AngularDimensionCommand { } fn prompt(&self) -> String { + if self.awaiting_quadrant { + return t!("DIMANGULAR Specify quadrant:").into_owned(); + } if self.awaiting_text { return if self.mtext_override { t!("DIMANGULAR Enter formatted dimension text (blank = measured value):") @@ -185,17 +338,24 @@ impl CadCommand for AngularDimensionCommand { }; } if self.awaiting_angle { - return t!("DIMANGULAR Specify text angle (degrees):").into_owned(); + return if self.angle_origin.is_some() { + t!("DIMANGULAR Specify second point for text angle:").into_owned() + } else { + t!("DIMANGULAR Specify text angle or first point:").into_owned() + }; } if self.selecting_object { return match self.step { Step::SecondLine { .. } => t!("DIMANGULAR Select second line:").into_owned(), - _ => t!("DIMANGULAR Select arc, circle, line, or polyline arc:").into_owned(), + _ => t!( + "DIMANGULAR Select arc, circle, line, or specify an angle vertex:" + ) + .into_owned(), }; } match self.step { Step::Vertex => t!( - "DIMANGULAR Specify angle vertex or press Enter to select an object:" + "DIMANGULAR Specify angle vertex:" ) .into_owned(), Step::FirstRay(_) => { @@ -213,6 +373,29 @@ impl CadCommand for AngularDimensionCommand { } fn on_point(&mut self, point: DVec3) -> CmdResult { + if self.awaiting_quadrant { + if self.set_quadrant_from_point(point) { + self.awaiting_quadrant = false; + } + return CmdResult::NeedPoint; + } + if self.awaiting_angle { + if let Some(origin) = self.angle_origin { + if let Some(angle) = self.plane.angle(origin, point) { + self.text_angle = Some(angle); + self.awaiting_angle = false; + self.angle_origin = None; + } + } else { + self.angle_origin = Some(point); + } + return CmdResult::NeedPoint; + } + if self.selecting_object && matches!(self.step, Step::Vertex) { + self.selecting_object = false; + self.step = Step::FirstRay(point); + return CmdResult::NeedPoint; + } match self.step { Step::Vertex => { self.step = Step::FirstRay(point); @@ -229,15 +412,26 @@ impl CadCommand for AngularDimensionCommand { if point.distance_squared(vertex) <= 1.0e-24 { return CmdResult::NeedPoint; } + let first_local = self.plane.vector_to_local(first - vertex); + let second_local = self.plane.vector_to_local(point - vertex); + if (first_local.x * second_local.y - first_local.y * second_local.x).abs() + <= 1.0e-12 * first_local.length().max(second_local.length()).max(1.0) + { + return CmdResult::NeedPoint; + } self.step = Step::ArcPoint3 { vertex, first, second: point }; CmdResult::NeedPoint } - Step::CircleSecondRay { vertex, first, radius, source } => { - let Some(second) = project_to_radius(vertex, point, radius) else { + Step::CircleSecondRay { vertex, first, source } => { + if point.distance_squared(vertex) <= 1.0e-24 { return CmdResult::NeedPoint; - }; - self.source_handles = vec![source, source, source]; - self.step = Step::ArcPoint3 { vertex, first, second }; + } + self.source_refs = vec![ + Some(DimensionAssociationSource::inferred(source)), + Some(DimensionAssociationSource::inferred(source)), + None, + ]; + self.step = Step::ArcPoint3 { vertex, first, second: point }; CmdResult::NeedPoint } Step::SecondLine { .. } => CmdResult::NeedPoint, @@ -260,16 +454,21 @@ impl CadCommand for AngularDimensionCommand { } fn on_enter(&mut self) -> CmdResult { + if self.awaiting_quadrant { + self.awaiting_quadrant = false; + return CmdResult::NeedPoint; + } if self.awaiting_text { self.awaiting_text = false; return CmdResult::NeedPoint; } if self.awaiting_angle { self.awaiting_angle = false; + self.angle_origin = None; return CmdResult::NeedPoint; } if matches!(self.step, Step::Vertex) { - self.selecting_object = true; + self.selecting_object = !self.selecting_object; return CmdResult::NeedPoint; } CmdResult::Cancel @@ -287,8 +486,24 @@ impl CadCommand for AngularDimensionCommand { self.awaiting_text } + fn options(&self) -> Vec { + if self.placement_step() && !self.awaiting_text && !self.awaiting_angle && !self.awaiting_quadrant { + vec![ + CmdOption::new("Mtext", "MTEXT"), + CmdOption::new("Text", "TEXT"), + CmdOption::new("Angle", "ANGLE"), + CmdOption::new("Quadrant", "QUADRANT"), + ] + } else { + Vec::new() + } + } + fn point_step_accepts_keywords(&self) -> bool { - self.placement_step() && !self.awaiting_text && !self.awaiting_angle + self.placement_step() + && !self.awaiting_text + && !self.awaiting_angle + && !self.awaiting_quadrant } fn on_text_input(&mut self, text: &str) -> Option { @@ -309,6 +524,7 @@ impl CadCommand for AngularDimensionCommand { crate::entities::common::parse_typed_angle(text.trim()) }; self.awaiting_angle = false; + self.angle_origin = None; return Some(CmdResult::NeedPoint); } if !self.placement_step() { @@ -322,22 +538,46 @@ impl CadCommand for AngularDimensionCommand { } "M" | "MTEXT" => { self.mtext_override = true; - self.awaiting_text = true; - Some(CmdResult::NeedPoint) + Some(CmdResult::SuspendForMTextInput { + pos: self.editor_anchor(), + initial: self.text_override.clone().unwrap_or_default(), + height: 2.5, + }) } "A" | "ANGLE" => { self.awaiting_angle = true; + self.angle_origin = None; + Some(CmdResult::NeedPoint) + } + "Q" | "QUADRANT" => { + self.awaiting_quadrant = true; Some(CmdResult::NeedPoint) } - "Q" | "QUADRANT" => Some(CmdResult::NeedPoint), _ => None, } } + fn on_editor_text(&mut self, value: String) { + let value = value.trim(); + self.text_override = if value.is_empty() || value == "<>" { + None + } else { + Some(value.to_string()) + }; + } + + fn on_editor_closed(&mut self, _committed: bool) -> CmdResult { + CmdResult::NeedPoint + } + fn needs_entity_pick(&self) -> bool { self.selecting_object } + fn entity_pick_accepts_points(&self) -> bool { + self.selecting_object && matches!(self.step, Step::Vertex) + } + fn entity_pick_highlights_hover(&self) -> bool { true } @@ -352,6 +592,10 @@ impl CadCommand for AngularDimensionCommand { fn on_entity_pick(&mut self, handle: Handle, point: DVec3) -> CmdResult { if handle.is_null() { + if matches!(self.step, Step::Vertex) { + self.selecting_object = false; + self.step = Step::FirstRay(point); + } return CmdResult::NeedPoint; } let Some(entity) = self.picked_entity.take() else { @@ -360,13 +604,42 @@ impl CadCommand for AngularDimensionCommand { let Some(curve) = picked_curve(&entity, point) else { return CmdResult::NeedPoint; }; + if !curve_is_coplanar(&curve, self.plane) { + return CmdResult::NeedPoint; + } match (&self.step, curve) { ( - Step::SecondLine { first_start, first_end, first_source }, - PickedCurve::Line(second_start, second_end), - ) if *first_source != handle => { - self.source_handles = vec![*first_source, *first_source, handle, handle]; + Step::SecondLine { + first_start, + first_end, + first_source, + first_refs, + }, + PickedCurve::Line { + start: second_start, + end: second_end, + refs: second_refs, + .. + }, + ) => { + if (*first_source == handle && *first_refs == second_refs) + || lines_parallel_in_plane( + self.plane, + *first_start, + *first_end, + second_start, + second_end, + ) + { + return CmdResult::NeedPoint; + } + self.source_refs = vec![ + Some(first_refs[0].bind(*first_source)), + Some(first_refs[1].bind(*first_source)), + Some(second_refs[0].bind(handle)), + Some(second_refs[1].bind(handle)), + ]; self.selecting_object = false; self.step = Step::ArcPoint2 { first_start: *first_start, @@ -376,29 +649,49 @@ impl CadCommand for AngularDimensionCommand { }; CmdResult::NeedPoint } - (Step::Vertex, PickedCurve::Line(first_start, first_end)) => { + ( + Step::Vertex, + PickedCurve::Line { + start: first_start, + end: first_end, + refs, + .. + }, + ) => { self.step = Step::SecondLine { first_start, first_end, first_source: handle, + first_refs: refs, }; CmdResult::NeedPoint } - (Step::Vertex, PickedCurve::Arc { center, first, second }) => { - self.source_handles = vec![handle, handle, handle]; + ( + Step::Vertex, + PickedCurve::Arc { + center, + first, + second, + refs, + .. + }, + ) => { + self.source_refs = refs + .into_iter() + .map(|reference| Some(reference.bind(handle))) + .collect(); self.selecting_object = false; self.step = Step::ArcPoint3 { vertex: center, first, second }; CmdResult::NeedPoint } - (Step::Vertex, PickedCurve::Circle { center, radius }) => { - let Some(first) = project_to_radius(center, point, radius) else { + (Step::Vertex, PickedCurve::Circle { center, .. }) => { + if point.distance_squared(center) <= 1.0e-24 { return CmdResult::NeedPoint; - }; + } self.selecting_object = false; self.step = Step::CircleSecondRay { vertex: center, - first, - radius, + first: point, source: handle, }; CmdResult::NeedPoint @@ -408,29 +701,63 @@ impl CadCommand for AngularDimensionCommand { } fn on_mouse_move(&mut self, point: DVec3) -> Option { + if self.awaiting_angle { + return self + .angle_origin + .map(|origin| preview_wire(vec![origin, point])); + } let points = match self.step { Step::Vertex | Step::SecondLine { .. } => return None, Step::FirstRay(vertex) => vec![vertex, point], Step::SecondRay { vertex, first } => vec![vertex, first, nan(), vertex, point], - Step::CircleSecondRay { vertex, first, radius, .. } => { - let second = project_to_radius(vertex, point, radius).unwrap_or(point); - vec![vertex, first, nan(), vertex, second] + Step::CircleSecondRay { vertex, first, .. } => { + vec![vertex, first, nan(), vertex, point] } Step::ArcPoint3 { vertex, first, second } => { + let vertex = self.plane.to_local(vertex); + let first = self.plane.to_local(first); + let second = self.plane.to_local(second); + let point = locked_arc_point( + vertex, + self.plane.to_local(point), + self.quadrant_lock, + ); angular_preview(vertex, first, second, point) + .into_iter() + .map(|value| if value.is_nan() { value } else { self.plane.to_world(value) }) + .collect() } Step::ArcPoint2 { first_start, first_end, second_start, second_end, - } => two_line_preview( - first_start, - first_end, - second_start, - second_end, - point, - ), + } => { + let first_start = self.plane.to_local(first_start); + let first_end = self.plane.to_local(first_end); + let second_start = self.plane.to_local(second_start); + let second_end = self.plane.to_local(second_end); + let point = self.plane.to_local(point); + let point = two_line_frame( + first_start, + first_end, + second_start, + second_end, + point, + ) + .map(|(vertex, _, _)| locked_arc_point(vertex, point, self.quadrant_lock)) + .unwrap_or(point); + two_line_preview( + first_start, + first_end, + second_start, + second_end, + point, + ) + .into_iter() + .map(|value| if value.is_nan() { value } else { self.plane.to_world(value) }) + .collect() + } }; Some(preview_wire(points)) } @@ -438,24 +765,43 @@ impl CadCommand for AngularDimensionCommand { fn picked_curve(entity: &EntityType, click: DVec3) -> Option { let point = |value: Vector3| DVec3::new(value.x, value.y, value.z); + let normal = |value: Vector3| DVec3::new(value.x, value.y, value.z); match entity { - EntityType::Line(line) => Some(PickedCurve::Line(point(line.start), point(line.end))), + EntityType::Line(line) => { + let start = point(line.start); + let end = point(line.end); + (start.distance_squared(end) > 1.0e-24).then_some(PickedCurve::Line { + start, + end, + refs: [SourceLocator::INFERRED; 2], + normal: None, + }) + } EntityType::Arc(arc) => Some(PickedCurve::Arc { center: point(arc.center_wcs()), first: point(arc.start_point_wcs()), second: point(arc.end_point_wcs()), + refs: [SourceLocator::INFERRED; 3], + normal: normal(arc.normal), }), EntityType::Circle(circle) => Some(PickedCurve::Circle { center: point(circle.center_wcs()), - radius: circle.radius, + normal: normal(circle.normal), }), EntityType::LwPolyline(polyline) => { let click = crate::scene::view::transform::wcs_point_to_ocs( (click.x, click.y, click.z), (polyline.normal.x, polyline.normal.y, polyline.normal.z), ); + let points: Vec<_> = polyline + .vertices + .iter() + .map(|vertex| [vertex.location.x, vertex.location.y]) + .collect(); + let bulges: Vec<_> = polyline.vertices.iter().map(|vertex| vertex.bulge).collect(); let segment = nearest_segment_index( - polyline.vertices.iter().map(|vertex| [vertex.location.x, vertex.location.y]).collect(), + &points, + &bulges, polyline.is_closed, [click.0, click.1], )?; @@ -467,17 +813,24 @@ fn picked_curve(entity: &EntityType, click: DVec3) -> Option { first.bulge, polyline.elevation, polyline.normal, + segment, + polyline.vertices.len(), ) } EntityType::Polyline2D(polyline) => { - let vertices = crate::entities::polyline::drawn_vertices2d(polyline) - .unwrap_or_else(|| polyline.vertices.clone()); + let vertices = &polyline.vertices; let click = crate::scene::view::transform::wcs_point_to_ocs( (click.x, click.y, click.z), (polyline.normal.x, polyline.normal.y, polyline.normal.z), ); + let points: Vec<_> = vertices + .iter() + .map(|vertex| [vertex.location.x, vertex.location.y]) + .collect(); + let bulges: Vec<_> = vertices.iter().map(|vertex| vertex.bulge).collect(); let segment = nearest_segment_index( - vertices.iter().map(|vertex| [vertex.location.x, vertex.location.y]).collect(), + &points, + &bulges, polyline.is_closed(), [click.0, click.1], )?; @@ -489,27 +842,86 @@ fn picked_curve(entity: &EntityType, click: DVec3) -> Option { first.bulge, polyline.elevation, polyline.normal, + segment, + vertices.len(), ) } _ => None, } } -fn nearest_segment_index(points: Vec<[f64; 2]>, closed: bool, click: [f64; 2]) -> Option { +fn nearest_segment_index( + points: &[[f64; 2]], + bulges: &[f64], + closed: bool, + click: [f64; 2], +) -> Option { if points.len() < 2 { return None; } let count = if closed { points.len() } else { points.len() - 1 }; (0..count).min_by(|first, second| { - segment_distance_squared(points[*first], points[(*first + 1) % points.len()], click) - .total_cmp(&segment_distance_squared( + polyline_segment_distance_squared( + points[*first], + points[(*first + 1) % points.len()], + bulges.get(*first).copied().unwrap_or(0.0), + click, + ) + .total_cmp(&polyline_segment_distance_squared( points[*second], points[(*second + 1) % points.len()], + bulges.get(*second).copied().unwrap_or(0.0), click, )) }) } +fn bulge_center(first: [f64; 2], second: [f64; 2], bulge: f64) -> Option<[f64; 2]> { + if bulge.abs() <= 1.0e-12 { + return None; + } + let dx = second[0] - first[0]; + let dy = second[1] - first[1]; + let chord = dx.hypot(dy); + if chord <= 1.0e-12 { + return None; + } + let midpoint = [(first[0] + second[0]) * 0.5, (first[1] + second[1]) * 0.5]; + let offset = chord * (1.0 - bulge * bulge) / (4.0 * bulge); + Some([ + midpoint[0] - dy / chord * offset, + midpoint[1] + dx / chord * offset, + ]) +} + +fn polyline_segment_distance_squared( + first: [f64; 2], + second: [f64; 2], + bulge: f64, + point: [f64; 2], +) -> f64 { + let Some(center) = bulge_center(first, second, bulge) else { + return segment_distance_squared(first, second, point); + }; + let radius = (first[0] - center[0]).hypot(first[1] - center[1]); + let start = (first[1] - center[1]).atan2(first[0] - center[0]); + let target = (point[1] - center[1]).atan2(point[0] - center[0]); + let sweep = 4.0 * bulge.atan(); + let into = if sweep >= 0.0 { + (target - start).rem_euclid(std::f64::consts::TAU) + } else { + (start - target).rem_euclid(std::f64::consts::TAU) + }; + if into <= sweep.abs() + 1.0e-12 { + let radial = (point[0] - center[0]).hypot(point[1] - center[1]); + (radial - radius).powi(2) + } else { + ((point[0] - first[0]).powi(2) + (point[1] - first[1]).powi(2)).min( + (point[0] - second[0]).powi(2) + (point[1] - second[1]).powi(2), + ) + } +} + fn segment_distance_squared(first: [f64; 2], second: [f64; 2], point: [f64; 2]) -> f64 { let dx = second[0] - first[0]; let dy = second[1] - first[1]; @@ -530,6 +942,8 @@ fn polyline_segment( bulge: f64, elevation: f64, normal: Vector3, + segment: usize, + vertex_count: usize, ) -> Option { let to_world = |point: [f64; 2]| { let value = crate::scene::view::transform::ocs_point_to_wcs( @@ -540,31 +954,95 @@ fn polyline_segment( }; let first_world = to_world(first); let second_world = to_world(second); - if bulge.abs() <= 1.0e-12 { - return Some(PickedCurve::Line(first_world, second_world)); - } - let dx = second[0] - first[0]; - let dy = second[1] - first[1]; - let chord = (dx * dx + dy * dy).sqrt(); - if chord <= 1.0e-12 { + if first_world.distance_squared(second_world) <= 1.0e-24 { return None; } - let midpoint = [(first[0] + second[0]) * 0.5, (first[1] + second[1]) * 0.5]; - let center_offset = chord * (1.0 - bulge * bulge) / (4.0 * bulge); - let center = [ - midpoint[0] - dy / chord * center_offset, - midpoint[1] + dx / chord * center_offset, + let refs = [ + SourceLocator::explicit(segment as i32, 0.0), + SourceLocator::explicit(((segment + 1) % vertex_count) as i32, 0.0), ]; + let normal_world = DVec3::new(normal.x, normal.y, normal.z); + if bulge.abs() <= 1.0e-12 { + return Some(PickedCurve::Line { + start: first_world, + end: second_world, + refs, + normal: Some(normal_world), + }); + } + let center = bulge_center(first, second, bulge)?; Some(PickedCurve::Arc { center: to_world(center), first: first_world, second: second_world, + refs: [ + SourceLocator::explicit(-4, segment as f64), + refs[0], + refs[1], + ], + normal: normal_world, }) } -fn project_to_radius(center: DVec3, point: DVec3, radius: f64) -> Option { - let direction = (point - center).normalize_or_zero(); - (direction.length_squared() > 0.0).then_some(center + direction * radius) +fn curve_is_coplanar(curve: &PickedCurve, plane: WorkingPlane) -> bool { + let (points, normal): (Vec, Option) = match curve { + PickedCurve::Line { start, end, normal, .. } => (vec![*start, *end], *normal), + PickedCurve::Arc { center, first, second, normal, .. } => { + (vec![*center, *first, *second], Some(*normal)) + } + PickedCurve::Circle { center, normal } => (vec![*center], Some(*normal)), + }; + if let Some(normal) = normal { + let alignment = normal.normalize_or_zero().dot(plane.z).abs(); + if alignment < 1.0 - 1.0e-7 { + return false; + } + } + let local: Vec<_> = points.into_iter().map(|point| plane.to_local(point)).collect(); + let min_z = local.iter().map(|point| point.z).fold(f64::INFINITY, f64::min); + let max_z = local.iter().map(|point| point.z).fold(f64::NEG_INFINITY, f64::max); + let scale = local + .iter() + .map(|point| point.x.abs().max(point.y.abs()).max(1.0)) + .fold(1.0, f64::max); + max_z - min_z <= 1.0e-9 * scale +} + +fn lines_parallel_in_plane( + plane: WorkingPlane, + first_start: DVec3, + first_end: DVec3, + second_start: DVec3, + second_end: DVec3, +) -> bool { + let first = plane.vector_to_local(first_end - first_start); + let second = plane.vector_to_local(second_end - second_start); + let denominator = first.x * second.y - first.y * second.x; + denominator.abs() <= 1.0e-12 * first.length().max(second.length()).max(1.0) +} + +fn locked_arc_point( + vertex: DVec3, + point: DVec3, + frame: Option<(f64, f64)>, +) -> DVec3 { + let Some((start, end)) = frame else { return point }; + let radius = ((point.x - vertex.x).powi(2) + (point.y - vertex.y).powi(2)).sqrt(); + if radius <= 1.0e-12 { + return point; + } + let angle = (start + end) * 0.5; + DVec3::new( + vertex.x + angle.cos() * radius, + vertex.y + angle.sin() * radius, + vertex.z, + ) +} + +fn point_angle_in_frame(vertex: DVec3, point: DVec3, frame: (f64, f64)) -> bool { + let angle = (point.y - vertex.y).atan2(point.x - vertex.x); + let sweep = frame.1 - frame.0; + (angle - frame.0).rem_euclid(std::f64::consts::TAU) <= sweep + 1.0e-9 } fn two_line_frame( diff --git a/src/scene/dimension_assoc.rs b/src/scene/dimension_assoc.rs index 853d40092..4918550f0 100644 --- a/src/scene/dimension_assoc.rs +++ b/src/scene/dimension_assoc.rs @@ -6,6 +6,8 @@ use acadrust::objects::{ use acadrust::types::{Handle, Vector3}; use acadrust::EntityType; +use crate::command::DimensionAssociationSource; + use super::{ChangeKind, Scene}; fn point_distance_squared(first: Vector3, second: Vector3) -> f64 { @@ -23,6 +25,62 @@ fn ocs_point(x: f64, y: f64, elevation: f64, normal: Vector3) -> Vector3 { Vector3::new(point.0, point.1, point.2) } +fn bulge_center_world( + first: [f64; 2], + second: [f64; 2], + bulge: f64, + elevation: f64, + normal: Vector3, +) -> Option { + if bulge.abs() <= 1.0e-12 { + return None; + } + let dx = second[0] - first[0]; + let dy = second[1] - first[1]; + let chord = dx.hypot(dy); + if chord <= 1.0e-12 { + return None; + } + let midpoint = [(first[0] + second[0]) * 0.5, (first[1] + second[1]) * 0.5]; + let offset = chord * (1.0 - bulge * bulge) / (4.0 * bulge); + Some(ocs_point( + midpoint[0] - dy / chord * offset, + midpoint[1] + dx / chord * offset, + elevation, + normal, + )) +} + +fn polyline_arc_center(entity: &EntityType, segment: usize) -> Option { + match entity { + EntityType::LwPolyline(polyline) => { + let count = polyline.vertices.len(); + let first = *polyline.vertices.get(segment)?; + let second = *polyline.vertices.get((segment + 1) % count)?; + bulge_center_world( + [first.location.x, first.location.y], + [second.location.x, second.location.y], + first.bulge, + polyline.elevation, + polyline.normal, + ) + } + EntityType::Polyline2D(polyline) => { + let count = polyline.vertices.len(); + let first = polyline.vertices.get(segment)?; + let second = polyline.vertices.get((segment + 1) % count)?; + bulge_center_world( + [first.location.x, first.location.y], + [second.location.x, second.location.y], + first.bulge, + polyline.elevation, + polyline.normal, + ) + } + _ => None, + } +} + fn source_points(entity: &EntityType) -> Vec { match entity { EntityType::Line(line) => vec![line.start, line.end], @@ -101,6 +159,10 @@ fn source_marker(entity: &EntityType, point: Vector3) -> Option { fn resolve_reference(scene: &Scene, reference: &AssocDimensionReference) -> Option { let source = *reference.xrefs.first()?; let entity = scene.document.get_entity(source)?; + if reference.main_gs_marker == -4 { + let segment = reference.osnap_distance.round().max(0.0) as usize; + return polyline_arc_center(entity, segment); + } if reference.main_gs_marker == -3 { return match entity { EntityType::Circle(circle) => Some(circle.center_wcs()), @@ -167,6 +229,20 @@ impl Scene { &mut self, dimension: Handle, sources: Vec>, + ) { + self.attach_dimension_association_sources( + dimension, + sources + .into_iter() + .map(|source| source.map(DimensionAssociationSource::inferred)) + .collect(), + ); + } + + pub(crate) fn attach_dimension_association_sources( + &mut self, + dimension: Handle, + sources: Vec>, ) { let Some(EntityType::Dimension(dimension_entity)) = self.document.get_entity(dimension) @@ -182,9 +258,14 @@ impl Scene { .enumerate() .map(|(index, point)| { let source = sources.get(index).copied().flatten()?; - let entity = self.document.get_entity(source)?; - source_reference(entity, *point) - .map(|(marker, parameter)| (source, marker, parameter)) + let (marker, parameter) = match source.marker { + Some(marker) => (marker, source.parameter), + None => { + let entity = self.document.get_entity(source.handle)?; + source_reference(entity, *point)? + } + }; + Some((source.handle, marker, parameter)) }) .collect(); if resolved.iter().all(Option::is_none) { @@ -229,7 +310,7 @@ impl Scene { .insert(association_handle, ObjectType::Associative(object)); let mut reactor_targets = vec![dimension]; - reactor_targets.extend(sources.into_iter().flatten()); + reactor_targets.extend(sources.into_iter().flatten().map(|source| source.handle)); reactor_targets.sort_by_key(|handle| handle.value()); reactor_targets.dedup(); for handle in reactor_targets { From 6bbef80a2687d6a0da3d02f32e0a2db13f219f4d Mon Sep 17 00:00:00 2001 From: ramox81 <184937705+ramox81@users.noreply.github.com> Date: Tue, 25 Aug 2026 12:23:29 +0300 Subject: [PATCH 5/5] Complete angular dimension layout and fitting --- src/entities/dimension.rs | 234 +++++++++++++++++++++++++++++++++++--- 1 file changed, 216 insertions(+), 18 deletions(-) diff --git a/src/entities/dimension.rs b/src/entities/dimension.rs index 0e0d8123a..0314a2f70 100644 --- a/src/entities/dimension.rs +++ b/src/entities/dimension.rs @@ -1095,6 +1095,14 @@ fn dimension_line_grip_position(dim: &Dimension) -> Option { } fn above_dimension_text_position(dim: &Dimension) -> Option { + if let Some((vertex, start, end, radius)) = angular_dimension_frame(dim) { + let angle = (start + end) * 0.5; + let direction = DVec3::new(angle.cos() as f64, angle.sin() as f64, 0.0); + return Some( + DVec3::new(vertex.x as f64, vertex.y as f64, vertex.z as f64) + + direction * (radius as f64 + 1.0), + ); + } let center = dimension_line_grip_position(dim)?; let (ax, ay) = match dim { Dimension::Linear(d) => (d.rotation.cos(), d.rotation.sin()), @@ -2524,7 +2532,7 @@ use acadrust::{CadDocument, EntityType, Handle}; use crate::scene::convert::tess_util::aci_to_rgba; use crate::scene::convert::tessellate::{ - add_polyline, add_segment, append_arrow, arrow_from_block_with_deferred_hatch, + add_segment, append_arrow, arrow_from_block_with_deferred_hatch, normalized_or, ArrowKind, DimGeom, }; use crate::scene::model::wire_model::{SnapHint, WireModel}; @@ -4056,6 +4064,43 @@ fn two_line_angle_frame( Some((vertex, start, end)) } +fn angular_dimension_frame(dim: &Dimension) -> Option<(Vec3, f32, f32, f32)> { + let (vertex, start, end, arc_point) = match dim { + Dimension::Angular2Ln(value) => { + let first_start = vec3_local(value.first_point); + let first_end = vec3_local(value.second_point); + let second_start = vec3_local(value.angle_vertex); + let second_end = vec3_local(value.definition_point); + let stored_arc = if value.dimension_arc.length_squared() > 1.0e-18 { + value.dimension_arc + } else { + value.base.definition_point + }; + let arc_point = vec3_local(stored_arc); + let (vertex, start, end) = two_line_angle_frame( + first_start, + first_end, + second_start, + second_end, + arc_point, + )?; + (vertex, start, end, arc_point) + } + Dimension::Angular3Pt(value) => { + let vertex = vec3_local(value.angle_vertex); + let first = vec3_local(value.first_point); + let second = vec3_local(value.second_point); + let arc_point = vec3_local(value.definition_point); + let (vertex, start, end) = + two_line_angle_frame(vertex, first, vertex, second, arc_point)?; + (vertex, start, end, arc_point) + } + _ => return None, + }; + let radius = vertex.distance(arc_point); + (radius > 1.0e-6).then_some((vertex, start, end, radius)) +} + fn append_angular_dimension( g: &mut DimGeom, vertex: Vec3, @@ -4121,11 +4166,22 @@ fn append_angular_dimension( delta = end - start; } - let arc_extension = if params.ticks && radius > 1.0e-6 { - params.dimdle / radius + let arc_length = radius * delta.abs(); + let arrows_outside = if params.ticks || params.arrow_len <= 1.0e-6 { + false + } else if arc_length < params.arrow_len * 2.0 { + true + } else if arc_length < params.text_width + params.arrow_len * 2.0 { + match params.dimatfit { + 0 | 1 => true, + 2 => false, + _ => params.text_width <= arc_length, + } } else { - 0.0 + false }; + let draw_inside_line = !arrows_outside || params.dimtofl; + let arc_extension = if params.ticks { params.dimdle / radius } else { 0.0 }; let direction = delta.signum(); let draw_start = start - direction * arc_extension; let draw_delta = delta + direction * arc_extension * 2.0; @@ -4133,34 +4189,119 @@ fn append_angular_dimension( let mut arc_pts = Vec::with_capacity((steps + 1) as usize); for i in 0..=steps { let t = i as f32 / steps as f32; - let a = draw_start + draw_delta * t; - arc_pts.push(vertex + Vec3::new(a.cos() * radius, a.sin() * radius, 0.0)); + let angle = draw_start + draw_delta * t; + arc_pts.push(vertex + Vec3::new(angle.cos() * radius, angle.sin() * radius, 0.0)); } - let midpoint = arc_pts.len() / 2; - if !suppress.dim1 && midpoint > 0 { - add_polyline(&mut g.dim_lines, &arc_pts[..=midpoint]); - } - if !suppress.dim2 && midpoint + 1 < arc_pts.len() { - add_polyline(&mut g.dim_lines, &arc_pts[midpoint..]); + if draw_inside_line { + for index in 0..steps as usize { + let t = (index as f32 + 0.5) / steps as f32; + if (t < 0.5 && suppress.dim1) || (t >= 0.5 && suppress.dim2) { + continue; + } + let a = arc_pts[index]; + let b = arc_pts[index + 1]; + let hidden_by_text = params.text_break.is_some_and(|(center, half_width, half_height)| { + let angle = draw_start + draw_delta * t; + let radial = Vec3::new(angle.cos(), angle.sin(), 0.0); + let tangent = Vec3::new(-angle.sin(), angle.cos(), 0.0); + let offset = center - (a + b) * 0.5; + offset.dot(tangent).abs() <= half_width + && offset.dot(radial).abs() <= half_height + }); + if !hidden_by_text { + add_segment(&mut g.dim_lines, a, b); + } + } } - if arc_pts.len() >= 2 { + if arrows_outside && !params.dimsoxd { + let stub_angle = (params.arrow_len * 2.0 / radius).min(std::f32::consts::FRAC_PI_2); + if !suppress.dim1 { + append_sampled_arc( + &mut g.dim_lines, + vertex, + radius, + start - direction * stub_angle, + start, + ); + } + if !suppress.dim2 { + append_sampled_arc( + &mut g.dim_lines, + vertex, + radius, + end, + end + direction * stub_angle, + ); + } + } + + if let Some((text_center, half_width, _)) = params.text_break { + let text_angle = (text_center.y - vertex.y).atan2(text_center.x - vertex.x); + let into = (text_angle - start).rem_euclid(std::f32::consts::TAU); + if into > delta.abs() + 1.0e-6 { + let back_to_start = (start - text_angle).rem_euclid(std::f32::consts::TAU); + let forward_from_end = (text_angle - end).rem_euclid(std::f32::consts::TAU); + let text_gap = (half_width / radius).min(std::f32::consts::FRAC_PI_2); + if back_to_start <= forward_from_end && !suppress.dim1 { + append_sampled_arc( + &mut g.dim_lines, + vertex, + radius, + text_angle + text_gap, + start, + ); + } else if !suppress.dim2 { + append_sampled_arc( + &mut g.dim_lines, + vertex, + radius, + end, + text_angle - text_gap, + ); + } + } + } + + let start_tangent = Vec3::new(-start.sin(), start.cos(), 0.0) * direction; + let end_tangent = Vec3::new(-end.sin(), end.cos(), 0.0) * direction; + let draw_arrows = !arrows_outside || !params.dimsoxd; + if draw_arrows && !suppress.dim1 { append_arrow( g, - arc_pts[0], - normalized_or(arc_pts[1] - arc_pts[0], Vec3::X), + arc_start, + if arrows_outside { -start_tangent } else { start_tangent }, arrow1, ); - let n = arc_pts.len(); + } + if draw_arrows && !suppress.dim2 { append_arrow( g, - arc_pts[n - 1], - normalized_or(arc_pts[n - 2] - arc_pts[n - 1], Vec3::X), + arc_end, + if arrows_outside { end_tangent } else { -end_tangent }, arrow2, ); } } +fn append_sampled_arc( + lines: &mut Vec<[f32; 3]>, + vertex: Vec3, + radius: f32, + start: f32, + end: f32, +) { + let steps = angular_arc_steps(end - start); + let mut previous = vertex + Vec3::new(start.cos() * radius, start.sin() * radius, 0.0); + for index in 1..=steps { + let t = index as f32 / steps as f32; + let angle = start + (end - start) * t; + let next = vertex + Vec3::new(angle.cos() * radius, angle.sin() * radius, 0.0); + add_segment(lines, previous, next); + previous = next; + } +} + fn angular_arc_steps(sweep: f32) -> u32 { ((sweep.abs() / std::f32::consts::PI * 90.0).ceil() as u32).clamp(8, 720) } @@ -4422,6 +4563,32 @@ fn dimension_text_is_outside(dim: &Dimension, style: Option<&DimStyle>) -> bool let Some(style) = style else { return false; }; + if let Some((vertex, start, end, radius)) = angular_dimension_frame(dim) { + if dim.base().text_user_positioned { + let text = vec3_local(dim.base().text_middle_point); + let angle = (text.y - vertex.y).atan2(text.x - vertex.x); + return (angle - start).rem_euclid(std::f32::consts::TAU) + > end - start + 1.0e-6; + } + if style.dimtix { + return false; + } + let scale = if style.dimscale > 1e-9 { style.dimscale } else { 1.0 }; + let height = style.dimtxt * scale; + let gap = style.dimgap.abs() * scale; + let text_width = dimension_text_value(dim, Some(style)) + .map(|value| value.chars().count() as f64 * height * 0.6 + gap * 2.0) + .unwrap_or(0.0); + let arrow = style.dimasz * scale; + let span = radius as f64 * (end - start).abs() as f64; + let insufficient = text_width + arrow * 2.0 > span; + return insufficient + && match style.dimatfit { + 0 | 2 => true, + 1 | 3 => text_width > span, + _ => text_width > span, + }; + } let (first, second, axis) = match dim { Dimension::Linear(d) => ( d.first_point, @@ -4472,6 +4639,11 @@ fn dimension_text_natural_rotation(dim: &Dimension) -> f64 { let dy = d.second_point.y - d.first_point.y; dy.atan2(dx) } + Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_) => angular_dimension_frame(dim) + .map(|(_, start, end, _)| { + ((start + end) * 0.5 + std::f32::consts::FRAC_PI_2) as f64 + }) + .unwrap_or(0.0), _ => 0.0, }; // Clamp to (-π/2, π/2] so text never appears upside-down. @@ -5245,6 +5417,32 @@ fn dimension_text_pos_f64( dimtad, ) } + Dimension::Angular2Ln(_) | Dimension::Angular3Pt(_) => { + let Some((vertex, start, end, radius)) = angular_dimension_frame(dim) else { + return base.text_middle_point; + }; + let span = radius as f64 * (end - start).abs() as f64; + let insufficient = text_w + arrow * 2.0 > span; + let move_outside = !dimtix + && insufficient + && match dimatfit { + 0 | 2 => true, + 1 | 3 => text_w > span, + _ => text_w > span, + }; + let angle = if move_outside { + end as f64 + (text_w * 0.5 + dimgap + arrow) / (radius as f64).max(1.0e-12) + } else { + ((start + end) * 0.5) as f64 + }; + let radial_offset = if dimtad == 4 { -perp_off } else { perp_off }; + let text_radius = (radius as f64 + radial_offset).max(0.0); + Vector3::new( + vertex.x as f64 + angle.cos() * text_radius, + vertex.y as f64 + angle.sin() * text_radius, + vertex.z as f64, + ) + } _ => { // Non-linear (radius / diameter / angular / ordinate): lift the // natural mid point straight up by the style offset. A user-dragged