From cbcde608e56234b07065b1c95592aae2fefbb56e Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 26 Oct 2026 19:09:11 +0000 Subject: [PATCH 1/3] Drawing sheets on paper: the drawing border, grid and marks (#4890 A6, #3875) SheetLayout::paper gives what a sheet's drawing border draws as paper groups of kind drawing_border, in order, each left out when empty: - the drawing border, one closed stroke drawing_border_line_mm wide (0.7 mm in the built-in profile, ISO 5457); - the grid: the grid reference border, closed, and a mark at each edge between two fields from the drawing border out to it, on all four sides, GRID_LINE_MM (0.35 mm, ISO 5457's grid line width as the drawings study's section 11.3 gives it) wide; none without fields or with the grid reference border on the drawing border; - the centring marks, as the layout places them, in the drawing border's width, as the profile says; - the trimming marks, each rectangle filled. The grid's labels are text and come once the paper scene has text (#4813). Only the function, its constant and its tests are added. Co-Authored-By: Claude Opus 5.5 --- crates/geom/src/drawing_sheet.rs | 50 +++++++++++- crates/geom/src/drawing_sheet_tests.rs | 101 +++++++++++++++++++++++++ 2 files changed, 148 insertions(+), 3 deletions(-) diff --git a/crates/geom/src/drawing_sheet.rs b/crates/geom/src/drawing_sheet.rs index 86ec18ba28e..b98db333de4 100644 --- a/crates/geom/src/drawing_sheet.rs +++ b/crates/geom/src/drawing_sheet.rs @@ -6,7 +6,7 @@ //! of reference fields with their labels, and the centring and trimming marks. //! [`DrawingBorderProfile::validate`] checks a profile on its own, as when one is read, and //! [`DrawingBorderProfile::layout`] works it out for one sheet, so a new size regrows it. Nothing -//! here is frozen geometry, saved in a design or drawn: a writer draws the [`SheetLayout`] later. +//! here is frozen geometry or saved in a design: [`SheetLayout::paper`] gives a writer what it draws. //! //! Sheet coordinates are millimetres from the sheet's lower-left corner, x to the right and y up. //! The drawing border's line is centred on [`SheetLayout::drawing_border`]. @@ -32,10 +32,10 @@ use serde::{Deserialize, Serialize}; -use crate::paper::MAX_LINE_MM; /// The longest side a custom sheet may have, in millimetres: the paper scene's limit. pub use crate::paper::MAX_SIDE_MM; -use crate::{Aabb2, Vec2}; +use crate::paper::{Group, Item, MAX_LINE_MM, ObjectKind}; +use crate::{Aabb2, Loop2, Region2, Seg2, Vec2}; /// The most fields an equal division may cut each way. pub const MAX_EQUAL_FIELDS: u32 = 200; @@ -433,6 +433,50 @@ impl DrawingBorderProfile { } } +/// ISO 5457's grid line width (the drawings study, section 11.3): the grid reference border and the +/// marks at its field edges. +pub const GRID_LINE_MM: f64 = 0.35; + +impl SheetLayout { + /// What the drawing border draws, as paper groups of kind `drawing_border` for `object`, in this + /// order and each left out when it has nothing: the drawing border, closed, + /// `drawing_border_line_mm` wide; the grid reference border and a mark at each edge between two + /// fields, from the drawing border out to it on every side, [`GRID_LINE_MM`] wide; the centring + /// marks in the drawing border's width; the trimming marks, filled. The grid's labels are text, + /// which the paper scene doesn't have yet. + pub fn paper(&self, object: u64) -> Vec { + let line = |a, b, width_mm| Item::Stroke { path: vec![Seg2::Line { a, b }], closed: false, width_mm }; + let outline = |r, width_mm| Item::Stroke { path: rectangle(r).segs, closed: true, width_mm }; + let (d, g) = (self.drawing_border, self.grid_border); + let mut grid = Vec::new(); + // No fields, or a grid reference border on the drawing border: no grid to draw. + if !self.columns.is_empty() && g.min.x < d.min.x { + grid.push(outline(g, GRID_LINE_MM)); + // Each field's far edge but the last's: left to right, and top to bottom. + for x in self.columns.iter().take(self.columns.len().saturating_sub(1)).map(|f| f.to_mm) { + grid.push(line(Vec2::new(x, g.min.y), Vec2::new(x, d.min.y), GRID_LINE_MM)); + grid.push(line(Vec2::new(x, d.max.y), Vec2::new(x, g.max.y), GRID_LINE_MM)); + } + for y in self.rows.iter().take(self.rows.len().saturating_sub(1)).map(|f| f.from_mm) { + grid.push(line(Vec2::new(g.min.x, y), Vec2::new(d.min.x, y), GRID_LINE_MM)); + grid.push(line(Vec2::new(d.max.x, y), Vec2::new(g.max.x, y), GRID_LINE_MM)); + } + } + let centring = self.centring_marks.iter().map(|&[a, b]| line(a, b, self.drawing_border_line_mm)).collect(); + let trimming = self.trimming_marks.iter().map(|&r| Item::Fill { region: Region2 { outer: rectangle(r), holes: vec![] } }).collect(); + [vec![outline(d, self.drawing_border_line_mm)], grid, centring, trimming] + .into_iter() + .filter(|items| !items.is_empty()) + .map(|items| Group { object, kind: ObjectKind::DrawingBorder, items }) + .collect() + } +} + +/// `r`'s outline, anticlockwise from its lower-left corner. +fn rectangle(r: Aabb2) -> Loop2 { + Loop2::polygon(&[r.min, Vec2::new(r.max.x, r.min.y), r.max, Vec2::new(r.min.x, r.max.y)]) +} + /// The four centring marks: on the sheet's centre lines, from the edges of `start` to `reach` /// inside the drawing border, which must not take them past the centre. fn centring_marks(start: Aabb2, drawing_border: Aabb2, size: Vec2, reach: f64) -> Result> { diff --git a/crates/geom/src/drawing_sheet_tests.rs b/crates/geom/src/drawing_sheet_tests.rs index 6b6ee2612ce..840fe2e439d 100644 --- a/crates/geom/src/drawing_sheet_tests.rs +++ b/crates/geom/src/drawing_sheet_tests.rs @@ -609,3 +609,104 @@ fn rounding_past_a_whole_number_of_fields_leaves_no_sliver() { assert_eq!(layout.columns.first().unwrap().from_mm, 60.0 - hair); } } + +/// A group's items as (each piece's ends in micrometres, closed, width) for strokes and (the +/// outline's corners in micrometres) for fills: what hand-worked values are compared with. +fn drawn(group: &Group) -> Vec<(Vec<[i64; 4]>, bool, f64)> { + let um = |v: f64| (v * 1000.0).round() as i64; + let ends = |segs: &[Seg2]| segs.iter().map(|s| [um(s.start().x), um(s.start().y), um(s.end().x), um(s.end().y)]).collect(); + group + .items + .iter() + .map(|item| match item { + Item::Stroke { path, closed, width_mm } => (ends(path), *closed, *width_mm), + Item::Fill { region } => (ends(®ion.outer.segs), true, 0.0), + }) + .collect() +} + +/// A line from (x0, y0) to (x1, y1) mm, `width` wide. +fn line(x0: f64, y0: f64, x1: f64, y1: f64, width: f64) -> (Vec<[i64; 4]>, bool, f64) { + let um = |v: f64| (v * 1000.0).round() as i64; + (vec![[um(x0), um(y0), um(x1), um(y1)]], false, width) +} + +/// A rectangle (x0, y0)..(x1, y1) mm, anticlockwise from its lower-left corner: closed `width` +/// wide, or a fill when `width` is 0. +fn rect(x0: f64, y0: f64, x1: f64, y1: f64, width: f64) -> (Vec<[i64; 4]>, bool, f64) { + let um = |v: f64| (v * 1000.0).round() as i64; + let c = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]; + (c.windows(2).map(|w| [um(w[0].0), um(w[0].1), um(w[1].0), um(w[1].1)]).collect(), true, width) +} + +fn scene(layout: &SheetLayout, groups: Vec) -> crate::paper::Scene { + crate::paper::Scene { size_mm: layout.sheet_border.max, groups } +} + +/// A3 landscape, the built-in profile, by hand: the drawing border round 10..410 by 10..287, 0.7 +/// wide; the grid reference border 5 mm outside it and a 0.35 mark each side at every edge between +/// two fields (60 to 360 across, 248.5 down to 48.5 up); the centring marks from the sheet's edge to +/// the drawing border on the centre lines x = 210 and y = 148.5, 0.7 wide; no trimming marks. +#[test] +fn a3s_drawing_border_on_paper_is_its_border_grid_and_marks() { + let layout = iso_layout(PaperSize::A3, Orientation::Landscape); + let groups = layout.paper(4); + assert_eq!(groups.len(), 3); + assert!(groups.iter().all(|g| (g.object, g.kind) == (4, ObjectKind::DrawingBorder))); + assert_eq!(drawn(&groups[0]), [rect(10.0, 10.0, 410.0, 287.0, 0.7)]); + let mut grid = vec![rect(5.0, 5.0, 415.0, 292.0, 0.35)]; + for x in [60.0, 110.0, 160.0, 210.0, 260.0, 310.0, 360.0] { + grid.extend([line(x, 5.0, x, 10.0, 0.35), line(x, 287.0, x, 292.0, 0.35)]); + } + for y in [248.5, 198.5, 148.5, 98.5, 48.5] { + grid.extend([line(5.0, y, 10.0, y, 0.35), line(410.0, y, 415.0, y, 0.35)]); + } + assert_eq!(drawn(&groups[1]), grid); + assert_eq!( + drawn(&groups[2]), + [ + line(210.0, 0.0, 210.0, 10.0, 0.7), + line(210.0, 297.0, 210.0, 287.0, 0.7), + line(0.0, 148.5, 10.0, 148.5, 0.7), + line(420.0, 148.5, 410.0, 148.5, 0.7) + ] + ); + scene(&layout, groups).validate().unwrap(); +} + +/// ISO 5457's full border: the filing margin moves the drawing border to x = 20, the centring +/// marks run from the grid reference border to 10 mm inside, and the eight trimming marks are +/// filled, each the layout's own rectangle. +#[test] +fn the_full_iso_5457_border_on_paper_fills_its_trimming_marks() { + let layout = full_iso_5457().layout(&Sheet::standard(PaperSize::A3, Orientation::Landscape)).unwrap(); + let groups = layout.paper(1); + assert_eq!(groups.len(), 4); + assert_eq!(drawn(&groups[0]), [rect(20.0, 10.0, 410.0, 287.0, 0.7)]); + assert_eq!(drawn(&groups[1])[0], rect(15.0, 5.0, 415.0, 292.0, 0.35)); + assert_eq!(drawn(&groups[2])[2], line(15.0, 148.5, 30.0, 148.5, 0.7)); + let fills: Vec<_> = layout.trimming_marks.iter().map(|r| rect(r.min.x, r.min.y, r.max.x, r.max.y, 0.0)).collect(); + assert_eq!((fills.len(), drawn(&groups[3])), (8, fills)); + assert_eq!(drawn(&groups[3])[0], rect(0.0, 0.0, 10.0, 5.0, 0.0)); + scene(&layout, groups).validate().unwrap(); +} + +/// The shapes: no grid, or a grid reference border on the drawing border, draws no grid group; no +/// centring marks, no centring group; one field each way, the grid reference border alone; A4, +/// labelled on two sides, still has its marks on all four (3 edges across, 5 down). +#[test] +fn a_border_on_paper_draws_only_what_its_profile_has() { + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let paper = |profile: DrawingBorderProfile, sheet: &Sheet| { + let layout = profile.layout(sheet).unwrap(); + let groups = layout.paper(1); + scene(&layout, groups.clone()).validate().unwrap(); + groups.iter().map(|g| g.items.len()).collect::>() + }; + let iso = DrawingBorderProfile::iso; + assert_eq!(paper(DrawingBorderProfile { grid: GridRule::None, ..iso() }, &a3), [1, 4]); + assert_eq!(paper(DrawingBorderProfile { grid_border_mm: 0.0, ..iso() }, &a3), [1, 4]); + assert_eq!(paper(DrawingBorderProfile { centring_mark_mm: None, ..iso() }, &a3), [1, 1 + 2 * 7 + 2 * 5]); + assert_eq!(paper(DrawingBorderProfile { grid: GridRule::Equal { columns: 1, rows: 1 }, ..iso() }, &a3), [1, 1, 4]); + assert_eq!(paper(iso(), &Sheet::standard(PaperSize::A4, Orientation::Portrait)), [1, 1 + 2 * 3 + 2 * 5, 4]); +} From 41290856cd807039ee9d846a9018d9089a498ee0 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Tue, 27 Oct 2026 13:41:51 +0000 Subject: [PATCH 2/3] Drawing sheets on paper: one sheet's scene, its border then its views by id (#4890 W10, #3890 W15) `drawing_scene::build` draws one sheet of a drawing as one paper scene, the one the sheet page and every export will draw, and `drawing.scene {sheet}` answers it (in_drawing, noundo, doc_only, typed contract and output schema). In paint order: the sheet's drawing border groups as `SheetLayout::paper` gives them (object: the sheet), then each view on the sheet by id (object: the view), its visible lines as `paper_group` makes them. - A view's lines are worked out centred on the view and then moved to its centre, exactly (each point plus the centre), so the same lines on the same centre are the same bytes. They match the snapshot's within rounding. - The shown set is worked out once per sheet. No model is evaluated. - A view with nothing to measure is a placeholder, and one that can't be drawn yet (shaded, or hidden lines) fails with the snapshot's reason. Each draws nothing, and the sheet's other views are still drawn. - A view is placed only while the sheet stays within the paper scene's 100,000 records. One that would pass the limit fails and says so, and later views that fit are still drawn. Each view's lines are placed as they are drawn, so at most one view's lines are held beside the scene. - A view above 100:1 takes a coarser chord rather than asking the mesh for chords below its floor. A saved view has no chord setting to give. One rule, one place: - the snapshot's two style refusals are `drawing_view::not_drawable`; - a group's record count is `paper::Group::records`, which `Scene::validate` now counts with; - the stats reply is `From`; - both paper scene schemas come from `paper_scene_schema`. Tests: the border then the views by id, byte for byte against the layout, with hand-worked outlines and lengths; the command's reply and its schema; the SVG's group order; each view against the snapshot, and one of many lines (a block with eight holes, from above); an empty sheet; a failed and a placeholder view; no evaluation; refusals; the record limit at exactly 100,000 and one past it; a 200:1 view. Co-Authored-By: Claude Opus 5.5 --- assets/locales/en.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/engine/src/cmd/drawing_scene.rs | 48 ++++ crates/engine/src/cmd/drawing_view.rs | 21 +- crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/drawing_scene.rs | 213 +++++++++++++++++ crates/engine/src/drawing_scene_tests.rs | 266 ++++++++++++++++++++++ crates/engine/src/drawing_view.rs | 16 +- crates/engine/src/lib.rs | 1 + crates/engine/src/schema/drawing_scene.rs | 60 +++++ crates/engine/src/schema/drawing_view.rs | 83 +++++-- crates/engine/src/schema/mod.rs | 1 + crates/geom/src/paper.rs | 25 +- crates/geom/src/paper_tests.rs | 2 + 15 files changed, 691 insertions(+), 50 deletions(-) create mode 100644 crates/engine/src/cmd/drawing_scene.rs create mode 100644 crates/engine/src/drawing_scene.rs create mode 100644 crates/engine/src/drawing_scene_tests.rs create mode 100644 crates/engine/src/schema/drawing_scene.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 2f38f8b2090..4b8214a851c 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -581,6 +581,7 @@ "cmd.drawing_revision_add": "Add Revision", "cmd.drawing_revision_delete": "Delete Revision", "cmd.drawing_revision_edit": "Edit Revision", + "cmd.drawing_scene": "Draw Sheet", "cmd.drawing_set": "Drawing Settings", "cmd.drawing_sheet_add": "Add Sheet", "cmd.drawing_sheet_delete": "Delete Sheet", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 939c3041bee..92d6b561477 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -581,6 +581,7 @@ "cmd.drawing_revision_add": "リビジョンを追加", "cmd.drawing_revision_delete": "リビジョンを削除", "cmd.drawing_revision_edit": "リビジョンを編集", + "cmd.drawing_scene": "シートを描画", "cmd.drawing_set": "図面設定", "cmd.drawing_sheet_add": "シートを追加", "cmd.drawing_sheet_delete": "シートを削除", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 217db880818..53a1793ef0d 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -581,6 +581,7 @@ "cmd.drawing_revision_add": "添加版本", "cmd.drawing_revision_delete": "删除版本", "cmd.drawing_revision_edit": "编辑版本", + "cmd.drawing_scene": "绘制图纸", "cmd.drawing_set": "绘图设置", "cmd.drawing_sheet_add": "添加图纸", "cmd.drawing_sheet_delete": "删除图纸", diff --git a/crates/engine/src/cmd/drawing_scene.rs b/crates/engine/src/cmd/drawing_scene.rs new file mode 100644 index 00000000000..af669e94dca --- /dev/null +++ b/crates/engine/src/cmd/drawing_scene.rs @@ -0,0 +1,48 @@ +//! `drawing.scene` (#4890 W10): one sheet of the open drawing as one paper scene, drawn at once +//! ([`crate::drawing_scene::build`]): its drawing border, then each view on it by id. The sheet +//! page draws the same scene through the provider, and the drawing export (A7) writes it. + +use serde_json::Value; +use solidcraft_doc::ids; + +use super::CommandSpec; +use crate::drawing_scene::{CMD, Status}; +use crate::params::bad; +use crate::schema::drawing_scene::{SheetPaperScene, SheetSceneParams, SheetSceneResult, SheetSceneView}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session}; + +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Draw Sheet", crate::checked!("drawing.scene", CONTRACT, scene)) + .icon("export") + .in_drawing() + .noundo() + .doc_only() + .contract(&CONTRACT) + .output(output_schema_for::) + .params("sheet: id or name → {sheet, scene: {size_mm, groups: [{object, kind: drawing_border|view, items: [{kind: stroke, path, closed, width_mm} or {kind: fill, region}]}]} in paint order: the sheet's drawing border (object: the sheet), then each view on it by id (object: the view; its visible lines only for now), views: [{view, status: drawn|placeholder|failed, reason?, stats?}]}. A view with nothing to measure, or one that can't be drawn yet, is left out and says why. Read-only; no model is evaluated.")]; + +fn scene(s: &mut Session, p: &Value) -> Result { + let request: SheetSceneParams = crate::schema::read(CMD, p)?; + let d = s.drawing(CMD)?.clone(); + let at = d.sheet_index(&request.sheet).map_err(|e| bad(CMD, e.to_string()))?; + let sheet = d.sheets.get(at).map(|sheet| sheet.id).ok_or_else(|| bad(CMD, format!("no sheet `{}`", request.sheet)))?; + let built = crate::drawing_scene::build(s, &d, sheet)?; + let views = built + .views + .into_iter() + .map(|v| SheetSceneView { + view: ids::encode(v.view), + status: v.status.name(), + reason: match v.status { + Status::Drawn => None, + Status::Placeholder(why) => Some(why.to_string()), + Status::Failed(why) => Some(why), + }, + stats: v.stats.map(Into::into), + }) + .collect(); + let reply = SheetSceneResult { sheet: ids::encode(sheet), scene: SheetPaperScene(built.scene), views, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} diff --git a/crates/engine/src/cmd/drawing_view.rs b/crates/engine/src/cmd/drawing_view.rs index d92fd6d0e61..31bb0609e54 100644 --- a/crates/engine/src/cmd/drawing_view.rs +++ b/crates/engine/src/cmd/drawing_view.rs @@ -39,8 +39,8 @@ use crate::drawing_view::{CHORD_RANGE, Extents, Lines, MAX_PATH_IDS, MAX_PATHS, use crate::params::bad; use crate::schema::drawing_view::{ AccuracyResult, BoxResult, ChoicesResult, CopyParams, DPI_RANGE, EditParams, EditResult, ExtentsResult, FromResult, InspectParams, InspectResult, - LineResult, LineSourceResult, LinesStatsResult, LinesStatusResult, MoveParams, OutsideResult, PathSegResult, PieceResult, PlaceParam, - ScaleResult, SceneResult, SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult, ToSheetResult, ViewResult, ViewSet, + LineResult, LineSourceResult, LinesStatusResult, MoveParams, OutsideResult, PathSegResult, PieceResult, PlaceParam, ScaleResult, SceneResult, + SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult, ToSheetResult, ViewResult, ViewSet, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; @@ -97,11 +97,8 @@ fn snapshot(s: &mut Session, p: &Value) -> Result { let request: SnapshotParams = crate::schema::read(CMD, p)?; let settings = request.settings(); let basis = settings.validate().map_err(|e| bad(CMD, e.to_string()))?; - if settings.display_style.is_shaded() || settings.reference_style.is_shaded() { - return Err(bad(CMD, "not supported yet: shaded views need the drawing renderer (#5624)")); - } - if request.scene && settings.display_style == VisualStyle::VisibleHidden { - return Err(bad(CMD, "not supported yet: hidden lines in the paper scene need dashed lines (#4890 A5)")); + if let Some(why) = crate::drawing_view::not_drawable(settings.display_style, settings.reference_style, request.scene) { + return Err(bad(CMD, why)); } if !(request.sheet.dpi.is_finite() && DPI_RANGE.contains(&request.sheet.dpi)) { return Err(bad(CMD, format!("sheet.dpi is a number from {} to {}", DPI_RANGE.start(), DPI_RANGE.end()))); @@ -178,15 +175,7 @@ fn snapshot(s: &mut Session, p: &Value) -> Result { uncertain_pieces: 0, covered_pieces: drawn.covered, }, - stats: LinesStatsResult { - bodies: drawn.stats.bodies, - shared_meshes: drawn.stats.shared_meshes, - triangles: drawn.stats.triangles, - segments: drawn.stats.segments, - prepare_ms: drawn.stats.prepare_ms, - projection_ms: drawn.stats.projection_ms, - occlusion_ms: drawn.stats.occlusion_ms, - }, + stats: drawn.stats.into(), scene, source: SourceResult { bodies: extents.bodies, timeline_at_end: s.doc.marker.is_none() }, param_warnings: Vec::new(), diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 57f71f1e133..e2f1d133e8d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -35,6 +35,7 @@ mod drawing; mod drawing_balloon; mod drawing_dimension; mod drawing_revision; +mod drawing_scene; mod drawing_sheet; mod drawing_view; mod edit; @@ -345,6 +346,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(drawing_balloon::COMMANDS.iter()); v.extend(drawing_dimension::COMMANDS.iter()); v.extend(drawing_revision::COMMANDS.iter()); + v.extend(drawing_scene::COMMANDS.iter()); v.extend(drawing_sheet::COMMANDS.iter()); v.extend(drawing_view::COMMANDS.iter()); v.extend(diagnostics::COMMANDS.iter()); diff --git a/crates/engine/src/drawing_scene.rs b/crates/engine/src/drawing_scene.rs new file mode 100644 index 00000000000..da757f6b18d --- /dev/null +++ b/crates/engine/src/drawing_scene.rs @@ -0,0 +1,213 @@ +//! The sheet scene (#4890 W10, #3890 W15): everything drawn on one sheet of a drawing as one paper +//! scene ([`Scene`]), for the sheet page and every export, so the screen and the files draw the +//! same thing. In paint order: the sheet's drawing border ([`SheetLayout::paper`]), then each view +//! on the sheet by id, its visible lines as [`paper_group`] makes them. Text, the title block, +//! tables, hidden lines and shaded views each join as one more kind of group. +//! +//! [`build`] draws a sheet at once, each view the one way: its lines worked out centred on the view, +//! then moved to its centre, so the same lines on the same centre are the same bytes however they +//! got there. It reads the model as it is: no model is evaluated. +//! +//! [`SheetLayout::paper`]: solidcraft_geom::drawing_sheet::SheetLayout::paper + +use std::borrow::Borrow; + +use solidcraft_doc::drawing::view::ResolvedView; +use solidcraft_doc::drawing::{Drawing, Sheet}; +use solidcraft_doc::drawing_view::TangentEdges; +use solidcraft_doc::{DocError, ids}; +use solidcraft_geom::paper::{Group, Item, MAX_RECORDS, Scene}; +use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; + +use crate::drawing_view::{CHORD_MM, MIN_MODEL_CHORD_MM, ShownSet, Stats, Unmeasured, paper_group}; +use crate::params::bad; +use crate::{EngineError, Result, Session}; + +/// The command the sheet scene answers for, in its errors. +pub const CMD: &str = "drawing.scene"; + +/// What became of one view of a sheet scene. +#[derive(Clone, Debug, PartialEq)] +pub enum Status { + /// Its visible lines are in the scene. + Drawn, + /// It has nothing to measure, so it draws nothing: the sheet page shows its placeholder. + Placeholder(Unmeasured), + /// It can't be drawn yet, or its lines are more than a paper scene holds: why. The sheet's + /// other views are drawn all the same. + Failed(String), +} + +impl Status { + /// Its name in replies. + pub fn name(&self) -> &'static str { + match self { + Status::Drawn => "drawn", + Status::Placeholder(_) => "placeholder", + Status::Failed(_) => "failed", + } + } +} + +/// One view of a sheet scene. +#[derive(Clone, Debug)] +pub struct ViewState { + pub view: u64, + pub status: Status, + /// What working out its lines cost, when they were. + pub stats: Option, +} + +/// One sheet drawn at once ([`build`]). +#[derive(Clone, Debug)] +pub struct SheetScene { + pub scene: Scene, + /// Each view on the sheet, in id order. + pub views: Vec, +} + +/// Sheet `sheet` of `drawing`, one of `s`'s design's drawings, drawn at once: its border, then each +/// of its views by id. A view with nothing to measure, or one that can't be drawn, is left out and +/// says why; the sheet is refused only when it can't be drawn at all. +pub fn build(s: &Session, drawing: &Drawing, sheet: u64) -> Result { + let record = sheet_of(drawing, sheet)?; + let on = views_on(drawing, sheet)?; + // Worked out once for the sheet: every view draws from the same one. Each view's lines are + // placed as they are drawn, so at most one view's are held beside the scene. + let shown = crate::drawing_view::shown(s); + let drawn = on.iter().map(|(id, view, centre)| (*id, *centre, draw(s, &shown, *id, view))); + let (scene, views) = assemble(record, drawn)?; + Ok(SheetScene { scene, views }) +} + +/// A view's lines for a sheet scene, centred on the view, or why it has none. +#[derive(Clone, Debug)] +struct Drawn { + group: Option, + status: Status, + stats: Option, +} + +/// View `id`, drawing as `view` does, of the bodies `shown` holds: its visible lines, sampled at +/// [`CHORD_MM`] on paper, or coarser past 100:1, where that would ask the mesh for chords finer than +/// [`MIN_MODEL_CHORD_MM`]; centred on the view ([`assemble`] moves them to its centre). Lines past +/// the paper scene's [`MAX_RECORDS`] are refused here, so no view holds more than a scene takes. +fn draw(s: &Session, shown: &std::result::Result, id: u64, view: &ResolvedView) -> Drawn { + let none = |status| Drawn { group: None, status, stats: None }; + // A style that draws hidden lines is refused here too, so the lines below are visible ones. + if let Some(why) = crate::drawing_view::not_drawable(view.display_style.value, view.reference_style.value, true) { + return none(Status::Failed(why.into())); + } + // Every body the design places, until saved views have `source` and `hide` (V4) to keep a part. + let measured = shown.as_ref().map_err(|why| *why).and_then(|set| crate::drawing_view::measure(set, &view.basis).map(|e| (set, e))); + let (set, extents) = match measured { + Ok(measured) => measured, + Err(why) => return none(Status::Placeholder(why)), + }; + let around = extents.model.inflated(view.reference_margin_mm); + let tangent_edges = view.tangent_edges.value == TangentEdges::Show; + // The margin keeps the mesh's chord at or above its floor once divided back by the factor. + let chord_mm = CHORD_MM.max(MIN_MODEL_CHORD_MM * view.scale.value.factor() * (1.0 + 1e-9)); + let lines = crate::drawing_view::frame(view.basis, view.scale.value, &around, Vec2::ZERO, CMD) + .and_then(|frame| crate::drawing_view::lines(s, set, &frame, false, tangent_edges, chord_mm, CMD)); + match lines { + Ok(lines) => { + let group = paper_group(&lines, id); + if group.records() > MAX_RECORDS { + return none(Status::Failed(format!("its lines are more than a paper scene's {MAX_RECORDS} records: choose a smaller scale"))); + } + Drawn { group: Some(group), status: Status::Drawn, stats: Some(lines.stats) } + } + Err(e) => none(Status::Failed(reason(e))), + } +} + +/// The scene of sheet `record`: its border, then each of `views` (its id, centre and lines, in id +/// order) moved to its centre. A view that would take the scene past a paper scene's limits is left +/// out and says why, and the views after it are still drawn when they fit. +fn assemble>(record: &Sheet, views: impl Iterator) -> Result<(Scene, Vec)> { + let size_mm = record.sheet.size_mm().map_err(|e| bad(CMD, e.to_string()))?; + let border = match &record.border { + Some(border) => border.layout(&record.sheet).map_err(|e| bad(CMD, e.to_string()))?.paper(record.id), + None => Vec::new(), + }; + let mut records = border.iter().map(Group::records).fold(0usize, usize::saturating_add); + let mut scene = Scene { size_mm, groups: border }; + // Each view's group is counted onto the scene and checked alone on the sheet first, so one past + // the limits leaves out only itself, and checking costs one pass over each group. + let mut alone = Scene { size_mm, groups: Vec::with_capacity(1) }; + let mut states = Vec::new(); + for (view, centre, drawn) in views { + let drawn: &Drawn = drawn.borrow(); + let mut status = drawn.status.clone(); + if let Some(group) = &drawn.group { + let more = group.records(); + if records.saturating_add(more) > MAX_RECORDS { + status = Status::Failed(format!( + "with its lines the sheet is more than a paper scene's {MAX_RECORDS} records: put it on another sheet, or choose a smaller scale" + )); + } else { + alone.groups.push(moved(group, centre)); + match alone.validate() { + Ok(()) => { + records += more; + scene.groups.append(&mut alone.groups); + } + Err(e) => { + alone.groups.clear(); + status = Status::Failed(format!("{e}: choose a smaller scale")); + } + } + } + } + states.push(ViewState { view, status, stats: drawn.stats }); + } + scene.validate().map_err(|e| bad(CMD, e.to_string()))?; + Ok((scene, states)) +} + +/// `group` moved `by` on paper: each point plus `by`, exactly, so the same lines moved to the same +/// centre are the same bytes however they got there. +fn moved(group: &Group, by: Vec2) -> Group { + let segs = |path: &[Seg2]| -> Vec { + let shift = |seg: &Seg2| match *seg { + // An arc's centre moves; its radius and its angles stay. + Seg2::Arc { center, radius, start, sweep } => Seg2::Arc { center: center + by, radius, start, sweep }, + _ => seg.map_controls(|p| p + by), + }; + path.iter().map(shift).collect() + }; + let ring = |l: &Loop2| Loop2 { segs: segs(&l.segs) }; + let items = group.items.iter().map(|item| match item { + Item::Stroke { path, closed, width_mm } => Item::Stroke { path: segs(path), closed: *closed, width_mm: *width_mm }, + Item::Fill { region } => Item::Fill { region: Region2 { outer: ring(®ion.outer), holes: region.holes.iter().map(ring).collect() } }, + }); + Group { object: group.object, kind: group.kind, items: items.collect() } +} + +/// Sheet `sheet` of `d`. +fn sheet_of(d: &Drawing, sheet: u64) -> Result<&Sheet> { + d.sheets.iter().map(|s| &**s).find(|s| s.id == sheet).ok_or_else(|| bad(CMD, format!("the drawing has no sheet {}", ids::encode(sheet)))) +} + +/// The views on sheet `sheet` of `d`, in id order, each as it draws and with its centre. +fn views_on(d: &Drawing, sheet: u64) -> Result> { + let fail = |e: DocError| bad(CMD, e.to_string()); + let mut on: Vec = d.views.iter().filter(|v| v.sheet == sheet).map(|v| v.id).collect(); + on.sort_unstable(); + on.into_iter() + .map(|id| -> Result<(u64, ResolvedView, Vec2)> { Ok((id, d.resolve_view(id).map_err(fail)?, d.view_centre(id).map_err(fail)?)) }) + .collect() +} + +/// `e`'s message without the command's name: a view's reason in a sheet scene. +fn reason(e: EngineError) -> String { + match e { + EngineError::BadParams { msg, .. } => msg, + e => e.to_string(), + } +} + +#[cfg(test)] +#[path = "drawing_scene_tests.rs"] +mod tests; diff --git a/crates/engine/src/drawing_scene_tests.rs b/crates/engine/src/drawing_scene_tests.rs new file mode 100644 index 00000000000..8d649a42a23 --- /dev/null +++ b/crates/engine/src/drawing_scene_tests.rs @@ -0,0 +1,266 @@ +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_doc::MAX_PLACEMENT_DEPTH; +use solidcraft_doc::drawing::view::{View, ViewKind, ViewPlace}; +use solidcraft_doc::drawing_view::{ViewDirection, ViewOverrides}; +use solidcraft_geom::drawing_view::{NamedView, ProjectedSide}; +use solidcraft_geom::paper::ObjectKind; + +use super::*; +use crate::schema::drawing_scene::SheetSceneResult; +use crate::schema::output_schema_for; +use crate::schema::tests::conforms; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap() +} + +/// A block 100 x 50 x 20 mm along X, Y and Z from the origin, and a drawing of it on A3 with the +/// ISO border: the front view at 1:2 centred at (150, 150), and the view above it, the top view in +/// third angle, lined up with it at y 220. The session, the sheet and the two views' ids. +fn front_and_top() -> (Session, u64, [u64; 2]) { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 100, "width": 50, "height": 20, "body_name": "Block"})); + run(&mut s, "drawing.create", json!({})); + let mut d = (**s.drawing("test").unwrap()).clone(); + let mut id_source = solidcraft_doc::ids::IdSource::seeded(4890); + let (sheet, source) = (d.sheets[0].id, d.sources[0].id); + let mut add = |d: &mut Drawing, kind: ViewKind, place: ViewPlace, settings: ViewOverrides| { + let id = d.allocate_id(&mut id_source).unwrap(); + d.add_views([Arc::new(View { id, sheet, kind, place, settings, reference_margin_mm: 0.0 })]); + id + }; + let half = ViewOverrides { scale: Some("1:2".parse().unwrap()), ..ViewOverrides::default() }; + let front = add(&mut d, ViewKind::Base { source, view: ViewDirection::Named(NamedView::Front) }, ViewPlace::At([150.0, 150.0]), half); + let top = add(&mut d, ViewKind::Projected { parent: front, side: ProjectedSide::Above }, ViewPlace::Aligned(220.0), ViewOverrides::default()); + d.validate().unwrap(); + s.doc_mut().put_drawing(Arc::new(d)); + (s, sheet, [front, top]) +} + +/// Component `L{level}`, placed inside `L{level - 1}` (the design itself at level 0). +fn nest(s: &mut Session, level: u64) { + let (component, parent) = (1000 + level, if level == 0 { 0 } else { 1000 + level - 1 }); + let doc = s.doc_mut(); + doc.components.push(solidcraft_doc::Component { id: component, name: format!("L{level}"), parent, ..Default::default() }); + let name = format!("L{level}"); + // From JSON, so a field another change adds to occurrences takes its default here. + let occurrence = json!({"id": 5000 + level, "component": component, "parent": parent, "name": name}); + doc.occurrences.push(serde_json::from_value(occurrence).unwrap()); +} + +/// Sheet `sheet` of the drawing open, built at once. +fn built(s: &Session, sheet: u64) -> SheetScene { + let d = s.drawing("test").unwrap().clone(); + build(s, &d, sheet).unwrap() +} + +/// The scene as its JSON text: what byte for byte compares. +fn bytes(scene: &Scene) -> String { + serde_json::to_string(scene).unwrap() +} + +/// The drawing border's groups of sheet `sheet` of the drawing open, as its sheet layout draws them. +fn border(s: &Session, sheet: u64) -> Vec { + let d = s.drawing("test").unwrap(); + let record = d.sheets.iter().find(|x| x.id == sheet).unwrap(); + record.border.as_ref().unwrap().layout(&record.sheet).unwrap().paper(sheet) +} + +/// The box round the ends of `group`'s stroke pieces, and how long they are in all. +fn reach(group: &Group) -> (Vec2, Vec2, f64) { + let (mut lo, mut hi, mut length) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY), 0.0); + for item in &group.items { + let Item::Stroke { path, .. } = item else { continue }; + for seg in path { + for p in [seg.start(), seg.end()] { + lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); + hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); + } + length += seg.length(); + } + } + (lo, hi, length) +} + +/// Whether `a` and `b` are the same strokes in the same order, their pieces' ends within `tol`. +fn same_within(a: &Group, b: &Group, tol: f64) -> bool { + let near = |s: &Seg2, t: &Seg2| s.start().dist(t.start()) <= tol && s.end().dist(t.end()) <= tol; + a.items.len() == b.items.len() + && a.items.iter().zip(&b.items).all(|pair| match pair { + (Item::Stroke { path: p, closed: c, width_mm: w }, Item::Stroke { path: q, closed: d, width_mm: v }) => { + c == d && w == v && p.len() == q.len() && p.iter().zip(q).all(|(s, t)| near(s, t)) + } + _ => false, + }) +} + +/// The scene is the sheet's three border groups as its layout draws them, byte for byte, then the +/// two views in id order: the front view round its 50 x 10 mm outline centred at (150, 150), 120 mm +/// of line in all, the top view round 50 x 25 mm centred at (150, 220), 150 mm. The command answers +/// the same scene, matching its schema, and the SVG writer takes it with the border's three groups +/// before the views'. +#[test] +fn a_sheet_is_its_border_then_its_views_by_id() { + let (mut s, sheet, [front, top]) = front_and_top(); + let SheetScene { scene, views } = built(&s, sheet); + let border = border(&s, sheet); + assert_eq!(border.len(), 3); + assert_eq!(serde_json::to_string(&scene.groups[..3]).unwrap(), serde_json::to_string(&border).unwrap()); + let order = if front < top { [front, top] } else { [top, front] }; + let tail: Vec<(u64, ObjectKind)> = scene.groups[3..].iter().map(|g| (g.object, g.kind)).collect(); + assert_eq!(tail, order.map(|id| (id, ObjectKind::View))); + for (id, lo, hi, length) in [(front, [125.0, 145.0], [175.0, 155.0], 120.0), (top, [125.0, 207.5], [175.0, 232.5], 150.0)] { + let (min, max, drawn) = reach(scene.groups.iter().find(|g| g.object == id).unwrap()); + assert!(min.dist(Vec2::from(lo)) < 1e-6 && max.dist(Vec2::from(hi)) < 1e-6 && (drawn - length).abs() < 1e-6, "{id}: {min:?} {max:?} {drawn}"); + } + let statuses: Vec<(u64, Status)> = views.iter().map(|v| (v.view, v.status.clone())).collect(); + assert_eq!(statuses, order.map(|id| (id, Status::Drawn))); + + let reply = run(&mut s, CMD, json!({"sheet": "Sheet 1"})); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + assert_eq!(reply["scene"], serde_json::to_value(&scene).unwrap()); + let replied: Vec<(Value, Value)> = reply["views"].as_array().unwrap().iter().map(|v| (v["view"].clone(), v["status"].clone())).collect(); + assert_eq!(replied, order.map(|id| (json!(ids::encode(id)), json!("drawn")))); + + let (svg, _) = solidcraft_io::paper::paper_svg(&scene.prepare().unwrap()).unwrap(); + let svg = String::from_utf8(svg).unwrap(); + let borders: Vec = svg.match_indices("data-kind=\"drawing_border\"").map(|(at, _)| at).collect(); + let first_view = svg.find("data-kind=\"view\"").unwrap(); + assert!(borders.len() == 3 && borders.iter().all(|at| *at < first_view), "{svg}"); +} + +/// Each view's group is the snapshot's for the same view, scale and centre: the same strokes in the +/// same order, their ends within rounding. The scene works a view's lines out centred on it and +/// then moves them; the snapshot maps them to the centre in one step. +#[test] +fn each_view_draws_as_its_snapshot_within_rounding() { + let (mut s, sheet, [front, top]) = front_and_top(); + let scene = built(&s, sheet).scene; + // The snapshot works on the model, so with no drawing open. + run(&mut s, "drawing.close", json!({})); + for (id, named, at) in [(front, "front", [150.0, 150.0]), (top, "top", [150.0, 220.0])] { + let v = run(&mut s, "drawing.view.snapshot", json!({"view": named, "scale": "1:2", "position_mm": at, "scene": true})); + let snapped: Scene = serde_json::from_value(v["scene"].clone()).unwrap(); + let ours = scene.groups.iter().find(|g| g.object == id).unwrap(); + assert!(same_within(ours, &snapped.groups[0], 1e-9), "{id}: {ours:?} {:?}", snapped.groups[0]); + } +} + +/// A view of many lines is drawn whole, as its snapshot is: the block drilled with eight holes and +/// seen from above is its outline and the eight rims, some 30 records. +#[test] +fn a_view_of_many_lines_draws_as_its_snapshot() { + let (mut s, sheet, [_, top]) = front_and_top(); + let drawing = ids::encode(s.open_drawing.unwrap()); + run(&mut s, "drawing.close", json!({})); + for i in 0..8 { + let base = [12.5 + 25.0 * (i % 4) as f64, 12.5 + 25.0 * (i / 4) as f64, -1.0]; + run(&mut s, "solid.cylinder", json!({"diameter": 8, "height": 22, "base": base, "operation": "cut", "targets": ["Block"]})); + } + let v = run(&mut s, "drawing.view.snapshot", json!({"view": "top", "scale": "1:2", "position_mm": [150.0, 220.0], "scene": true})); + let snapped: Scene = serde_json::from_value(v["scene"].clone()).unwrap(); + run(&mut s, "drawing.open", json!({"drawing": drawing})); + let scene = built(&s, sheet); + let state = scene.views.iter().find(|v| v.view == top).unwrap(); + assert_eq!(state.status, Status::Drawn, "{state:?}"); + let ours = scene.scene.groups.iter().find(|g| g.object == top).unwrap(); + assert!(ours.records() > 20 && same_within(ours, &snapped.groups[0], 1e-9), "{ours:?} {:?}", snapped.groups[0]); +} + +/// A sheet with no views is its border alone. +#[test] +fn a_sheet_with_no_views_is_its_border() { + let (mut s, _, _) = front_and_top(); + let second = run(&mut s, "drawing.sheet.add", json!({}))["sheet"].as_str().and_then(ids::decode).unwrap(); + let SheetScene { scene, views } = built(&s, second); + assert_eq!((serde_json::to_string(&scene.groups).unwrap(), views.len()), (serde_json::to_string(&border(&s, second)).unwrap(), 0)); +} + +/// A view in a style the paper scene can't draw yet fails with the snapshot's reason, and a view +/// with nothing to measure is a placeholder; each draws nothing, and the sheet's other views and +/// its border are drawn all the same. The command says why for each. +#[test] +fn a_view_that_cant_be_drawn_leaves_out_only_itself() { + let (mut s, sheet, [front, top]) = front_and_top(); + let status = |s: &Session, id: u64| built(s, sheet).views.into_iter().find(|v| v.view == id).map(|v| v.status); + for (style, why) in [ + ("shaded", "not supported yet: shaded views need the drawing renderer (#5624)"), + ("visible_hidden", "not supported yet: hidden lines in the paper scene need dashed lines (#4890 A5)"), + ] { + run(&mut s, "drawing.view.edit", json!({"view": ids::encode(top), "set": {"display_style": style}})); + assert_eq!((status(&s, front), status(&s, top)), (Some(Status::Drawn), Some(Status::Failed(why.into()))), "{style}"); + let objects: Vec = built(&s, sheet).scene.groups.iter().map(|g| g.object).collect(); + assert_eq!(objects, [sheet, sheet, sheet, front], "{style}"); + } + let reply = run(&mut s, CMD, json!({"sheet": ids::encode(sheet)})); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + let failed = reply["views"].as_array().unwrap().iter().find(|v| v["view"] == ids::encode(top)).unwrap().clone(); + assert_eq!((&failed["status"], failed["reason"].as_str().map(|r| r.contains("dashed lines"))), (&json!("failed"), Some(true)), "{reply}"); + // Past the walk limit the front view has nothing to measure. + for level in 0..=MAX_PLACEMENT_DEPTH as u64 + 1 { + nest(&mut s, level); + } + assert_eq!(status(&s, front), Some(Status::Placeholder(Unmeasured::PastWalkLimit))); + assert_eq!(built(&s, sheet).scene.groups.len(), 3); +} + +/// The command evaluates no model. +#[test] +fn drawing_a_sheet_evaluates_no_model() { + let (mut s, sheet, _) = front_and_top(); + let before = s.evaluations; + run(&mut s, CMD, json!({"sheet": ids::encode(sheet)})); + assert_eq!(s.evaluations, before); +} + +/// An unknown sheet and another drawing's sheet are refused, and so is a sheet with no drawing open. +#[test] +fn unknown_and_other_drawings_sheets_are_refused() { + let (mut s, sheet, _) = front_and_top(); + let refused = |s: &mut Session, named: &str| s.execute(CMD, &json!({"sheet": named})).unwrap_err().to_string(); + assert!(refused(&mut s, "Sheet 9").contains("no sheet `Sheet 9`")); + run(&mut s, "drawing.create", json!({"name": "Second"})); + let first = ids::encode(sheet); + assert!(refused(&mut s, &first).contains(&format!("no sheet `{first}`"))); + run(&mut s, "drawing.close", json!({})); + assert!(refused(&mut s, &first).contains("open a drawing first")); +} + +/// A view whose lines would take the sheet past a paper scene's records fails and is left out; +/// a view after it that fits is still drawn, up to the limit exactly. +#[test] +fn a_view_past_the_sheets_records_leaves_out_only_itself() { + let (s, sheet, _) = front_and_top(); + let d = s.drawing("test").unwrap().clone(); + let record = d.sheets.iter().find(|x| x.id == sheet).unwrap(); + // One stroke of `n` pieces: n + 2 records with its group. + let lines = |n: usize| { + let path = (0..n).map(|i| Seg2::Line { a: Vec2::new(i as f64 * 1e-3, 0.0), b: Vec2::new((i + 1) as f64 * 1e-3, 0.0) }).collect(); + let items = vec![Item::Stroke { path, closed: false, width_mm: 0.5 }]; + Drawn { group: Some(Group { object: n as u64, kind: ObjectKind::View, items }), status: Status::Drawn, stats: None } + }; + let left = MAX_RECORDS - border(&s, sheet).iter().map(Group::records).sum::(); + // The first leaves 20 records; the second needs 32; the third takes the last 20. + let views = [lines(left - 22), lines(30), lines(18)]; + let centre = Vec2::new(100.0, 100.0); + let (scene, states) = assemble(record, views.iter().enumerate().map(|(i, v)| (i as u64, centre, v))).unwrap(); + let statuses: Vec<&'static str> = states.iter().map(|v| v.status.name()).collect(); + assert_eq!(statuses, ["drawn", "failed", "drawn"]); + assert_eq!((scene.groups.len(), scene.groups.iter().map(Group::records).sum::()), (5, MAX_RECORDS)); + assert!(matches!(&states[1].status, Status::Failed(why) if why.contains("put it on another sheet")), "{:?}", states[1]); +} + +/// A view at 200:1 asks the mesh for chords no finer than its floor, so it is drawn rather than +/// refused for a chord it has no setting for. +#[test] +fn a_view_past_100_to_1_is_drawn_with_a_coarser_chord() { + let (mut s, sheet, [front, _]) = front_and_top(); + run(&mut s, "drawing.view.edit", json!({"view": ids::encode(front), "set": {"scale": "200:1"}})); + let scene = built(&s, sheet); + let front = scene.views.iter().find(|v| v.view == front).unwrap(); + assert_eq!(front.status, Status::Drawn, "{front:?}"); +} diff --git a/crates/engine/src/drawing_view.rs b/crates/engine/src/drawing_view.rs index b3905cc9711..b284250bb49 100644 --- a/crates/engine/src/drawing_view.rs +++ b/crates/engine/src/drawing_view.rs @@ -13,6 +13,7 @@ use solidcraft_doc::drawing::Drawing; use solidcraft_doc::{MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, ModelBody, ModelState, ids}; use solidcraft_geom::drawing_view::{Scale, ViewFrame}; use solidcraft_geom::{Aabb2, EPS, Plane, Vec2}; +use solidcraft_render::VisualStyle; use crate::params::bad; use crate::{Result, Session}; @@ -20,7 +21,7 @@ use crate::{Result, Session}; #[path = "drawing_view_lines.rs"] mod lines; -pub use lines::{CHORD_MM, CHORD_RANGE, Lines, Piece, VISIBLE_MM, ViewLine, lines, paper_group}; +pub use lines::{CHORD_MM, CHORD_RANGE, Lines, MIN_MODEL_CHORD_MM, Piece, Stats, VISIBLE_MM, ViewLine, lines, paper_group}; /// The paper millimetres each way of a view's boundary when there's nothing to measure, round its /// centre, so it can still be picked, moved and deleted. @@ -149,6 +150,19 @@ pub struct OnSheet { pub unmeasured: Option, } +/// Why a view drawing in `display` and `reference` styles can't be drawn yet, if it can't: shaded +/// views need pictures, and a paper scene (`scene`) has no dashed lines for hidden ones. The +/// snapshot and the sheet scene refuse alike. +pub fn not_drawable(display: VisualStyle, reference: VisualStyle, scene: bool) -> Option<&'static str> { + if display.is_shaded() || reference.is_shaded() { + Some("not supported yet: shaded views need the drawing renderer (#5624)") + } else if scene && display == VisualStyle::VisibleHidden { + Some("not supported yet: hidden lines in the paper scene need dashed lines (#4890 A5)") + } else { + None + } +} + /// The extents of the bodies `shown` holds, seen on `basis`, or that they have nothing to measure. pub fn measure(shown: &ShownSet, basis: &Plane) -> std::result::Result { let bodies = shown.bodies.iter().filter_map(|b| shown.body(b)); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 84b6c7bb10f..6163c679420 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod capture; pub mod cmd; pub mod control_auth; pub mod crash; +pub mod drawing_scene; pub mod drawing_view; pub mod frames; pub mod fuzz; diff --git a/crates/engine/src/schema/drawing_scene.rs b/crates/engine/src/schema/drawing_scene.rs new file mode 100644 index 00000000000..bcefe24ce5f --- /dev/null +++ b/crates/engine/src/schema/drawing_scene.rs @@ -0,0 +1,60 @@ +//! Contracts and result types for `drawing.scene` (`cmd/drawing_scene.rs`, #4890). + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator}; +use serde::{Deserialize, Serialize}; +use solidcraft_geom::paper::ObjectKind; + +use super::drawing_sheet::sheet_ref; +use super::drawing_view::{LinesStatsResult, paper_scene_schema}; + +/// Draw one sheet of the open drawing. Read-only. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SheetSceneParams { + /// The sheet, by id or name. + #[serde(deserialize_with = "sheet_ref")] + pub sheet: String, +} + +/// A sheet's paper scene: its size and its groups in paint order, in paper millimetres from the +/// sheet's lower-left corner: the drawing border's (object: the sheet), then each view's strokes +/// (object: the view). +#[derive(Debug, Serialize)] +#[serde(transparent)] +pub struct SheetPaperScene(pub solidcraft_geom::paper::Scene); + +impl JsonSchema for SheetPaperScene { + fn schema_name() -> Cow<'static, str> { + "SheetPaperScene".into() + } + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + paper_scene_schema(generator, &[ObjectKind::DrawingBorder, ObjectKind::View], true) + } +} + +/// One view on the sheet: `drawn`, `placeholder` (nothing to measure, so no lines) or `failed`, +/// with why. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SheetSceneView { + pub view: String, + pub status: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// What working out its lines cost, when they were. + #[serde(skip_serializing_if = "Option::is_none")] + pub stats: Option, +} + +/// What `drawing.scene` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SheetSceneResult { + pub sheet: String, + pub scene: SheetPaperScene, + /// Each view on the sheet, in id order. + pub views: Vec, + /// 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, +} diff --git a/crates/engine/src/schema/drawing_view.rs b/crates/engine/src/schema/drawing_view.rs index 0f84e23d308..def5024ca34 100644 --- a/crates/engine/src/schema/drawing_view.rs +++ b/crates/engine/src/schema/drawing_view.rs @@ -15,10 +15,11 @@ use solidcraft_doc::drawing_view::{TangentEdges, ViewDirection, ViewSettings}; use solidcraft_geom::Seg2; use solidcraft_geom::drawing_sheet::{Orientation, PaperSize, SheetSize}; use solidcraft_geom::drawing_view::{NamedView, Scale}; +use solidcraft_geom::paper::ObjectKind; use solidcraft_geom::section::CurveAccuracy; use solidcraft_render::VisualStyle; -use crate::drawing_view::{CHORD_MM, CHORD_RANGE}; +use crate::drawing_view::{CHORD_MM, CHORD_RANGE, Stats}; use super::Point2; @@ -618,6 +619,20 @@ pub struct LinesStatsResult { pub occlusion_ms: f64, } +impl From for LinesStatsResult { + fn from(s: Stats) -> Self { + LinesStatsResult { + bodies: s.bodies, + shared_meshes: s.shared_meshes, + triangles: s.triangles, + segments: s.segments, + prepare_ms: s.prepare_ms, + projection_ms: s.projection_ms, + occlusion_ms: s.occlusion_ms, + } + } +} + /// A view's lines as a paper scene: the sheet's size and the view's one group of strokes (kind /// `view`, object 0), in paint order, in paper millimetres from the sheet's lower-left corner. #[derive(Debug, Serialize)] @@ -629,29 +644,55 @@ impl JsonSchema for SceneResult { "ViewPaperScene".into() } fn json_schema(generator: &mut SchemaGenerator) -> Schema { - let point = json!({"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}); - let segment = generator.subschema_for::(); - let stroke = json!({ - "type": "object", - "properties": {"kind": {"const": "stroke"}, "path": {"type": "array", "items": segment}, "closed": {"type": "boolean"}, "width_mm": {"type": "number", "exclusiveMinimum": 0}}, - "required": ["kind", "path", "closed", "width_mm"], - "additionalProperties": false - }); - let group = json!({ - "type": "object", - "properties": {"object": {"type": "integer", "minimum": 0}, "kind": {"const": "view"}, "items": {"type": "array", "items": stroke}}, - "required": ["object", "kind", "items"], - "additionalProperties": false - }); - json_schema!({ - "type": "object", - "properties": {"size_mm": point, "groups": {"type": "array", "items": group}}, - "required": ["size_mm", "groups"], - "additionalProperties": false - }) + paper_scene_schema(generator, &[ObjectKind::View], false) } } +/// A paper scene's schema ([`solidcraft_geom::paper::Scene`]): its groups of `kinds`, each holding +/// strokes, and fills too when `fills`. +pub(super) fn paper_scene_schema(generator: &mut SchemaGenerator, kinds: &[ObjectKind], fills: bool) -> Schema { + let point = json!({"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}); + let segment = generator.subschema_for::(); + let stroke = json!({ + "type": "object", + "properties": {"kind": {"const": "stroke"}, "path": {"type": "array", "items": segment}, "closed": {"type": "boolean"}, "width_mm": {"type": "number", "exclusiveMinimum": 0}}, + "required": ["kind", "path", "closed", "width_mm"], + "additionalProperties": false + }); + let ring = json!({ + "type": "object", + "properties": {"segs": {"type": "array", "items": segment}}, + "required": ["segs"], + "additionalProperties": false + }); + let region = json!({ + "type": "object", + "properties": {"outer": ring, "holes": {"type": "array", "items": ring}}, + "required": ["outer", "holes"], + "additionalProperties": false + }); + let fill = json!({ + "type": "object", + "properties": {"kind": {"const": "fill"}, "region": region}, + "required": ["kind", "region"], + "additionalProperties": false + }); + let items = if fills { json!({"anyOf": [stroke, fill]}) } else { stroke }; + let kinds: Vec = kinds.iter().filter_map(|kind| serde_json::to_value(kind).ok()).collect(); + let group = json!({ + "type": "object", + "properties": {"object": {"type": "integer", "minimum": 0}, "kind": {"enum": kinds}, "items": {"type": "array", "items": items}}, + "required": ["object", "kind", "items"], + "additionalProperties": false + }); + json_schema!({ + "type": "object", + "properties": {"size_mm": point, "groups": {"type": "array", "items": group}}, + "required": ["size_mm", "groups"], + "additionalProperties": false + }) +} + /// What `drawing.view.snapshot` returns. #[derive(Debug, Serialize, JsonSchema)] pub struct SnapshotResult { diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 07ac2c582da..297a837937a 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -49,6 +49,7 @@ pub(crate) mod tests; pub mod drawing_balloon; pub mod drawing_dimension; pub mod drawing_revision; +pub mod drawing_scene; pub mod drawing_sheet; pub mod drawing_view; pub mod features; diff --git a/crates/geom/src/paper.rs b/crates/geom/src/paper.rs index e8540bd30a9..e045dda43f7 100644 --- a/crates/geom/src/paper.rs +++ b/crates/geom/src/paper.rs @@ -67,6 +67,18 @@ pub struct Group { pub items: Vec, } +impl Group { + /// The records the group counts toward [`MAX_RECORDS`]: itself, each item, each stroke's pieces, + /// and each loop of a fill with its pieces. Saturates rather than overflows. + pub fn records(&self) -> usize { + let item = |item: &Item| match item { + Item::Stroke { path, .. } => path.len(), + Item::Fill { region } => region.loops().fold(0usize, |n, l| n.saturating_add(1).saturating_add(l.segs.len())), + }; + self.items.iter().fold(1usize, |n, i| n.saturating_add(1).saturating_add(item(i))) + } +} + /// What kind of object drew a group. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -181,19 +193,8 @@ impl Scene { /// Checks the scene against the limits in the module's notes, counting its records first. pub fn validate(&self) -> Result<()> { let mut budget = Budget(0); - budget.add(self.groups.len())?; for group in &self.groups { - budget.add(group.items.len())?; - for item in &group.items { - match item { - Item::Stroke { path, .. } => budget.add(path.len())?, - Item::Fill { region } => { - for l in region.loops() { - budget.add(1 + l.segs.len())?; - } - } - } - } + budget.add(group.records())?; } let Vec2 { x, y } = self.size_mm; require([x, y].into_iter().all(|side| side > 0.0 && side <= MAX_SIDE_MM), "each side of the sheet is above 0 and at most 5000 mm")?; diff --git a/crates/geom/src/paper_tests.rs b/crates/geom/src/paper_tests.rs index 3c6135de0de..88eda91c45d 100644 --- a/crates/geom/src/paper_tests.rs +++ b/crates/geom/src/paper_tests.rs @@ -252,6 +252,7 @@ fn at_most_100_000_records_are_counted_before_any_geometry() { // One group and one stroke, then its pieces. let steps = |n: usize| -> Vec { (0..n).map(|i| line(p(i as f64 * 1e-3, 0.0), p((i + 1) as f64 * 1e-3, 0.0))).collect() }; scene(vec![group(vec![stroke(steps(MAX_RECORDS - 2), false, 0.35)])]).validate().unwrap(); + assert_eq!(group(vec![stroke(steps(MAX_RECORDS - 2), false, 0.35)]).records(), MAX_RECORDS); assert_eq!(scene(vec![group(vec![stroke(steps(MAX_RECORDS - 1), false, 0.35)])]).validate(), Err(REFUSED)); // A fill counts each loop as well as its pieces: 2 + (1 + 5) + 49,996 × (1 + 1) = 100,000. let holes = vec![Loop2 { segs: vec![Seg2::Arc { center: p(200.0, 150.0), radius: 1.0, start: 0.0, sweep: TAU }] }; 49_996]; @@ -260,6 +261,7 @@ fn at_most_100_000_records_are_counted_before_any_geometry() { Loop2::polygon(&corners) }; scene(vec![group(vec![fill(polygon(5), holes.clone())])]).validate().unwrap(); + assert_eq!(group(vec![fill(polygon(5), holes.clone())]).records(), MAX_RECORDS); assert_eq!(scene(vec![group(vec![fill(polygon(6), holes)])]).validate(), Err(REFUSED)); // Counted first: an over-budget scene with a non-finite piece reports the count. let mut bad = steps(MAX_RECORDS - 1); From f21db0021f070cb94bf2502941894e98f25dada3 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Tue, 27 Oct 2026 13:42:08 +0000 Subject: [PATCH 3/3] Drawing sheets on paper: the provider the sheet page draws through (#4890 W10, #3890 W15) The sheet page asks for a sheet every frame, so it draws through a provider that keeps each view's lines between frames, instead of through `build`. - `drawing_scene::extract(session, sheet)` returns the last scene at once, with each view as it was last drawn and the ones out of date. Nothing is drawn there. When the drawing, the world state and the views drawn are all as they were, it returns the same answer without looking at the sheet. - `drawing_scene::step(session)` draws the first out-of-date view of the sheet last extracted and says whether more wait: a short piece of work for the UI's tick, one view's projection. - `generation` comes from one counter for every session. It goes up only when a sheet's scene is assembled again, so a page never sees one number for two scenes, even across closing and opening its drawing. The cache is the session's view state, beside the record: never saved, never an undo step. `Session::execute` drops it when a command closes the drawing or opens another. One entry per view, keyed by the world state it was drawn from (held in the entry and compared with `Arc::ptr_eq`) and the view as it resolves. A drawing-only edit keeps the world state, so a move, and its undo, project nothing: the same centred lines are moved to the new centre. The shown set is worked out once per world state. Views no longer in the drawing are forgotten when a scene is assembled again. Tests: - a new cache gives the border with both views out of date; - each step draws one view, in id order, until the scene is `build`'s, byte for byte; - the generation stays put while nothing changes; - a move and its undo project nothing, and the views move by exactly the move; - after a model change (a checkpoint restored) the last scene shows, and a view listed as up to date always draws as `build` does; - closing drops the cache, and the scene after reopening has a new generation; - seeded mixes of moves, setting edits, undos, redos, extracts and steps always end at `build`'s scene. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/drawing_scene.rs | 156 ++++++++++++++++++++++- crates/engine/src/drawing_scene_tests.rs | 151 +++++++++++++++++++++- crates/engine/src/lib.rs | 7 + 3 files changed, 312 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/drawing_scene.rs b/crates/engine/src/drawing_scene.rs index da757f6b18d..db7841af776 100644 --- a/crates/engine/src/drawing_scene.rs +++ b/crates/engine/src/drawing_scene.rs @@ -8,14 +8,24 @@ //! then moved to its centre, so the same lines on the same centre are the same bytes however they //! got there. It reads the model as it is: no model is evaluated. //! +//! The sheet page draws through the provider instead, which keeps each view's lines between frames: +//! [`extract`] returns the last scene at once and says which views are out of date, and [`step`] +//! brings one of them up to date, a short piece of work for the UI's tick. A view moved across its +//! sheet is moved, never projected again. The provider evaluates no model either. Its cache is the +//! session's view state, beside the drawing: never saved, never an undo step, and dropped when its +//! drawing closes. +//! //! [`SheetLayout::paper`]: solidcraft_geom::drawing_sheet::SheetLayout::paper use std::borrow::Borrow; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use solidcraft_doc::drawing::view::ResolvedView; use solidcraft_doc::drawing::{Drawing, Sheet}; use solidcraft_doc::drawing_view::TangentEdges; -use solidcraft_doc::{DocError, ids}; +use solidcraft_doc::{DocError, ModelState, ids}; use solidcraft_geom::paper::{Group, Item, MAX_RECORDS, Scene}; use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; @@ -26,6 +36,10 @@ use crate::{EngineError, Result, Session}; /// The command the sheet scene answers for, in its errors. pub const CMD: &str = "drawing.scene"; +/// Numbers every scene the provider assembles, in every session, so a page never sees one number +/// for two scenes, not even across closing and opening its drawing. +static GENERATION: AtomicU64 = AtomicU64::new(0); + /// What became of one view of a sheet scene. #[derive(Clone, Debug, PartialEq)] pub enum Status { @@ -66,6 +80,19 @@ pub struct SheetScene { pub views: Vec, } +/// One sheet as the provider last drew it ([`extract`]). +#[derive(Clone, Debug)] +pub struct SheetView { + pub scene: Arc, + /// Goes up each time `scene` changes, so the page redraws only then. + pub generation: u64, + /// Each view on the sheet drawn so far, in id order, as it was last drawn. + pub views: Vec, + /// The views out of date, in id order: not drawn yet, or drawn from another model or with other + /// settings than they have now. Their last lines stay in the scene until [`step`] draws them. + pub stale: Vec, +} + /// Sheet `sheet` of `drawing`, one of `s`'s design's drawings, drawn at once: its border, then each /// of its views by id. A view with nothing to measure, or one that can't be drawn, is left out and /// says why; the sheet is refused only when it can't be drawn at all. @@ -208,6 +235,133 @@ fn reason(e: EngineError) -> String { } } +/// The provider's cache: per view, the lines it was last drawn with. The session holds one, for +/// the drawing open. +#[derive(Default)] +pub struct Cache { + /// The drawing it is for. + drawing: Option, + /// The sheet last extracted: the one [`step`] brings up to date. + sheet: Option, + /// Each view's last drawing, by id. + views: BTreeMap, + /// The shown set of the world state views were last drawn from, worked out once for it. + shown: Option<(Arc, std::result::Result)>, + last: Option, + /// Numbers each view drawn, so a scene is assembled again only when one of its views was. + serial: u64, + /// Views drawn, for tests: a move draws none. + #[cfg(test)] + projections: usize, +} + +/// A view's last drawing, and what it was drawn from: the world state (held, so its address can't +/// be reused while it is compared) and the view as it drew. +struct Entry { + state: Arc, + view: ResolvedView, + drawn: Drawn, + serial: u64, +} + +/// What a scene is assembled from: the sheet's record, and each view on it with its entry's serial +/// (0: not drawn yet) and its centre. +#[derive(PartialEq)] +struct Inputs { + sheet: Sheet, + views: Vec<(u64, u64, Vec2)>, +} + +/// The last answer of [`extract`], for the sheet, drawing, world state and serial it was for: the +/// same four again return it as it is. +struct Assembled { + sheet: u64, + drawing: Arc, + state: Arc, + serial: u64, + inputs: Inputs, + answer: SheetView, +} + +impl Cache { + /// Whether view `id`, drawing as `view` now, was last drawn so, from `state`. + fn fresh(&self, id: u64, state: &Arc, view: &ResolvedView) -> bool { + self.views.get(&id).is_some_and(|e| Arc::ptr_eq(&e.state, state) && e.view == *view) + } +} + +/// Sheet `sheet` of the drawing open, as the provider last drew it: at once, as nothing is drawn +/// here. The first call for a sheet gives its border, with every view out of date. +pub fn extract(s: &mut Session, sheet: u64) -> Result { + forget_closed(s); + let d = s.drawing(CMD)?.clone(); + let state = s.world_state(); + let cache = &mut s.drawing_scenes; + if let Some(last) = &cache.last + && last.sheet == sheet + && last.serial == cache.serial + && Arc::ptr_eq(&last.drawing, &d) + && Arc::ptr_eq(&last.state, &state) + { + return Ok(last.answer.clone()); + } + let record = sheet_of(&d, sheet)?; + let on = views_on(&d, sheet)?; + cache.drawing = Some(d.id); + cache.sheet = Some(sheet); + let stale = on.iter().filter(|(id, view, _)| !cache.fresh(*id, &state, view)).map(|(id, ..)| *id).collect(); + let serial = |id: &u64| cache.views.get(id).map_or(0, |e| e.serial); + let inputs = Inputs { sheet: record.clone(), views: on.iter().map(|(id, _, centre)| (*id, serial(id), *centre)).collect() }; + let (scene, views, generation) = match cache.last.take() { + Some(last) if last.inputs == inputs => (last.answer.scene, last.answer.views, last.answer.generation), + _ => { + // Views no longer in the drawing are forgotten: each holds a world state. + let kept: BTreeSet = d.views.iter().map(|v| v.id).collect(); + cache.views.retain(|id, _| kept.contains(id)); + let drawn = on.iter().filter_map(|(id, _, centre)| cache.views.get(id).map(|e| (*id, *centre, &e.drawn))); + let (scene, views) = assemble(record, drawn)?; + (Arc::new(scene), views, GENERATION.fetch_add(1, Ordering::Relaxed).wrapping_add(1)) + } + }; + let answer = SheetView { scene, generation, views, stale }; + cache.last = Some(Assembled { sheet, drawing: d, state, serial: cache.serial, inputs, answer: answer.clone() }); + Ok(answer) +} + +/// Draws the first view out of date on the sheet last extracted, and says whether more are +/// waiting: a short piece of work for the UI's tick, one view's projection. +pub fn step(s: &mut Session) -> bool { + forget_closed(s); + let (Ok(d), Some(sheet)) = (s.drawing(CMD).cloned(), s.drawing_scenes.sheet) else { return false }; + let Ok(on) = views_on(&d, sheet) else { return false }; + let state = s.world_state(); + let waiting: Vec<(u64, ResolvedView)> = + on.into_iter().filter(|(id, view, _)| !s.drawing_scenes.fresh(*id, &state, view)).map(|(id, view, _)| (id, view)).collect(); + let Some(&(id, view)) = waiting.first() else { return false }; + let shown = match s.drawing_scenes.shown.take() { + Some((was, shown)) if Arc::ptr_eq(&was, &state) => shown, + _ => crate::drawing_view::shown(s), + }; + let drawn = draw(s, &shown, id, &view); + let cache = &mut s.drawing_scenes; + cache.shown = Some((state.clone(), shown)); + cache.serial += 1; + cache.views.insert(id, Entry { state, view, drawn, serial: cache.serial }); + #[cfg(test)] + { + cache.projections += 1; + } + waiting.len() > 1 +} + +/// Drops the cache once its drawing isn't the one open: closing a drawing (or opening another) ends +/// its scenes, and the world states they hold. [`Session::execute`] calls it after every command. +pub(crate) fn forget_closed(s: &mut Session) { + if s.drawing_scenes.drawing.is_some_and(|d| s.open_drawing != Some(d)) { + s.drawing_scenes = Cache::default(); + } +} + #[cfg(test)] #[path = "drawing_scene_tests.rs"] mod tests; diff --git a/crates/engine/src/drawing_scene_tests.rs b/crates/engine/src/drawing_scene_tests.rs index 8d649a42a23..c58350eda9b 100644 --- a/crates/engine/src/drawing_scene_tests.rs +++ b/crates/engine/src/drawing_scene_tests.rs @@ -56,6 +56,13 @@ fn built(s: &Session, sheet: u64) -> SheetScene { build(s, &d, sheet).unwrap() } +/// The provider's scene of `sheet` once nothing is waiting. +fn settled(s: &mut Session, sheet: u64) -> SheetView { + extract(s, sheet).unwrap(); + while step(s) {} + extract(s, sheet).unwrap() +} + /// The scene as its JSON text: what byte for byte compares. fn bytes(scene: &Scene) -> String { serde_json::to_string(scene).unwrap() @@ -208,12 +215,13 @@ fn a_view_that_cant_be_drawn_leaves_out_only_itself() { assert_eq!(built(&s, sheet).scene.groups.len(), 3); } -/// The command evaluates no model. +/// Neither the command nor the provider evaluates the model. #[test] fn drawing_a_sheet_evaluates_no_model() { let (mut s, sheet, _) = front_and_top(); let before = s.evaluations; run(&mut s, CMD, json!({"sheet": ids::encode(sheet)})); + settled(&mut s, sheet); assert_eq!(s.evaluations, before); } @@ -226,8 +234,115 @@ fn unknown_and_other_drawings_sheets_are_refused() { run(&mut s, "drawing.create", json!({"name": "Second"})); let first = ids::encode(sheet); assert!(refused(&mut s, &first).contains(&format!("no sheet `{first}`"))); + assert!(extract(&mut s, sheet).unwrap_err().to_string().contains("the drawing has no sheet")); run(&mut s, "drawing.close", json!({})); assert!(refused(&mut s, &first).contains("open a drawing first")); + assert!(extract(&mut s, sheet).is_err() && !step(&mut s)); +} + +/// A new cache gives the border with both views out of date and draws nothing; each step draws one +/// view, in id order; once nothing is waiting the scene is the built one, byte for byte. The +/// generation goes up each time the scene changes, and only then. +#[test] +fn the_provider_draws_a_view_a_step_until_it_is_the_built_scene() { + let (mut s, sheet, [front, top]) = front_and_top(); + let order = if front < top { [front, top] } else { [top, front] }; + let whole = built(&s, sheet).scene; + let first = extract(&mut s, sheet).unwrap(); + assert_eq!( + (bytes(&first.scene), first.stale.as_slice(), first.views.len()), + (bytes(&Scene { size_mm: whole.size_mm, groups: whole.groups[..3].to_vec() }), &order[..], 0) + ); + let again = extract(&mut s, sheet).unwrap(); + assert!(Arc::ptr_eq(&again.scene, &first.scene) && again.generation == first.generation); + assert_eq!(s.drawing_scenes.projections, 0); + + assert!(step(&mut s)); + let one = extract(&mut s, sheet).unwrap(); + let objects: Vec = one.scene.groups.iter().map(|g| g.object).collect(); + assert_eq!((objects, one.stale.as_slice()), (vec![sheet, sheet, sheet, order[0]], &order[1..])); + assert!(one.generation > first.generation); + assert!(!step(&mut s)); + let both = extract(&mut s, sheet).unwrap(); + assert_eq!((bytes(&both.scene), both.stale.len()), (bytes(&whole), 0)); + assert!(both.generation > one.generation); + assert!(both.views.iter().all(|v| v.status == Status::Drawn) && both.views.len() == 2); + assert!(!step(&mut s)); + assert_eq!((s.drawing_scenes.projections, extract(&mut s, sheet).unwrap().generation), (2, both.generation)); +} + +/// Moving a view moves its lines and projects nothing: the top view is lined up with the front +/// one, so both move 50 mm right, and the scene is the built one. Undoing the move projects nothing +/// either and gives back the scene before it, byte for byte. +#[test] +fn a_move_and_its_undo_project_nothing() { + let (mut s, sheet, [front, _]) = front_and_top(); + let before = settled(&mut s, sheet); + let projections = s.drawing_scenes.projections; + run(&mut s, "drawing.view.edit", json!({"view": ids::encode(front), "set": {"place": {"at": [200.0, 150.0]}}})); + let after = extract(&mut s, sheet).unwrap(); + assert_eq!((after.stale.len(), s.drawing_scenes.projections), (0, projections)); + assert!(after.generation > before.generation); + assert_eq!(bytes(&after.scene), bytes(&built(&s, sheet).scene)); + for (was, now) in before.scene.groups.iter().zip(&after.scene.groups).skip(3) { + assert!(same_within(now, &moved(was, Vec2::new(50.0, 0.0)), 1e-9), "{now:?}"); + } + run(&mut s, "edit.undo", json!({})); + let undone = extract(&mut s, sheet).unwrap(); + assert_eq!((undone.stale.len(), s.drawing_scenes.projections), (0, projections)); + assert_eq!(bytes(&undone.scene), bytes(&before.scene)); +} + +/// After a model change (going back to a checkpoint taken before a tower was added) both views are +/// out of date and the last scene still shows. Each step draws one view from the model as it is +/// now, and a view listed as up to date always draws as the built scene does. +#[test] +fn after_a_model_change_the_last_scene_shows_until_its_views_are_drawn_again() { + let (mut s, sheet, _) = front_and_top(); + let drawing = ids::encode(s.open_drawing.unwrap()); + let checkpoint = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].clone(); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 40, "corner": [40, 60, 0], "body_name": "Tower", "operation": "new"})); + run(&mut s, "drawing.open", json!({"drawing": drawing})); + let with_tower = settled(&mut s, sheet); + run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": checkpoint})); + let projections = s.drawing_scenes.projections; + let old = extract(&mut s, sheet).unwrap(); + assert_eq!((old.stale.len(), bytes(&old.scene), old.generation), (2, bytes(&with_tower.scene), with_tower.generation)); + let now = built(&s, sheet).scene; + let group = |scene: &Scene, id: u64| { + scene.groups.iter().find(|g| g.object == id && g.kind == ObjectKind::View).map(|g| serde_json::to_string(g).unwrap()) + }; + loop { + let more = step(&mut s); + let mid = extract(&mut s, sheet).unwrap(); + for v in mid.views.iter().filter(|v| !mid.stale.contains(&v.view)) { + assert_eq!(group(&mid.scene, v.view), group(&now, v.view), "{}", v.view); + } + if !more { + break; + } + } + let last = extract(&mut s, sheet).unwrap(); + assert_eq!((last.stale.len(), s.drawing_scenes.projections, bytes(&last.scene)), (0, projections + 2, bytes(&now))); +} + +/// Closing the drawing drops its scenes and the world states they hold; opened again, every view +/// is out of date. +#[test] +fn closing_the_drawing_drops_its_scenes() { + let (mut s, sheet, _) = front_and_top(); + let drawing = ids::encode(s.open_drawing.unwrap()); + let before = settled(&mut s, sheet); + assert_eq!(s.drawing_scenes.views.len(), 2); + run(&mut s, "drawing.close", json!({})); + let cache = &s.drawing_scenes; + assert!(cache.views.is_empty() && cache.last.is_none() && cache.shown.is_none() && cache.drawing.is_none()); + assert!(!step(&mut s)); + run(&mut s, "drawing.open", json!({"drawing": drawing})); + let reopened = extract(&mut s, sheet).unwrap(); + // A new scene, so a new number: the page can't take it for the one it showed before. + assert!(reopened.stale.len() == 2 && reopened.generation > before.generation); } /// A view whose lines would take the sheet past a paper scene's records fails and is left out; @@ -264,3 +379,37 @@ fn a_view_past_100_to_1_is_drawn_with_a_coarser_chord() { let front = scene.views.iter().find(|v| v.view == front).unwrap(); assert_eq!(front.status, Status::Drawn, "{front:?}"); } + +/// Seeded mixes of moves, setting changes, undos, redos, extracts and steps: once nothing is +/// waiting, the provider's scene is always the built one, byte for byte. +#[test] +fn seeded_edits_and_steps_always_end_at_the_built_scene() { + let pick = |seed: u64, salt: u64, n: u64| ((seed ^ salt).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 33) % n; + for seed in 1..=24u64 { + let (mut s, sheet, [front, top]) = front_and_top(); + let edit = + |s: &mut Session, view: u64, set: Value| s.execute("drawing.view.edit", &json!({"view": ids::encode(view), "set": set})).map(|_| ()); + for i in 0..12u64 { + let along = 100.0 + 10.0 * pick(seed, 100 + i, 10) as f64; + let scale = ["1:1", "1:2", "1:5"][pick(seed, 200 + i, 3) as usize]; + let tangent_edges = ["hide", "show"][pick(seed, 300 + i, 2) as usize]; + // Refused edits (nothing to undo, say) change nothing, which the end still checks. + let _ = match pick(seed, i, 8) { + 0 => edit(&mut s, front, json!({"place": {"at": [along, 150.0]}})), + 1 => edit(&mut s, top, json!({"place": {"aligned": along + 100.0}})), + 2 => edit(&mut s, front, json!({"scale": scale})), + 3 => edit(&mut s, top, json!({"tangent_edges": tangent_edges})), + 4 => s.execute("edit.undo", &json!({})).map(|_| ()), + 5 => s.execute("edit.redo", &json!({})).map(|_| ()), + 6 => { + step(&mut s); + Ok(()) + } + _ => extract(&mut s, sheet).map(drop), + }; + } + let end = settled(&mut s, sheet); + assert!(end.stale.is_empty(), "seed {seed}"); + assert_eq!(bytes(&end.scene), bytes(&built(&s, sheet).scene), "seed {seed}"); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6163c679420..7d833c1551a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -318,6 +318,9 @@ pub struct Session { /// Host-owned viewport metadata, never saved or included in history. render_viewport: Option>, render_jobs: render_jobs::Jobs, + /// The sheet scenes of the drawing open, for the sheet page ([`drawing_scene::extract`]): view + /// state, never saved or an undo step, dropped when the drawing closes. + pub(crate) drawing_scenes: drawing_scene::Cache, /// The visibility the design file holds (what `is_dirty` compares with). saved_visibility: Visibility, /// States to go back to (`edit.checkpoint`, `edit.restore_checkpoint`): how batches of @@ -472,6 +475,7 @@ impl Session { render_viewport: None, render_jobs: Default::default(), dimension_values: Default::default(), + drawing_scenes: Default::default(), #[cfg(test)] evaluations: 0, crash_journal: false, @@ -884,6 +888,8 @@ impl Session { if self.render_jobs.host.is_none() && host_jobs.is_some() { self.set_render_job_host(host_jobs)?; } + // A command that closed the drawing, or opened another, ends its sheet scenes. + drawing_scene::forget_closed(self); if outermost && crash::enabled() { // A failed command leaves the design as it was (restored below). let failed = r.as_ref().err().map(ToString::to_string); @@ -1044,6 +1050,7 @@ impl Session { camera: self.camera, render_viewport: self.render_viewport.clone(), render_jobs: self.render_jobs.scratch(), + drawing_scenes: Default::default(), saved_visibility: self.saved_visibility.clone(), dimension_values: self.dimension_values.clone(), #[cfg(test)]