diff --git a/crates/doc/src/drawing/dimension.rs b/crates/doc/src/drawing/dimension.rs index c2f2bb46a..f807ca91c 100644 --- a/crates/doc/src/drawing/dimension.rs +++ b/crates/doc/src/drawing/dimension.rs @@ -72,6 +72,27 @@ use crate::{ DocError, Document, MAX_PLACEMENT_DEPTH, Mat, Model, ModelBody, ModelState, Result, apply_point, apply_vector, ids, map_plane, mat_inverse, }; +/// What a reading's number is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LabelKind { + Length, + Angle, + Radius, + Diameter, +} + +/// What a reading says: `value`, in model millimetres or radians for an angle, in `units` with +/// `decimals`. The one rule for a dimension's text and a view's measurements. +pub fn reading_label(kind: LabelKind, value: f64, units: &str, decimals: u8) -> String { + let length = || length_number(value, units, decimals); + match kind { + LabelKind::Length => length(), + LabelKind::Angle => format!("{:.*}°", usize::from(decimals), value.to_degrees()), + LabelKind::Radius => format!("R{}", length()), + LabelKind::Diameter => format!("{DIAMETER_SIGN}{}", length()), + } +} + /// The most dimensions a drawing may have. pub const MAX_DIMENSIONS: usize = 10_000; /// The most decimals a dimension shows. @@ -515,6 +536,13 @@ impl Document { } } + /// The radius of the circle or arc `edge` names, on `model` (this design's), as the view through + /// `basis` sees it face on, and whether it was found exactly. + pub fn radius_on_view(&self, model: &Model, edge: &ModelEdge, basis: &Plane) -> std::result::Result<(f64, bool), Status> { + let (radius, _, exact) = Lookup::new(self, model).whole_arc(edge, basis)?; + Ok((radius, exact)) + } + /// The units `drawing` (one of this design's drawings) shows its numbers in. pub fn drawing_units<'a>(&'a self, drawing: &'a Drawing) -> &'a str { match &drawing.units { @@ -617,15 +645,15 @@ impl<'a> Lookup<'a> { }; let measured = found.as_ref().map(|f| f.measured); let length = |m: Measured| length_number(m.value, units, d.decimals); - let number = |m: Measured| match d.kind { - DimensionKind::Angle { .. } => Some(format!("{:.*}°", usize::from(d.decimals), m.value.to_degrees())), - DimensionKind::Radial { diameter, .. } => { - let symbol = if diameter { DIAMETER_SIGN } else { "R" }; - Some(format!("{symbol}{}", length(m))) - } - DimensionKind::Chain { .. } => None, - DimensionKind::Cylinder { .. } => Some(format!("{DIAMETER_SIGN}{}", length(m))), - _ => Some(length(m)), + let number = |m: Measured| { + let kind = match d.kind { + DimensionKind::Angle { .. } => LabelKind::Angle, + DimensionKind::Radial { diameter: false, .. } => LabelKind::Radius, + DimensionKind::Radial { diameter: true, .. } | DimensionKind::Cylinder { .. } => LabelKind::Diameter, + DimensionKind::Chain { .. } => return None, + _ => LabelKind::Length, + }; + Some(reading_label(kind, m.value, units, d.decimals)) }; let (members, points, exact) = found.map_or_else(Default::default, |f| (f.members, f.points, f.exact)); Resolved { @@ -668,15 +696,10 @@ impl<'a> Lookup<'a> { Ok(Found { measured: Measured { value, ..between }, members: Vec::new(), points, exact: exact_a && exact_b }) } DimensionKind::Radial { edge, diameter } => { - let found = self.edges(edge)?; - // A split edge is several arcs, each drawn in its own place. - if !found.whole { - return Err(Status::Ambiguous(edge_candidates(&edge.body, &found))); - } - let (radius, points) = self.arc(edge, &found, basis)?; + let (radius, points, exact) = self.whole_arc(edge, basis)?; let value = if *diameter { 2.0 * radius } else { radius }; let measured = Measured { value, foreshortened: false }; - Ok(Found { measured, members: Vec::new(), points: points.to_vec(), exact: found.exact }) + Ok(Found { measured, members: Vec::new(), points: points.to_vec(), exact }) } DimensionKind::Chain { points, direction } => { let found = points.iter().map(|p| self.corner(p)).collect::, _>>()?; @@ -715,26 +738,44 @@ impl<'a> Lookup<'a> { Ok(self.named.entry(i).or_insert_with(|| BodyEdges::new(b))) } - /// The edges `edge` names: the one edge, or the pieces of it. + /// The edges `edge` names: the one edge, or the pieces of it. One piece is that edge, though not + /// found exactly: a name saved from a split face finds it on a body with the one face. pub(super) fn edges(&mut self, edge: &ModelEdge) -> std::result::Result { let (i, frame) = self.body(&edge.body, edge.origin_feature, &edge.path)?; let names = self.names(i)?; - let (indices, whole) = match names.matching(&edge.name) { + let (indices, named) = match names.matching(&edge.name) { Some(EdgeMatch::Edge(e)) => (vec![e], true), Some(EdgeMatch::Pieces(pieces)) => (pieces, false), None => return Err(Status::Lost(format!("edge `{}` no longer exists", edge.name))), }; - let exact = whole && indices.iter().all(|e| names.verified(*e)); + let whole = named || indices.len() == 1; + let exact = named && indices.iter().all(|e| names.verified(*e)); let placed = |e: &usize| names.mesh.edges.get(*e).map(|line| (*e, line.iter().map(|p| apply_point(&frame, *p)).collect())); Ok(Edges { pieces: indices.iter().filter_map(placed).collect(), whole, exact, body: i, frame }) } - /// The circle or arc that `found` (one whole edge) is, as the view through `basis` sees it face - /// on: its radius, and its centre and its start, middle and end in the design's frame. Read - /// exactly from the body, in the view's plane through the edge, so the points are the edge's. - fn arc(&self, edge: &ModelEdge, found: &Edges, basis: &Plane) -> std::result::Result<(f64, [Vec3; 4]), Status> { + /// The circle or arc `edge` names, as [`Lookup::arc`] reads it, and whether it was found exactly. + /// The pieces of a split edge on one circle are still that circle, as [`Lookup::line`] keeps a + /// line: read from the longest, so its points lie on what is left of it. Pieces on several + /// circles are listed, and none is chosen. + fn whole_arc(&mut self, edge: &ModelEdge, basis: &Plane) -> std::result::Result<(f64, [Vec3; 4], bool), Status> { + let found = self.edges(edge)?; + if !found.whole && one_circle(&found.pieces).is_none() { + return Err(Status::Ambiguous(edge_candidates(&edge.body, &found))); + } + let length = |line: &[Vec3]| line.windows(2).map(|w| w.first().zip(w.last()).map_or(0.0, |(a, b)| a.dist(*b))).sum::(); + let longest = found.pieces.iter().max_by(|a, b| length(&a.1).total_cmp(&length(&b.1))); + let not_found = || Status::Lost(format!("edge `{}` no longer exists", edge.name)); + let (radius, points) = self.arc(edge, &found, longest.ok_or_else(not_found)?, basis)?; + Ok((radius, points, found.exact)) + } + + /// The circle or arc that `piece` of `found` is, as the view through `basis` sees it face on: + /// its radius, and its centre and its start, middle and end in the design's frame. Read exactly + /// from the body, in the view's plane through the edge, so the points are the edge's. + fn arc(&self, edge: &ModelEdge, found: &Edges, piece: &(usize, Vec), basis: &Plane) -> std::result::Result<(f64, [Vec3; 4]), Status> { let face_on = || Status::Unmeasurable(format!("edge `{}` isn't a circle in this view (it isn't parallel to it)", edge.name)); - let (index, line) = found.pieces.first().ok_or_else(face_on)?; + let (index, line) = piece; let through = Plane { origin: *line.first().ok_or_else(face_on)?, ..*basis }; let local = mat_inverse(&found.frame).and_then(|back| map_plane(&back, &through)).ok_or_else(face_on)?; let body = self.state.bodies.get(found.body).ok_or_else(|| Status::Lost("its body no longer exists".into()))?; @@ -786,19 +827,17 @@ impl<'a> Lookup<'a> { } } - /// The centre `point` names: of the circle or arc its one named edge is, whole, as construction - /// geometry finds a round edge's ([`as_circle`]). + /// The centre `point` names: of the circle or arc its one named edge is, or the one circle its + /// pieces lie on, as construction geometry finds a round edge's ([`as_circle`]). fn centre(&mut self, point: &ModelPoint) -> std::result::Result<(Vec3, bool), Status> { let name = point.edges.first().ok_or_else(|| Status::Lost("its centre names no edge".into()))?; let edge = ModelEdge { body: point.body.clone(), origin_feature: point.origin_feature, name: name.clone(), path: point.path.clone() }; let found = self.edges(&edge)?; - // A split edge is several arcs. - if !found.whole { - return Err(Status::Ambiguous(edge_candidates(&edge.body, &found))); + match one_circle(&found.pieces) { + Some(centre) => Ok((centre, found.exact)), + None if found.whole => Err(Status::Unmeasurable(format!("edge `{name}` isn't a circle or an arc"))), + None => Err(Status::Ambiguous(edge_candidates(&edge.body, &found))), } - let round = found.pieces.first().and_then(|(_, line)| as_circle(line)); - let (centre, ..) = round.ok_or_else(|| Status::Unmeasurable(format!("edge `{name}` isn't a circle or an arc")))?; - Ok((centre, found.exact)) } /// The cylinder `face` lies on (or the pieces it was cut into, all on one cylinder), with every @@ -1090,6 +1129,21 @@ fn one_arc(segs: &[Seg2]) -> Option<(f64, [Vec2; 4])> { Some((radius, [center, arc.start(), arc.mid(), arc.end()])) } +/// The centre of the one circle every one of `pieces` lies on: `None` if they aren't on one circle. +/// The circle is read from all their points together ([`as_circle`], four at least), since a short +/// arc's three points are too few to read one from alone, and every point lies on it, in its plane. +/// Two points could be a chord, so a piece needs three. +fn one_circle(pieces: &[(usize, Vec)]) -> Option { + if pieces.iter().any(|(_, line)| line.len() < 3) { + return None; + } + let points: Vec = pieces.iter().flat_map(|(_, line)| line.iter().copied()).collect(); + let (centre, normal, radius) = as_circle(&points)?; + let tol = radius * 1e-6; + let on = |p: &Vec3| ((*p - centre).len() - radius).abs() <= tol && (*p - centre).dot(normal).abs() <= tol; + points.iter().all(on).then_some(centre) +} + /// A straight polyline's ends. fn straight(line: &[Vec3]) -> Option<[Vec3; 2]> { as_line(line)?; diff --git a/crates/doc/src/drawing/dimension_tests.rs b/crates/doc/src/drawing/dimension_tests.rs index 9335876b2..2f4804f63 100644 --- a/crates/doc/src/drawing/dimension_tests.rs +++ b/crates/doc/src/drawing/dimension_tests.rs @@ -513,3 +513,40 @@ fn keep_last_good_never_writes_a_record_a_file_refuses() { assert_eq!(read.dimension(linear).unwrap().last_good, doc.drawings[0].dimension(linear).unwrap().last_good, "{value}"); } } + +/// Quarter arcs of radius `r` round `c` in the plane z = 0, from `from` degrees, as a tessellated edge. +fn arc_at(c: [f64; 2], r: f64, from: f64) -> (usize, Vec) { + let at = |d: f64| Vec3::new(c[0] + r * (from + d).to_radians().cos(), c[1] + r * (from + d).to_radians().sin(), 0.0); + (0, (0..=9).map(|i| at(f64::from(i) * 10.0)).collect()) +} + +/// Pieces are one circle only when every one lies on it: another centre or radius, however near, is +/// another circle, and a straight piece isn't a circle. Pieces too short to read a circle from alone +/// are read together, so short arcs of one circle are it and of two circles aren't; a piece of only +/// two points could be a chord, and no pieces are none. +#[test] +fn pieces_are_one_circle_only_when_they_all_lie_on_it() { + let c = [40.0, 15.0]; + let first = arc_at(c, 6.0, 0.0); + let found = one_circle(&[first.clone(), arc_at(c, 6.0, 180.0)]).unwrap(); + assert!(found.dist(Vec3::new(40.0, 15.0, 0.0)) < 1e-9, "{found:?}"); + assert!(one_circle(std::slice::from_ref(&first)).is_some()); + assert!(one_circle(&[first.clone(), arc_at([40.0 + 1e-9, 15.0], 6.0, 180.0)]).is_some(), "rounding is the same circle"); + assert!(one_circle(&[first.clone(), arc_at([40.0 + 1e-3, 15.0], 6.0, 180.0)]).is_none(), "another centre"); + assert!(one_circle(&[first.clone(), arc_at(c, 6.0 + 1e-3, 180.0)]).is_none(), "another radius"); + let above: Vec = arc_at(c, 6.0, 180.0).1.iter().map(|p| Vec3::new(p.x, p.y, 5.0)).collect(); + assert!(one_circle(&[first.clone(), (1, above)]).is_none(), "the same circle moved along its axis"); + let tilted: Vec = arc_at(c, 6.0, 180.0).1.iter().map(|p| Vec3::new(40.0, p.y, p.x - 40.0)).collect(); + assert!(one_circle(&[first.clone(), (1, tilted)]).is_none(), "round another axis"); + let line: Vec = (0..5).map(|i| Vec3::new(f64::from(i), 0.0, 0.0)).collect(); + assert!(one_circle(&[first.clone(), (1, line)]).is_none(), "a straight piece"); + assert!(one_circle(&[first.clone(), (1, first.1[..3].to_vec())]).is_some(), "too short to read, but on it"); + let off: Vec = first.1[..3].iter().map(|p| Vec3::new(p.x + 1e-3, p.y, p.z)).collect(); + assert!(one_circle(&[first.clone(), (1, off)]).is_none(), "too short to read, and off it"); + assert!(one_circle(&[first.clone(), (1, first.1[..2].to_vec())]).is_none(), "two points could be a chord"); + let short = |c: [f64; 2]| (1, arc_at(c, 6.0, 180.0).1[..3].to_vec()); + let three = (0, first.1[..3].to_vec()); + assert!(one_circle(&[three.clone(), short(c)]).is_some(), "short arcs of one circle, read together"); + assert!(one_circle(&[three, short([45.0, 15.0])]).is_none(), "short arcs of two circles of one radius"); + assert!(one_circle(&[]).is_none()); +} diff --git a/crates/engine/src/cmd/drawing_view.rs b/crates/engine/src/cmd/drawing_view.rs index 11f9eb0ef..3bede22d4 100644 --- a/crates/engine/src/cmd/drawing_view.rs +++ b/crates/engine/src/cmd/drawing_view.rs @@ -24,15 +24,17 @@ use std::sync::Arc; use serde::Serialize; use serde_json::Value; +use solidcraft_doc::display_units::unit_scale; use solidcraft_doc::drawing::Drawing; use solidcraft_doc::drawing::balloon::Balloon; -use solidcraft_doc::drawing::dimension::Dimension; +use solidcraft_doc::drawing::dimension::{Dimension, LabelKind, MAX_DECIMALS, reading_label}; use solidcraft_doc::drawing::view::{ResolvedView, SetBy, Setting, View, ViewKind, ViewPlace}; use solidcraft_doc::drawing_view::{Looking, TangentEdges, ViewDirection, ViewOverrides}; use solidcraft_doc::ids; use solidcraft_geom::Plane; +use solidcraft_geom::drawing_measure::{self, AngleFrom, LinearDirection, Measured, Reading}; use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Sheet}; -use solidcraft_geom::drawing_view::{NamedView, PRESETS, ProjectedSide, Scale}; +use solidcraft_geom::drawing_view::{Invalid, NamedView, PRESETS, ProjectedSide, Scale}; use solidcraft_geom::hlr::{Source, Visibility}; use solidcraft_geom::paper::{MAX_COORDINATE_MM, Picture}; use solidcraft_geom::section::CurveAccuracy; @@ -44,10 +46,10 @@ use super::CommandSpec; use crate::drawing_view::{CHORD_RANGE, Extents, LineRequest, Lines, MAX_PATH_IDS, MAX_PATHS, OnSheet, ShownSet, Styles, Unmeasured}; use crate::params::bad; use crate::schema::drawing_view::{ - AccuracyResult, BaseParams, BoxResult, ChoicesResult, CopyParams, CreateResult, DPI_RANGE, EditParams, EditResult, ExtentsResult, FromResult, - InspectParams, InspectResult, LineResult, LineSourceResult, LinesStatusResult, MoveParams, OutsideResult, PathSegResult, PictureResult, - PieceResult, PlaceParam, ProjectedParams, ScaleResult, SceneResult, SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult, - ToSheetResult, ViewResult, ViewSet, + AccuracyResult, AlongParam, AngleFromParam, BaseParams, BoxResult, ChoicesResult, CopyParams, CreateResult, DPI_RANGE, EditParams, EditResult, + ExtentsResult, FromResult, InspectParams, InspectResult, LineResult, LineSourceResult, LinesStatusResult, MeasureParam, MeasurementResult, + MoveParams, OutsideResult, PathSegResult, PictureResult, PieceResult, PlaceParam, ProjectedParams, ScaleResult, SceneResult, SettingResult, + SettingsResult, SnapshotParams, SnapshotResult, SourceResult, ToSheetResult, ViewLineParam, ViewResult, ViewSet, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; @@ -76,7 +78,7 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Drawing View Snap .noundo() .contract(&CONTRACT) .output(output_schema_for::) - .params("view?: front (default), back, top, bottom, left, right, iso (= iso_front_right), iso_front_left, iso_back_right, iso_back_left, or {direction, up, origin?}; scale?: \"paper:model\" such as \"1:2\" (default: the largest ISO 5455 scale that fits the sheet's drawing area); position_mm?: [x, y] for the view's centre on the sheet (default the sheet's centre); sheet?: {size: {standard: a3} or {custom: {sides_mm: [w, h]}}, orientation?: landscape|portrait, dpi?: 25..2400} (default A3 landscape, 300 dpi); display_style?, reference_style?: visible (default), visible_hidden or shaded (drawn as a picture, without its own lines, and not with scene; shaded_visible and shaded_visible_hidden aren't supported yet); reference_hides_model?: false; reference_shown_percent?: 0..100, how far the box grows from the model's towards holding its reference parts, each side on its own (0, the default: the model's box; 100: holds them all); tangent_edges?: hide (default) or show; chord_mm?: 0.001..1 paper mm the lines are sampled at (default 0.01); max_error_mm?: the accuracy the lines must certify on paper (refused while they come from the mesh); scene?: true adds the lines as a paper scene of the sheet (visible lines only for now); source?: {occurrences: [[ids…]]}, the occurrence subtrees drawn ([] the design's own bodies; default every body); hide?: [[ids…]], subtrees left out; at most 1000 paths in each and 4096 ids in all. Every body the design places, whatever the browser shows. Returns {view, scale: {text, factor, fitted}, position_mm, sheet, extents (model mm on the view's plane), boundary_mm (on the sheet), lines: [{occurrence, body, reference, source: {kind: edge, edge, tangent} or {kind: silhouette, face}, pieces: [{visibility, path: [paper mm lines, and arcs for circles facing the view], accuracy}]}], status: {lines: approximate, provenance: mesh_projection, chord_mm, model_chord_mm, uncertain_pieces, covered_pieces}, stats, scene (with scene: true: {size_mm, groups: [{object: 0, kind: view, items: [{kind: stroke, path, closed, width_mm}]}]}), picture? ({pixels: [w, h], dpi, rect_mm} when something is shaded: the boundary's pixel grid at sheet.dpi or 1200, the lower, which dpi gives), source}. Read-only: saves nothing."), + .params("view?: front (default), back, top, bottom, left, right, iso (= iso_front_right), iso_front_left, iso_back_right, iso_back_left, or {direction, up, origin?}; scale?: \"paper:model\" such as \"1:2\" (default: the largest ISO 5455 scale that fits the sheet's drawing area); position_mm?: [x, y] for the view's centre on the sheet (default the sheet's centre); sheet?: {size: {standard: a3} or {custom: {sides_mm: [w, h]}}, orientation?: landscape|portrait, dpi?: 25..2400} (default A3 landscape, 300 dpi); display_style?, reference_style?: visible (default), visible_hidden or shaded (drawn as a picture, without its own lines, and not with scene; shaded_visible and shaded_visible_hidden aren't supported yet); reference_hides_model?: false; reference_shown_percent?: 0..100, how far the box grows from the model's towards holding its reference parts, each side on its own (0, the default: the model's box; 100: holds them all); tangent_edges?: hide (default) or show; chord_mm?: 0.001..1 paper mm the lines are sampled at (default 0.01); max_error_mm?: the accuracy the lines must certify on paper (refused while they come from the mesh); scene?: true adds the lines as a paper scene of the sheet (visible lines only for now); source?: {occurrences: [[ids…]]}, the occurrence subtrees drawn ([] the design's own bodies; default every body); hide?: [[ids…]], subtrees left out; at most 1000 paths in each and 4096 ids in all. measure?: up to 100 values to read on the view, each {linear: {along: x|y, from, to}}, {aligned: {from, to}} (model points), {angle: {edge: [a, b], from: horizontal|vertical|[c, d]}} or {radius: {edge}} (an edge as drawing.dimension.add takes it, which the view must see face on), with units?: mm|cm|m|in|ft (default the design's) and decimals?: 0..6 (default 2) for their labels; the reply then has measurements: [{kind, value_mm and paper_mm, or value_rad, label, meaning: projected, foreshortened, status: exact|approximate}]. Every body the design places, whatever the browser shows. Returns {view, scale: {text, factor, fitted}, position_mm, sheet, extents (model mm on the view's plane), boundary_mm (on the sheet), lines: [{occurrence, body, reference, source: {kind: edge, edge, tangent} or {kind: silhouette, face}, pieces: [{visibility, path: [paper mm lines, and arcs for circles facing the view], accuracy}]}], status: {lines: approximate, provenance: mesh_projection, chord_mm, model_chord_mm, uncertain_pieces, covered_pieces}, stats, scene (with scene: true: {size_mm, groups: [{object: 0, kind: view, items: [{kind: stroke, path, closed, width_mm}]}]}), picture? ({pixels: [w, h], dpi, rect_mm} when something is shaded: the boundary's pixel grid at sheet.dpi or 1200, the lower, which dpi gives), source}. Read-only: saves nothing."), CommandSpec::new(INSPECT, "Inspect Drawing View", crate::checked!("drawing.view.inspect", inspect)) .icon("inspect") .in_drawing() @@ -164,6 +166,7 @@ fn snapshot(s: &mut Session, p: &Value) -> Result { } let styles = Styles { display: settings.display_style, reference: settings.reference_style, reference_hides_model: settings.reference_hides_model }; + let measurements = measurements(s, &request, &basis, scale)?; let asked = LineRequest { shows: shown, hidden: settings.display_style == VisualStyle::VisibleHidden, @@ -221,12 +224,18 @@ fn snapshot(s: &mut Session, p: &Value) -> Result { stats: drawn.stats.into(), scene, picture, + measurements, source: SourceResult { bodies: set.bodies.len(), timeline_at_end: s.doc.marker.is_none() }, param_warnings: Vec::new(), }; serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) } +/// The most values one snapshot reads. +const MAX_MEASUREMENTS: usize = 100; +/// The decimals of a measurement's label unless told. +const DEFAULT_DECIMALS: u8 = 2; + /// `source` and `hide` checked: at most [`MAX_PATHS`] paths in each and [`MAX_PATH_IDS`] ids in all, /// each a path `occurrence_placement` takes, with `[]` (the design's own bodies) in `source` only. fn check_paths(s: &Session, source: Option<&[Vec]>, hide: &[Vec]) -> Result<()> { @@ -248,6 +257,66 @@ fn check_paths(s: &Session, source: Option<&[Vec]>, hide: &[Vec]) -> R Ok(()) } +/// What `request.measure` reads on the view through `basis` at `scale`, in its order. The first that +/// can't be read refuses the call, by its place in the list. +fn measurements(s: &Session, request: &SnapshotParams, basis: &Plane, scale: Scale) -> Result> { + if request.measure.len() > MAX_MEASUREMENTS { + return Err(bad(CMD, format!("at most {MAX_MEASUREMENTS} measurements in measure"))); + } + let decimals = request.decimals.unwrap_or(DEFAULT_DECIMALS); + if decimals > MAX_DECIMALS { + return Err(bad(CMD, format!("decimals is 0 to {MAX_DECIMALS}"))); + } + let units = request.units.as_deref().unwrap_or(s.doc.units.as_str()); + if unit_scale(units).1 != units { + return Err(bad(CMD, "units is mm, cm, m, in or ft")); + } + let length = |kind, reading: Measured, label: LabelKind| MeasurementResult { + kind, + value_mm: Some(reading.value), + paper_mm: Some(reading.value * scale.factor()), + value_rad: None, + label: reading_label(label, reading.value, units, decimals), + meaning: "projected", + foreshortened: reading.foreshortened, + status: "exact", + }; + let one = |m: &MeasureParam| -> std::result::Result { + let invalid = |e: Invalid| e.0.to_string(); + Ok(match m { + MeasureParam::Linear { along, from, to } => { + let direction = if *along == AlongParam::X { LinearDirection::Horizontal } else { LinearDirection::Vertical }; + let reading = drawing_measure::linear(basis, from.0, to.0, direction, Reading::Projected).map_err(invalid)?; + length("linear", reading, LabelKind::Length) + } + MeasureParam::Aligned { from, to } => { + let reading = drawing_measure::linear(basis, from.0, to.0, LinearDirection::Aligned, Reading::Projected).map_err(invalid)?; + length("aligned", reading, LabelKind::Length) + } + MeasureParam::Angle { edge: [a, b], from } => { + let line = match from { + AngleFromParam::View(ViewLineParam::Horizontal) => AngleFrom::Horizontal, + AngleFromParam::View(ViewLineParam::Vertical) => AngleFrom::Vertical, + AngleFromParam::Line([c, d]) => AngleFrom::Edge(c.0, d.0), + }; + let reading = drawing_measure::angle(basis, (a.0, b.0), line, Reading::Projected).map_err(invalid)?; + MeasurementResult { value_mm: None, paper_mm: None, value_rad: Some(reading.value), ..length("angle", reading, LabelKind::Angle) } + } + MeasureParam::Radius { edge } => { + let named = s.doc.edge_reference(&s.model, &edge.pick, &edge.path).map_err(|e| e.to_string())?; + let (radius, exact) = s.doc.radius_on_view(&s.model, &named, basis).map_err(|status| { + let (word, why, _) = super::drawing_dimension::status_words(status); + why.unwrap_or_else(|| word.to_string()) + })?; + let reading = Measured { value: radius, foreshortened: false }; + MeasurementResult { status: if exact { "exact" } else { "approximate" }, ..length("radius", reading, LabelKind::Radius) } + } + }) + }; + let read = request.measure.iter().enumerate().map(|(at, m)| one(m).map_err(|why| bad(CMD, format!("measure[{at}]: {why}")))); + read.collect() +} + /// Refused unless every piece of `drawn` certifies `max` paper mm at `scale` (the accuracy rule on /// #5866): an analytic piece meets any, a bounded one its bound, a sampled one none. fn certify(drawn: &Lines, max: f64, scale: Scale) -> Result<()> { diff --git a/crates/engine/src/cmd/drawing_view_tests.rs b/crates/engine/src/cmd/drawing_view_tests.rs index ef8953952..ef4671cb0 100644 --- a/crates/engine/src/cmd/drawing_view_tests.rs +++ b/crates/engine/src/cmd/drawing_view_tests.rs @@ -1443,6 +1443,112 @@ fn a_scene_with_hidden_reference_lines_is_refused() { assert!(e.contains("not supported yet: hidden lines"), "{e}"); } +/// The readings of `measure` on `v`, each (value, label). +fn readings(v: &Value) -> Vec<(f64, String)> { + let value = |m: &Value| m.get("value_mm").or(m.get("value_rad")).and_then(Value::as_f64).unwrap(); + v["measurements"].as_array().unwrap().iter().map(|m| (value(m), m["label"].as_str().unwrap().to_string())).collect() +} + +/// From (0, 0, 0) to (30, 40, 0) seen from above, 1:2: 30 along x, 40 along y, 50 as it runs, half +/// that on paper; a 45 degree line reads 45 degrees from the view's horizontal and from a line along +/// x; a reply with none says nothing about them. Nothing changes or is evaluated. +#[test] +fn a_views_measurements_are_read_as_it_shows_them() { + let mut s = block(); + let (doc, evaluations) = (s.doc.clone(), s.evaluations); + let (a, b) = (json!([0, 0, 0]), json!([30, 40, 0])); + let v = snap( + &mut s, + json!({"view": "top", "scale": "1:2", "measure": [ + {"linear": {"along": "x", "from": a, "to": b}}, + {"linear": {"along": "y", "from": a, "to": b}}, + {"aligned": {"from": a, "to": b}}, + {"angle": {"edge": [[0, 0, 0], [1, 1, 0]], "from": "horizontal"}}, + {"angle": {"edge": [[0, 0, 0], [1, 1, 0]], "from": [[0, 0, 0], [1, 0, 0]]}}, + ]}), + ); + let schema = crate::schema::output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &v), "{v}"); + let got = readings(&v); + let want = [(30.0, "30.00"), (40.0, "40.00"), (50.0, "50.00"), (std::f64::consts::FRAC_PI_4, "45.00°"), (std::f64::consts::FRAC_PI_4, "45.00°")]; + assert_eq!(got.len(), want.len()); + for ((value, label), (expected, text)) in got.iter().zip(want) { + assert!((value - expected).abs() < 1e-9 && label == text, "{got:?}"); + } + let first = &v["measurements"][0]; + assert_eq!( + (&first["kind"], &first["paper_mm"], &first["meaning"], &first["foreshortened"]), + (&json!("linear"), &json!(15.0), &json!("projected"), &json!(false)), + "{v}" + ); + assert_eq!(v["measurements"][3].get("value_mm"), None, "{v}"); + assert_eq!(snap(&mut s, json!({"view": "top"})).get("measurements"), None); + assert!(Arc::ptr_eq(&doc, &s.doc) && s.evaluations == evaluations); +} + +/// A 50 mm edge of a cube seen in iso reads 50 x sqrt(2/3) = 40.825 and says it is foreshortened; +/// the label takes the units and decimals asked for. +#[test] +fn an_edge_in_iso_reads_foreshortened() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 50, "width": 50, "height": 50})); + let edge = json!({"aligned": {"from": [0, 0, 0], "to": [50, 0, 0]}}); + let v = snap(&mut s, json!({"view": "iso", "measure": [edge], "decimals": 3})); + let got = readings(&v); + assert!((got[0].0 - 50.0 * (2.0f64 / 3.0).sqrt()).abs() < 1e-9 && got[0].1 == "40.825", "{got:?}"); + assert_eq!(v["measurements"][0]["foreshortened"], true); + let inch = json!({"aligned": {"from": [0, 0, 0], "to": [25.4, 0, 0]}}); + let v = snap(&mut s, json!({"view": "top", "measure": [inch], "units": "in", "decimals": 3})); + assert_eq!(readings(&v)[0].1, "1.000", "{v}"); +} + +/// A 20 mm hole reads R10 where the view sees it round, on paper at the view's scale, and is refused +/// end on, by its place in the list. +#[test] +fn a_holes_radius_is_read_face_on_and_refused_end_on() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 5, "body_name": "Plate"})); + run(&mut s, "solid.cylinder", json!({"diameter": 20, "height": 7, "base": [20, 20, -1], "operation": "cut", "targets": ["Plate"]})); + let rim = json!({"radius": {"edge": [30, 20, 5]}}); + let v = snap(&mut s, json!({"view": "top", "scale": "2:1", "measure": [rim]})); + let got = readings(&v); + assert!(got.len() == 1 && (got[0].0 - 10.0).abs() < 1e-9 && got[0].1 == "R10.00", "{v}"); + let paper = v["measurements"][0]["paper_mm"].as_f64().unwrap(); + assert!((paper - 20.0).abs() < 1e-9 && v["measurements"][0]["status"] == "exact", "{v}"); + let e = refused(&mut s, json!({"view": "front", "measure": [{"aligned": {"from": [0, 0, 0], "to": [1, 0, 0]}}, rim]})); + assert!(e.contains("measure[1]") && e.contains("isn't a circle in this view"), "{e}"); + let straight = json!({"radius": {"edge": [0, 20, 5]}}); + let e = refused(&mut s, json!({"view": "top", "measure": [straight]})); + assert!(e.contains("measure[0]"), "{e}"); +} + +#[test] +fn hostile_measurements_are_refused() { + let mut s = block(); + let doc = s.doc.clone(); + let one = json!({"aligned": {"from": [0, 0, 0], "to": [1, 0, 0]}}); + let many = vec![one.clone(); 101]; + let cases = [ + (json!({"measure": many}), "at most 100"), + (json!({"measure": [{"aligned": {"from": [0, 0, 0], "to": [0, 0, 0]}}]}), "measure[0]"), + (json!({"view": "top", "measure": [{"aligned": {"from": [0, 0, 0], "to": [0, 0, 5]}}]}), "measure[0]"), + (json!({"measure": [{"aligned": {"from": [0, 0, 0], "to": [1e13, 0, 0]}}]}), "measure[0]"), + (json!({"measure": [{"linear": {"along": "z", "from": [0, 0, 0], "to": [1, 0, 0]}}]}), "measure"), + (json!({"measure": [{"aligned": {"from": [0, 0, 0], "to": ["a", 0, 0]}}]}), "measure"), + (json!({"measure": [{"angle": {"edge": [[0, 0, 0], [1, 0, 0]], "from": "horizontal"}}]}), "measure[0]"), + (json!({"measure": [{"radius": {"edge": [1e13, 0, 0]}}]}), "measure"), + (json!({"measure": [{"nothing": {}}]}), "measure"), + (json!({"measure": [one.clone()], "units": "parsec"}), "units"), + (json!({"measure": [one.clone()], "decimals": 7}), "decimals"), + (json!({"measure": [one], "decimals": -1}), "decimals"), + ]; + for (p, says) in cases { + let e = refused(&mut s, p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(&doc, &s.doc), "{p}"); + } +} + /// The occurrence paths `v`'s lines name, each once. fn line_paths(v: &Value) -> Vec { let mut paths: Vec = v["lines"].as_array().unwrap().iter().map(|l| l["occurrence"].clone()).collect(); diff --git a/crates/engine/src/drawing_dimension_tests.rs b/crates/engine/src/drawing_dimension_tests.rs index 11a51aaa4..4526bff18 100644 --- a/crates/engine/src/drawing_dimension_tests.rs +++ b/crates/engine/src/drawing_dimension_tests.rs @@ -318,11 +318,44 @@ fn a_circle_and_an_arc_read_their_radius_and_diameter() { assert!(matches!(&r.status, Status::Lost(why) if why.contains("no longer exists")), "{r:?}"); run(&mut f.s, "edit.undo", json!({})); assert_reads(&f.resolve(across), 12.0, false); - // A slot across the rim splits it: which piece to measure isn't one answer, and none is chosen. + // A slot across the rim leaves two arcs of one circle: it is still that circle, not exactly, with + // its arrow on what is left of it. run(&mut f.s, "solid.box", json!({"length": 2, "width": 5, "height": 20, "corner": [39, -1, 5], "operation": "cut", "targets": ["Box"]})); let r = f.resolve(across); - assert!(matches!(&r.status, Status::Ambiguous(pieces) if pieces.len() >= 2), "{r:?}"); - assert_eq!(r.measured, None); + assert_reads(&r, 12.0, false); + assert!(!r.exact, "{r:?}"); + let centre = Vec3::new(40.0, 0.0, 15.0); + assert!(r.points[0].dist(centre) < 1e-6, "{r:?}"); + assert!(r.points[1..].iter().all(|p| (p.dist(centre) - 6.0).abs() < 1e-6 && (p.x - 40.0).abs() >= 1.0 - 1e-6), "{r:?}"); + // A slot through the whole hole, along a line through its centre, leaves arcs too short to read a + // circle from on their own: each still lies on the circle the longer ones give. + run(&mut f.s, "edit.undo", json!({})); + run(&mut f.s, "solid.box", json!({"length": 40, "width": 42, "height": 3, "corner": [20, -1, 13.5], "operation": "cut", "targets": ["Box"]})); + let r = f.resolve(across); + assert_reads(&r, 12.0, false); + assert!(!r.exact, "{r:?}"); +} + +/// A name saved from a face that was split finds the one edge on a body with the one face: it is +/// that edge, not exactly, for a length, a radius and a centre alike. +#[test] +fn one_piece_of_a_name_is_that_edge() { + let mut f = boxed(); + run(&mut f.s, "solid.cylinder", json!({"radius": 6, "height": 42, "base": [40, -1, 15], "axis": "Y", "operation": "cut", "targets": ["Box"]})); + // As a name reads once its second face was split by a face that has since gone. + let piece = |e: ModelEdge| ModelEdge { name: format!("{}#[F9:side]#1", e.name), ..e }; + let top = piece(f.edge([0.0, 0.0, 30.0], [80.0, 0.0, 30.0])); + let rim = piece(f.round([40.0, 0.0, 15.0], 6.0)); + let length = f.add(f.front, DimensionKind::Length { edge: top, direction: LinearDirection::Aligned, reading: Reading::True }, None); + let across = f.add(f.front, radial(&rim, true), None); + let centre = ModelPoint { body: rim.body, origin_feature: rim.origin_feature, edges: vec![rim.name], centre: true, path: Vec::new() }; + let up = DimensionKind::Linear { a: f.corner([0.0, 0.0, 0.0]), b: centre, direction: LinearDirection::Vertical, reading: Reading::Projected }; + let up = f.add(f.front, up, None); + for (id, value) in [(length, 80.0), (across, 12.0), (up, 15.0)] { + let r = f.resolve(id); + assert_reads(&r, value, false); + assert!(!r.exact, "{r:?}"); + } } /// What a dimension measures is gone when its edge is filleted away, and found again on undo; a @@ -384,8 +417,8 @@ fn a_split_edge_is_ambiguous_for_its_length_and_its_ends_still_meet() { } /// A hole's centre is found through its rim, exactly: 40 along and 15 up from the box's bottom -/// front left corner. A slot across the rim leaves it several arcs, so the centre is ambiguous and -/// none is chosen; with the hole suppressed its centre is lost. +/// front left corner. A slot across the rim leaves it several arcs of one circle, so the centre is +/// still that circle's, not exactly; with the hole suppressed its centre is lost. #[test] fn a_holes_centre_is_found_through_its_rim() { let mut f = boxed(); @@ -404,12 +437,17 @@ fn a_holes_centre_is_found_through_its_rim() { assert_reads(&f.resolve(up), 15.0, false); run(&mut f.s, "solid.box", json!({"length": 2, "width": 5, "height": 30, "corner": [39, -1, 0], "operation": "cut", "targets": ["Box"]})); let r = f.resolve(across); - assert!(matches!(&r.status, Status::Ambiguous(c) if c.len() >= 2) && r.measured.is_none(), "{r:?}"); + assert_reads(&r, 40.0, false); + assert!(!r.exact, "{r:?}"); run(&mut f.s, "timeline.suppress", json!({"feature": hole, "suppressed": true})); let r = f.resolve(across); assert!(matches!(&r.status, Status::Lost(why) if why.contains("no longer exists")), "{r:?}"); } +fn radial(edge: &ModelEdge, diameter: bool) -> DimensionKind { + DimensionKind::Radial { edge: edge.clone(), diameter } +} + /// A boss of radius 5 along X on the box's right face reads Ø10 between its silhouettes in the front /// view, exactly, with its silhouettes 10 apart from one end of it to the other. A notch across its /// top cuts its face into pieces, all on the one cylinder, so it still reads Ø10 (found through diff --git a/crates/engine/src/schema/drawing_view.rs b/crates/engine/src/schema/drawing_view.rs index 4b3540487..3276463d7 100644 --- a/crates/engine/src/schema/drawing_view.rs +++ b/crates/engine/src/schema/drawing_view.rs @@ -22,6 +22,8 @@ use solidcraft_render::VisualStyle; use crate::drawing_view::{CHORD_MM, CHORD_RANGE, Stats}; use super::Point2; +use super::drawing_dimension::EdgeParam; +use super::types::Point3; /// The lowest and highest picture resolution a sheet takes, in dots per inch. pub const DPI_RANGE: std::ops::RangeInclusive = 25.0..=2400.0; @@ -65,6 +67,54 @@ pub struct SnapshotParams { pub source: Option, /// Occurrence paths left out of this view, with everything under them (none when not given). pub hide: Vec>, + /// Values to read on the view, as it shows them, with their labels: at most 100. + pub measure: Vec, + /// The length unit of the labels, `mm`, `cm`, `m`, `in` or `ft` (the design's when not given). + #[serde(deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "String")] + pub units: Option, + /// The decimals of the labels, 0 to 6 (2 when not given). + #[serde(deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "u8")] + pub decimals: Option, +} + +/// A value to read on a view, from model points in the design's frame. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case", deny_unknown_fields)] +pub enum MeasureParam { + /// How far apart two points are along the view's x or y. + Linear { along: AlongParam, from: Point3, to: Point3 }, + /// How far apart two points are as the view shows them. + Aligned { from: Point3, to: Point3 }, + /// The angle of the line `edge` runs, from its first point, as the view shows it. + Angle { edge: [Point3; 2], from: AngleFromParam }, + /// A circle's or an arc's radius: the view must see it face on. + Radius { edge: EdgeParam }, +} + +/// Which way a linear measurement reads. +#[derive(Clone, Copy, Debug, PartialEq, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum AlongParam { + X, + Y, +} + +/// The line an angle is read from: the view's own, or a line through two model points. +#[derive(Clone, Copy, Debug, PartialEq, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum AngleFromParam { + View(ViewLineParam), + Line([Point3; 2]), +} + +/// One of the view's own lines. +#[derive(Clone, Copy, Debug, PartialEq, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ViewLineParam { + Horizontal, + Vertical, } /// What a view draws: occurrence paths from the design's root, each the subtree it places, with @@ -827,12 +877,38 @@ pub struct SnapshotResult { /// The view's picture, when something in it is shaded. #[serde(skip_serializing_if = "Option::is_none")] pub picture: Option, + /// What `measure` asked for, in its order. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub measurements: Vec, pub source: SourceResult, /// In the warn parameter-check mode: what the call's parameters got wrong. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub param_warnings: Vec, } +/// A value read on a view. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MeasurementResult { + /// `linear`, `aligned`, `angle` or `radius`. + pub kind: &'static str, + /// A length, in model millimetres. + #[serde(skip_serializing_if = "Option::is_none")] + pub value_mm: Option, + /// That length on paper, at the view's scale. + #[serde(skip_serializing_if = "Option::is_none")] + pub paper_mm: Option, + /// An angle, in radians. + #[serde(skip_serializing_if = "Option::is_none")] + pub value_rad: Option, + pub label: String, + /// Always `projected`: as the view shows it. + pub meaning: &'static str, + /// A measured line isn't parallel to the view's plane, so the model's value differs. + pub foreshortened: bool, + /// `exact`, or `approximate` for an edge found again only by its pieces. + pub status: &'static str, +} + #[cfg(test)] #[path = "drawing_view_tests.rs"] mod tests; diff --git a/crates/engine/src/schema/drawing_view_tests.rs b/crates/engine/src/schema/drawing_view_tests.rs index cd89cc6dc..6243ba662 100644 --- a/crates/engine/src/schema/drawing_view_tests.rs +++ b/crates/engine/src/schema/drawing_view_tests.rs @@ -9,9 +9,11 @@ use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; fn schemas_and_the_key_check_agree() { let keys = [ "chord_mm", + "decimals", "display_style", "hide", "max_error_mm", + "measure", "position_mm", "reference_hides_model", "reference_shown_percent", @@ -21,6 +23,7 @@ fn schemas_and_the_key_check_agree() { "sheet", "source", "tangent_edges", + "units", "view", ]; assert_keys(input_schema_for::(), &keys); @@ -72,8 +75,8 @@ fn the_contract_lists_the_view_settings() { let settings = serde_json::to_value(ViewSettings { scale: "1:2".parse().ok(), ..ViewSettings::default() }).unwrap_or_default(); let mut theirs: Vec = settings.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); // Beside a view's settings, the request's own: where it goes, its page, its lines' chord and - // accuracy check, whether it wants the paper scene, and what it draws. - theirs.extend(["position_mm", "sheet", "chord_mm", "max_error_mm", "scene", "source", "hide"].map(String::from)); + // accuracy check, whether it wants the paper scene, what it draws, and what it reads. + theirs.extend(["position_mm", "sheet", "chord_mm", "max_error_mm", "scene", "source", "hide", "measure", "units", "decimals"].map(String::from)); theirs.sort(); let schema = input_schema_for::(); let mut ours: Vec = schema.as_value()["properties"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();