Skip to main content

brep_render/sheets/
print.rs

1//! Manufacturing instructions on paper: the printed pages and the per-step
2//! pictures, drawn as sheets.
3//!
4//! [`brep_instructions::layout`] says WHERE everything goes on each page; this
5//! module fills those places with what the sheet writers already draw —
6//! polylines and centred text runs in paper millimetres, plus each step's view
7//! projected as a placed view ([`ViewDrawing`]) — so the PDF and the SVG are
8//! [`super::pdf::write_pdf`] and [`super::svg::to_svg`] unchanged. The
9//! projections come from the engine, which owns the scene: it asks
10//! [`picture_rects`] where each picture goes, fits a view into each with
11//! [`fit`], and hands the drawings back to [`pages`] or [`step_image`].
12
13use super::frame::FrameDrawing;
14use super::pdf::text_width;
15use super::project::{SheetDrawing, SheetText, ViewDrawing};
16use super::svg::CAP_PER_EM;
17use brep_instructions::layout::{self, Page, PageKind, RecordRow, Rect, TextLine, TextMeasure, BODY_MM, HEADER_MM, HEADING_MM, LEADING, MARGIN_MM, PARTS_ROW_MM, TEXT_INSET_MM, TOOLS_ROW_MM};
18use brep_instructions::model::{Instructions, Step};
19use brep_instructions::record::{self, Mark};
20use std::collections::HashMap;
21
22/// The share of a picture rectangle a fitted view fills.
23const FILL: f64 = 0.9;
24/// The cover's title block above its picture.
25const COVER_TEXT_MM: f64 = 46.0;
26/// A per-step picture: its paper and the caption band above the view.
27pub const IMAGE_MM: (f64, f64) = (160.0, 120.0);
28const IMAGE_CAPTION_MM: f64 = 10.0;
29
30/// A run's width in millimetres at cap height `cap`.
31fn width_mm(text: &str, cap: f64) -> f64 {
32    text_width(text) * cap / CAP_PER_EM
33}
34
35/// The pages' own text measure: the font the sheet writers set text in.
36pub struct PageFont;
37
38impl TextMeasure for PageFont {
39    fn width_mm(&self, text: &str, cap: f64) -> f64 {
40        width_mm(text, cap)
41    }
42}
43
44/// The block's printed pages, laid out with the pages' own font metrics:
45/// the layout [`pages`] draws, so a step's Record block (its fields as a
46/// paper form) is paged by the widths it is drawn with.
47pub fn layout(block: &Instructions) -> Result<Vec<Page>, String> {
48    layout::pages_with(block, &PageFont)
49}
50
51/// A run reading left to right whose line box starts at `(x, y)` (top-left).
52/// The writers centre a run on its anchor, so the anchor is the box's middle.
53fn left(text: impl Into<String>, x: f64, y: f64, cap: f64) -> SheetText {
54    let text = text.into();
55    let w = width_mm(&text, cap);
56    SheetText::flat(text, [x + w / 2.0, y + cap / 2.0], cap)
57}
58
59/// [`left`], ending at `x`.
60fn right(text: impl Into<String>, x: f64, y: f64, cap: f64) -> SheetText {
61    let text = text.into();
62    let w = width_mm(&text, cap);
63    SheetText::flat(text, [x - w / 2.0, y + cap / 2.0], cap)
64}
65
66/// `text` broken into lines no wider than `width` at cap height `cap`, at
67/// spaces; a word wider than the line stands alone on one.
68pub fn wrap(text: &str, width: f64, cap: f64) -> Vec<String> {
69    layout::wrap(text, width, cap, &PageFont)
70}
71
72fn rect_lines(r: Rect) -> Vec<[f64; 2]> {
73    vec![[r.x, r.y], [r.x + r.w, r.y], [r.x + r.w, r.y + r.h], [r.x, r.y + r.h], [r.x, r.y]]
74}
75
76/// A column of text lines from the top of `area` down; a line that would
77/// run past its bottom is left out and the last one kept reads `…`.
78struct Column {
79    area: Rect,
80    y: f64,
81    texts: Vec<SheetText>,
82    full: bool,
83}
84
85impl Column {
86    fn new(area: Rect) -> Self {
87        Column { area, y: area.y, texts: Vec::new(), full: false }
88    }
89
90    fn line(&mut self, text: impl Into<String>, cap: f64, indent: f64) {
91        if self.full {
92            return;
93        }
94        let pitch = cap * LEADING;
95        if self.y + pitch > self.area.y + self.area.h + 1e-9 {
96            self.full = true;
97            if let Some(last) = self.texts.pop() {
98                let x = last.anchor[0] - width_mm(&last.text, last.height) / 2.0;
99                let y = last.anchor[1] - last.height / 2.0;
100                self.texts.push(left(format!("{}\u{2026}", last.text), x, y, last.height));
101            }
102            return;
103        }
104        self.texts.push(left(text, self.area.x + indent, self.y, cap));
105        self.y += pitch;
106    }
107
108    fn wrapped(&mut self, text: &str, cap: f64, indent: f64) {
109        for line in wrap(text, self.area.w - indent, cap) {
110            self.line(line, cap, indent);
111        }
112    }
113
114    fn gap(&mut self) {
115        self.y += BODY_MM * 0.6;
116    }
117}
118
119/// What a step's text area says: its number and title, the parts it adds,
120/// its tools and torque, its callouts and its notes
121/// ([`layout::step_text`], the lines the layout measured).
122fn step_text(step: &Step, number: usize, area: Rect) -> Vec<SheetText> {
123    let mut column = Column::new(area);
124    for line in layout::step_text(step, number, area.w, &PageFont) {
125        match line {
126            TextLine::Text { text, cap, indent } => column.line(text, cap, indent),
127            TextLine::Gap => column.gap(),
128        }
129    }
130    column.texts
131}
132
133/// One placed band of a step's Record block as strokes and text: a box to
134/// tick is a square outline and a line to write on a stroke, so the form
135/// prints the same whatever font a viewer substitutes.
136fn record_row(block: &Instructions, row: &RecordRow, lines: &mut Vec<Vec<[f64; 2]>>, texts: &mut Vec<SheetText>) {
137    let Some(step) = block.step(&row.step_id) else { return };
138    let bands = record::bands(step, row.step_number, &row.item, row.rect.w, row.continued, &PageFont);
139    let Some(band) = bands.get(row.band) else { return };
140    let (ox, oy) = (row.rect.x, row.rect.y);
141    for mark in &band.marks {
142        match mark {
143            Mark::Text { text, x, y, cap } => texts.push(left(text.clone(), ox + x, oy + y, *cap)),
144            Mark::Box { x, y, size } => lines.push(rect_lines(Rect { x: ox + x, y: oy + y, w: *size, h: *size })),
145            Mark::Rule { x0, x1, y } => lines.push(vec![[ox + x0, oy + y], [ox + x1, oy + y]]),
146            Mark::Line(points) => lines.push(points.iter().map(|p| [ox + p[0], oy + p[1]]).collect()),
147        }
148    }
149}
150
151/// The document's title as the pages print it.
152pub fn title(block: &Instructions) -> String {
153    let title = block.front.title.trim();
154    if !title.is_empty() {
155        return title.to_string();
156    }
157    let name = block.target.name.trim();
158    if name.is_empty() { "Assembly instructions".into() } else { format!("{name} assembly instructions") }
159}
160
161/// The step a page's cover shows: the front matter's, else the last.
162pub fn cover_step(block: &Instructions) -> Option<String> {
163    block.front.cover_step.clone().or_else(|| block.steps().last().map(|(_, step)| step.id.clone()))
164}
165
166/// Where a picture goes, keyed by what it shows: `cover` for the cover's,
167/// else `(page index, slot index)` for a step slot's.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
169pub enum PictureAt {
170    Cover,
171    Slot(usize, usize),
172}
173
174/// Every picture the pages draw, with the step whose view it is and the
175/// rectangle it is fitted into.
176pub fn picture_rects(block: &Instructions, pages: &[Page]) -> Vec<(PictureAt, String, Rect)> {
177    let mut out = Vec::new();
178    for (index, page) in pages.iter().enumerate() {
179        match page.kind {
180            PageKind::Cover => {
181                if let Some(step) = cover_step(block) {
182                    let c = page.content;
183                    out.push((PictureAt::Cover, step, Rect { x: c.x, y: c.y + COVER_TEXT_MM, w: c.w, h: c.h - COVER_TEXT_MM }));
184                }
185            }
186            PageKind::Steps => {
187                for (slot_index, slot) in page.slots.iter().enumerate() {
188                    out.push((PictureAt::Slot(index, slot_index), slot.step_id.clone(), slot.picture));
189                }
190            }
191            _ => {}
192        }
193    }
194    out
195}
196
197/// The placement `(position, scale)` that fits a view into `rect`, from its
198/// drawing at position `[0, 0]` and scale 1 (`bounds` = that drawing's
199/// `[x0, y0, x1, y1]`). Text keeps its paper size, so this is the fit of the
200/// lines; the margin `FILL` leaves takes up the balloons' slack.
201pub fn fit(bounds: [f64; 4], rect: Rect) -> ([f64; 2], f64) {
202    let (w, h) = (bounds[2] - bounds[0], bounds[3] - bounds[1]);
203    let scale = if w > 1e-9 && h > 1e-9 {
204        (rect.w / w).min(rect.h / h) * FILL
205    } else if w > 1e-9 {
206        rect.w / w * FILL
207    } else if h > 1e-9 {
208        rect.h / h * FILL
209    } else {
210        1.0
211    };
212    let centre = [(bounds[0] + bounds[2]) / 2.0, (bounds[1] + bounds[3]) / 2.0];
213    ([rect.x + rect.w / 2.0 - centre[0] * scale, rect.y + rect.h / 2.0 - centre[1] * scale], scale)
214}
215
216/// The printed pages as sheets, in print order: each page's header (the
217/// title, and the page number of the count), then its own content — the
218/// cover's title, assembly and picture; a parts or tools list's rows; the
219/// step slots, each framed, its picture in `pictures` and its text beside or
220/// below, then its Record block (what the person doing the work fills in:
221/// boxes to tick, lines to write on, the Signed and Date lines), which
222/// continues on Record pages where the layout carried it. A picture missing
223/// from `pictures` leaves its place empty.
224pub fn pages(block: &Instructions, layout: &[Page], pictures: &HashMap<PictureAt, ViewDrawing>) -> Vec<SheetDrawing> {
225    let title = title(block);
226    let count = layout.len();
227    let parts = block.parts_list();
228    let tools = block.tools_list();
229    layout
230        .iter()
231        .enumerate()
232        .map(|(index, page)| {
233            let mut lines: Vec<Vec<[f64; 2]>> = Vec::new();
234            let mut texts: Vec<SheetText> = Vec::new();
235            let mut views: Vec<ViewDrawing> = Vec::new();
236            let c = page.content;
237            // The header band: title left, page number right, a rule below.
238            let header_y = MARGIN_MM + (HEADER_MM - BODY_MM * 1.2) / 2.0 - 1.0;
239            let section = match page.kind {
240                PageKind::Cover => String::new(),
241                PageKind::PartsList { .. } => " \u{2014} Parts list".into(),
242                PageKind::ToolsList { .. } => " \u{2014} Tools".into(),
243                PageKind::Steps => String::new(),
244                PageKind::Record => " \u{2014} Record".into(),
245            };
246            texts.push(left(format!("{title}{section}"), c.x, header_y, BODY_MM * 1.2));
247            texts.push(right(format!("Page {} of {count}", page.number), c.x + c.w, header_y, BODY_MM * 1.2));
248            lines.push(vec![[c.x, c.y - 2.0], [c.x + c.w, c.y - 2.0]]);
249            match page.kind {
250                PageKind::Cover => {
251                    let mut column = Column::new(Rect { h: COVER_TEXT_MM, ..c });
252                    for line in wrap(&title, c.w, 8.0) {
253                        column.line(line, 8.0, 0.0);
254                    }
255                    if !block.front.subtitle.is_empty() {
256                        column.wrapped(&block.front.subtitle, 4.5, 0.0);
257                    }
258                    column.gap();
259                    let target = &block.target;
260                    let mut assembly = format!("Assembly: {}", if target.name.is_empty() { "-" } else { &target.name });
261                    if !target.part_number.is_empty() {
262                        assembly.push_str(&format!(" {}", target.part_number));
263                    }
264                    if !target.revision.is_empty() {
265                        assembly.push_str(&format!(" rev {}", target.revision));
266                    }
267                    column.wrapped(&assembly, BODY_MM * 1.2, 0.0);
268                    column.line(format!("{} steps", block.step_count()), BODY_MM * 1.2, 0.0);
269                    texts.extend(column.texts);
270                    if let Some(view) = pictures.get(&PictureAt::Cover) {
271                        views.push(view.clone());
272                    }
273                }
274                PageKind::PartsList { first, count } => {
275                    let columns = [c.x, c.x + 24.0, c.x + c.w - 48.0, c.x + c.w - 30.0];
276                    let row = |r: usize| c.y + r as f64 * PARTS_ROW_MM + (PARTS_ROW_MM - BODY_MM) / 2.0;
277                    for (x, label) in columns.iter().zip(["Find No.", "Part", "Qty", "First step"]) {
278                        texts.push(left(label, *x, row(0), BODY_MM));
279                    }
280                    for (r, item) in parts.iter().skip(first).take(count).enumerate() {
281                        let step = block.step_number(&item.first_step).map(|n| n.to_string()).unwrap_or_default();
282                        let name = if item.subassembly { format!("{} (sub-assembly)", item.name) } else { item.name.clone() };
283                        let cells = [item.find_number.clone(), name, item.quantity.to_string(), step];
284                        for (x, cell) in columns.iter().zip(cells) {
285                            if !cell.is_empty() {
286                                texts.push(left(cell, *x, row(r + 1), BODY_MM));
287                            }
288                        }
289                    }
290                    for r in 1..=count + 1 {
291                        let y = c.y + r as f64 * PARTS_ROW_MM;
292                        lines.push(vec![[c.x, y], [c.x + c.w, y]]);
293                    }
294                }
295                PageKind::ToolsList { first, count } => {
296                    let columns = [c.x, c.x + c.w * 0.4, c.x + c.w - 30.0];
297                    let row = |r: usize| c.y + r as f64 * TOOLS_ROW_MM + (TOOLS_ROW_MM - BODY_MM) / 2.0;
298                    for (x, label) in columns.iter().zip(["Tool", "Spec", "Steps"]) {
299                        texts.push(left(label, *x, row(0), BODY_MM));
300                    }
301                    for (r, (tool, steps)) in tools.iter().skip(first).take(count).enumerate() {
302                        let numbers: Vec<String> =
303                            steps.iter().filter_map(|id| block.step_number(id)).map(|n| n.to_string()).collect();
304                        let cells = [tool.name.clone(), tool.spec.clone(), numbers.join(", ")];
305                        for (x, cell) in columns.iter().zip(cells) {
306                            if !cell.is_empty() {
307                                texts.push(left(cell, *x, row(r + 1), BODY_MM));
308                            }
309                        }
310                    }
311                    for r in 1..=count + 1 {
312                        let y = c.y + r as f64 * TOOLS_ROW_MM;
313                        lines.push(vec![[c.x, y], [c.x + c.w, y]]);
314                    }
315                }
316                PageKind::Steps => {
317                    for (slot_index, slot) in page.slots.iter().enumerate() {
318                        lines.push(rect_lines(slot.rect));
319                        if let Some(view) = pictures.get(&PictureAt::Slot(index, slot_index)) {
320                            views.push(view.clone());
321                        }
322                        if let Some(step) = block.step(&slot.step_id) {
323                            let t = TEXT_INSET_MM;
324                            let inset = Rect { x: slot.text.x + t, y: slot.text.y + t, w: slot.text.w - 2.0 * t, h: slot.text.h - 2.0 * t };
325                            texts.extend(step_text(step, slot.step_number, inset));
326                        }
327                        // The step's Record block: its fields as a paper form.
328                        for row in &slot.record {
329                            record_row(block, row, &mut lines, &mut texts);
330                        }
331                    }
332                }
333                PageKind::Record => {
334                    for row in &page.records {
335                        record_row(block, row, &mut lines, &mut texts);
336                    }
337                }
338            }
339            SheetDrawing {
340                id: format!("P{}", page.number),
341                name: format!("Page {}", page.number),
342                width_mm: page.width_mm,
343                height_mm: page.height_mm,
344                views,
345                dimensions: Vec::new(),
346                ordinates: Vec::new(),
347                frame: Some(FrameDrawing { lines, texts, revision_table: None }),
348            }
349        })
350        .collect()
351}
352
353/// Where a per-step picture's view goes on its [`IMAGE_MM`] paper.
354pub fn image_picture_rect() -> Rect {
355    let m = 4.0;
356    Rect { x: m, y: IMAGE_CAPTION_MM, w: IMAGE_MM.0 - 2.0 * m, h: IMAGE_MM.1 - IMAGE_CAPTION_MM - m }
357}
358
359/// One step's picture as a sheet: its number and title over its view.
360pub fn step_image(block: &Instructions, step_id: &str, picture: Option<ViewDrawing>) -> Result<SheetDrawing, String> {
361    let step = block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
362    let number = block.step_number(step_id).unwrap_or(0);
363    let caption = if step.title.is_empty() { format!("Step {number}") } else { format!("Step {number}  {}", step.title) };
364    let texts = vec![left(caption, 4.0, (IMAGE_CAPTION_MM - HEADING_MM) / 2.0, HEADING_MM)];
365    Ok(SheetDrawing {
366        id: step.id.clone(),
367        name: format!("Step {number}"),
368        width_mm: IMAGE_MM.0,
369        height_mm: IMAGE_MM.1,
370        views: picture.into_iter().collect(),
371        dimensions: Vec::new(),
372        ordinates: Vec::new(),
373        frame: Some(FrameDrawing { lines: Vec::new(), texts, revision_table: None }),
374    })
375}
376