Skip to main content

brep_render/
pmi_weld_symbol.rs

1//! Weld symbols for the `weldCallout` PMI type: AWS A2.4 by default, ISO 2553
2//! as an option, the kernel's text leader as the fallback (`style: TEXT`).
3//!
4//! The kernel resolves the callout (its seam anchor, the weld's size and process)
5//! into a text leader. The symbol is drawn here from that anchor, the label
6//! position (the elbow) and the weld feature's own parameters, in the view plane,
7//! as the same primitives every other PMI type is drawn with (polylines, filled
8//! triangles, text runs). The 3D overlay draws it now; the 3D PDF, the
9//! instructions player and STEP read the kernel's presentation, so they show
10//! the symbol once the kernel lays it out (until then, the text leader).
11//!
12//! The symbol's own fields (`style`, `standard`, `side`, `length`, `pitch`,
13//! `allAround`, `fieldWeld`) extend the kernel's `weldCallout` schema through
14//! [`pmi_schema_catalogue`] until the kernel schema carries them; a field the
15//! kernel already defines is never overridden.
16use brep_kernel::feature_pipeline::pmi::layout::TextRun;
17use brep_kernel::PmiPresentation;
18use serde_json::{json, Value};
19
20/// The PMI type this module draws.
21pub const WELD_CALLOUT: &str = "weldCallout";
22
23/// The symbol fields, in form order, as kernel-style schema entries.
24fn symbol_fields() -> Vec<(&'static str, Value)> {
25    vec![
26        ("style", json!({"type": "options", "label": "Style", "options": ["SYMBOL", "TEXT"], "default_value": "SYMBOL",
27            "hint": "SYMBOL draws the standard weld symbol; TEXT keeps the plain text leader."})),
28        ("standard", json!({"type": "options", "label": "Standard", "options": ["AWS", "ISO"], "default_value": "AWS",
29            "hint": "AWS A2.4 (fillet below the reference line for the arrow side) or ISO 2553 (solid and dashed reference lines, z leg size)."})),
30        ("side", json!({"type": "options", "label": "Weld side", "options": ["ARROW", "OTHER", "BOTH"], "default_value": "ARROW",
31            "hint": "Which side of the joint the weld is on, relative to the arrow."})),
32        ("length", json!({"type": "number", "label": "Length", "default_value": 0,
33            "hint": "Weld length (each segment of an intermittent weld). 0 = continuous; no length is shown."})),
34        ("pitch", json!({"type": "number", "label": "Pitch", "default_value": 0,
35            "hint": "Centre-to-centre spacing of an intermittent weld. 0 = not intermittent."})),
36        ("allAround", json!({"type": "boolean", "label": "All around", "default_value": false,
37            "hint": "Weld all around the joint (circle at the elbow)."})),
38        ("fieldWeld", json!({"type": "boolean", "label": "Field weld", "default_value": false,
39            "hint": "Weld made in the field (flag at the elbow)."})),
40    ]
41}
42
43/// The kernel's PMI schema catalogue with the weld symbol fields added to the
44/// `weldCallout` entry (after its existing fields; the kernel's own wins).
45pub fn pmi_schema_catalogue() -> Value {
46    let mut catalogue = brep_kernel::pmi_schema_catalogue();
47    if let Some(entries) = catalogue.as_array_mut() {
48        for entry in entries.iter_mut().filter(|e| e.get("type").and_then(Value::as_str) == Some(WELD_CALLOUT)) {
49            if let Some(fields) = entry.get_mut("inputParamsSchema").and_then(Value::as_object_mut) {
50                for (key, spec) in symbol_fields() {
51                    fields.entry(key.to_string()).or_insert(spec);
52                }
53            }
54        }
55    }
56    catalogue
57}
58
59/// Defaults of the symbol fields for a new `weldCallout`, for keys absent from `params`.
60pub fn seed_defaults(type_id: &str, params: &mut serde_json::Map<String, Value>) {
61    if type_id != WELD_CALLOUT {
62        return;
63    }
64    for (key, spec) in symbol_fields() {
65        if let Some(default) = spec.get("default_value") {
66            params.entry(key.to_string()).or_insert_with(|| default.clone());
67        }
68    }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq)]
72pub enum Standard {
73    Aws,
74    Iso,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq)]
78pub enum Side {
79    Arrow,
80    Other,
81    Both,
82}
83
84/// What one weld symbol says.
85#[derive(Debug, Clone, PartialEq)]
86pub struct WeldSymbol {
87    pub standard: Standard,
88    pub side: Side,
89    /// Leg size(s) as numbers; the second only when the legs differ.
90    pub legs: (f64, Option<f64>),
91    pub length: f64,
92    pub pitch: f64,
93    pub all_around: bool,
94    pub field_weld: bool,
95    /// Process / specification and the annotation's extra note, tail text.
96    pub tail: String,
97}
98
99/// A numeric parameter: a number, or an expression the caller's evaluator reads
100/// (the document's Expressions, as the kernel evaluates feature parameters).
101pub type Evaluate<'a> = &'a dyn Fn(&str) -> Option<f64>;
102
103/// A number, an expression that evaluates, or absent (0). An expression that
104/// does not evaluate is an error naming the field, never a silent 0.
105fn number(field: &str, value: Option<&Value>, evaluate: Evaluate<'_>) -> Result<f64, String> {
106    match value {
107        Some(Value::Number(n)) => Ok(n.as_f64().unwrap_or(0.0)),
108        Some(Value::String(s)) if s.trim().is_empty() => Ok(0.0),
109        Some(Value::String(s)) => s.trim().parse().ok().or_else(|| evaluate(s))
110            .ok_or_else(|| format!("{field}: cannot evaluate `{}`", s.trim())),
111        _ => Ok(0.0),
112    }
113}
114
115/// Literal numbers only: for callers with no expression environment.
116pub fn literal(_: &str) -> Option<f64> {
117    None
118}
119
120fn text<'a>(value: Option<&'a Value>) -> &'a str {
121    value.and_then(Value::as_str).unwrap_or("")
122}
123
124impl WeldSymbol {
125    /// The symbol an annotation asks for, or `None` for the text-leader style.
126    /// `weld` is the weld feature's `inputParams`; expressions in it and in the
127    /// annotation's numbers are read through `evaluate`.
128    /// `Ok(None)` for the text-leader style; `Err` names a number that does not
129    /// evaluate.
130    pub fn from_params(annotation: &Value, weld: &Value, evaluate: Evaluate<'_>) -> Result<Option<Self>, String> {
131        if text(annotation.get("style")) == "TEXT" {
132            return Ok(None);
133        }
134        let standard = if text(annotation.get("standard")) == "ISO" { Standard::Iso } else { Standard::Aws };
135        let side = match text(annotation.get("side")) {
136            "OTHER" => Side::Other,
137            "BOTH" => Side::Both,
138            _ => Side::Arrow,
139        };
140        let first = match weld.get("legSize") {
141            None => 3.0,
142            value => number("weld leg size", value, evaluate)?,
143        };
144        let second = number("weld second leg", weld.get("legSize2"), evaluate)?;
145        let second = (second > 0.0 && (second - first).abs() > 1e-12).then_some(second);
146        let mut tail: Vec<&str> = Vec::new();
147        for note in [text(weld.get("process")).trim(), text(annotation.get("afterText")).trim()] {
148            if !note.is_empty() {
149                tail.push(note);
150            }
151        }
152        Ok(Some(WeldSymbol {
153            standard,
154            side,
155            legs: (first, second),
156            length: number("length", annotation.get("length"), evaluate)?.max(0.0),
157            pitch: number("pitch", annotation.get("pitch"), evaluate)?.max(0.0),
158            all_around: annotation.get("allAround").and_then(Value::as_bool).unwrap_or(false),
159            field_weld: annotation.get("fieldWeld").and_then(Value::as_bool).unwrap_or(false),
160            tail: tail.join(" "),
161        }))
162    }
163
164    /// The size text: `6`, `6x8`; ISO prefixes the leg length with `z`.
165    pub fn size_text(&self) -> String {
166        let base = match self.legs.1 {
167            Some(second) => format!("{}x{}", fmt(self.legs.0), fmt(second)),
168            None => fmt(self.legs.0),
169        };
170        match self.standard {
171            Standard::Aws => base,
172            Standard::Iso => format!("z{base}"),
173        }
174    }
175
176    /// The length / pitch text: AWS `50-150`, ISO `50 (100)` (length and the gap
177    /// between segments); empty for a continuous weld.
178    pub fn length_text(&self) -> String {
179        if self.length <= 0.0 {
180            return String::new();
181        }
182        match (self.standard, self.pitch > 0.0) {
183            (_, false) => fmt(self.length),
184            (Standard::Aws, true) => format!("{}-{}", fmt(self.length), fmt(self.pitch)),
185            (Standard::Iso, true) => format!("{} ({})", fmt(self.length), fmt((self.pitch - self.length).max(0.0))),
186        }
187    }
188}
189
190/// A dimension number without a trailing `.0`, at most two decimals.
191fn fmt(value: f64) -> String {
192    let rounded = (value * 100.0).round() / 100.0;
193    let text = format!("{rounded:.2}");
194    text.trim_end_matches('0').trim_end_matches('.').to_string()
195}
196
197/// The view plane the symbol is drawn in: screen right and screen up.
198#[derive(Debug, Clone, Copy)]
199pub struct Frame {
200    pub right: [f64; 3],
201    pub up: [f64; 3],
202    /// PMI text cap height, world units.
203    pub height: f64,
204    /// Arrowhead length, world units.
205    pub arrow: f64,
206}
207
208impl Frame {
209    /// In a picked annotation plane: its in-plane text direction and the up
210    /// direction `normal × x_axis`, as the kernel lays planar PMI out.
211    pub fn from_plane(normal: [f64; 3], x_axis: [f64; 3], height: f64, arrow: f64) -> Self {
212        let right = normalize(x_axis);
213        Frame { right, up: normalize(cross(normal, right)), height, arrow }
214    }
215
216    /// From the camera's forward and up (`forward × up` is screen right).
217    pub fn from_view(forward: [f64; 3], up: [f64; 3], height: f64, arrow: f64) -> Self {
218        let right = normalize(cross(forward, up));
219        let up = normalize(cross(right, forward));
220        Frame { right, up, height, arrow }
221    }
222}
223
224fn add(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
225    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
226}
227fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
228    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
229}
230fn scale(a: [f64; 3], s: f64) -> [f64; 3] {
231    [a[0] * s, a[1] * s, a[2] * s]
232}
233fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
234    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
235}
236fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
237    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
238}
239fn normalize(a: [f64; 3]) -> [f64; 3] {
240    let length = dot(a, a).sqrt();
241    if length > 1e-12 { scale(a, 1.0 / length) } else { [1.0, 0.0, 0.0] }
242}
243
244/// Where the elbow sits when the user has not dragged the label: up and to the
245/// right of the seam point on screen, far enough for the arrow to read.
246pub fn default_elbow(anchor: [f64; 3], frame: &Frame) -> [f64; 3] {
247    add(anchor, add(scale(frame.right, 3.0 * frame.height), scale(frame.up, 4.0 * frame.height)))
248}
249
250/// The all-around ring's radius in text heights: it rings the label chip at the
251/// elbow (whose corners reach about 1.7 text heights), and the symbol, its texts
252/// and the field-weld flag stand clear of it.
253const RING: f64 = 2.2;
254
255/// Approximate width of a run in the PMI stroke font (used only to place texts
256/// beside the symbol; the strokes themselves come from the kernel font).
257fn text_width(text: &str, height: f64) -> f64 {
258    text.chars().count() as f64 * height * 0.8
259}
260
261/// Lay out the symbol: the arrow from `elbow` to the seam point `anchor`, the
262/// reference line from the elbow away from the arrow, and everything on it.
263pub fn present(symbol: &WeldSymbol, anchor: [f64; 3], elbow: [f64; 3], frame: &Frame) -> PmiPresentation {
264    let h = frame.height;
265    let (u, v) = (frame.right, frame.up);
266    // The reference line runs away from the arrow along screen right or left.
267    let s = if dot(sub(elbow, anchor), u) >= 0.0 { 1.0 } else { -1.0 };
268    let at = |x: f64, y: f64| add(elbow, add(scale(u, s * x), scale(v, y)));
269    // Screen-space point (x to the right, unaffected by the line's direction).
270    let size = symbol.size_text();
271    let length = symbol.length_text();
272    let tail = symbol.tail.clone();
273    let label_room = text_width(&size, h) + text_width(&length, h) + 4.0 * h;
274    // The symbol stands clear of the label chip at the elbow and of the
275    // all-around ring.
276    // The text on the elbow side of the triangle (the size when the line runs
277    // right, the length when it runs left) also needs its room.
278    let near_text = if s > 0.0 { text_width(&size, h) } else { text_width(&length, h) };
279    let centre = RING * h + 0.9 * h + near_text + 0.5 * h;
280    let line_length = (centre / h + 4.5).max(label_room / h + 2.0 + RING) * h;
281    let mut drawn = PmiPresentation::default();
282    let mut texts: Vec<TextRun> = Vec::new();
283
284    // Arrow from the elbow to the seam, head at the seam.
285    drawn.polylines.push(vec![elbow, anchor]);
286    let to_anchor = sub(anchor, elbow);
287    let distance = dot(to_anchor, to_anchor).sqrt();
288    if distance > 1e-9 {
289        let d = scale(to_anchor, 1.0 / distance);
290        let head = frame.arrow.min(distance * 0.5);
291        let side = normalize(cross(cross(u, v), d));
292        let base = sub(anchor, scale(d, head));
293        drawn.arrows.push([anchor, add(base, scale(side, head * 0.3)), sub(base, scale(side, head * 0.3))]);
294    }
295
296    // Reference line.
297    drawn.polylines.push(vec![at(0.0, 0.0), at(line_length, 0.0)]);
298
299    // ISO identification line: dashed, below the solid line, unless symmetric.
300    let iso = symbol.standard == Standard::Iso;
301    let dashed_y = -0.6 * h;
302    if iso && symbol.side != Side::Both {
303        let (dash, gap) = (0.5 * h, 0.25 * h);
304        let mut x = 0.0;
305        while x < line_length {
306            let end = (x + dash).min(line_length);
307            drawn.polylines.push(vec![at(x, dashed_y), at(end, dashed_y)]);
308            x += dash + gap;
309        }
310    }
311
312    // Fillet triangles. `x0` is the symbol's left edge in screen terms: the
313    // vertical leg is always on the left, whichever way the line runs.
314    let screen_left = |c: f64| if s > 0.0 { c - 0.5 * h } else { c + 0.5 * h };
315    let left = screen_left(centre);
316    let mut triangle = |base_y: f64, toward: f64| {
317        // In screen x: left edge, then h to the right.
318        let lx = left;
319        let rx = if s > 0.0 { left + h } else { left - h };
320        drawn.polylines.push(vec![at(lx, base_y), at(lx, base_y + toward * h), at(rx, base_y), at(lx, base_y)]);
321        // Size to the screen-left of the symbol, length to the screen-right,
322        // a little clear of the line they stand on.
323        let y = base_y + toward * 0.7 * h;
324        if !size.is_empty() {
325            let offset = 0.3 * h + text_width(&size, h) * 0.5;
326            let x = if s > 0.0 { lx - offset } else { lx + offset };
327            texts.push(run(&size, at(x, y), u, v, h));
328        }
329        if !length.is_empty() {
330            let offset = 0.3 * h + text_width(&length, h) * 0.5;
331            let x = if s > 0.0 { rx + offset } else { rx - offset };
332            texts.push(run(&length, at(x, y), u, v, h));
333        }
334    };
335    // AWS: arrow side below the line, other side above. ISO: arrow side on the
336    // solid line (above it), other side on the dashed line (below it).
337    let (arrow_side, other_side) = if iso { ((0.0, 1.0), (dashed_y, -1.0)) } else { ((0.0, -1.0), (0.0, 1.0)) };
338    match symbol.side {
339        Side::Arrow => triangle(arrow_side.0, arrow_side.1),
340        Side::Other => triangle(other_side.0, other_side.1),
341        Side::Both => {
342            triangle(0.0, -1.0);
343            triangle(0.0, 1.0);
344        }
345    }
346
347    // All around: a circle at the elbow, ringing the label chip there so the
348    // chip never hides it.
349    if symbol.all_around {
350        let r = RING * h;
351        drawn.polylines.push((0..=32).map(|k| {
352            let a = k as f64 / 32.0 * std::f64::consts::TAU;
353            add(elbow, add(scale(u, r * a.cos()), scale(v, r * a.sin())))
354        }).collect());
355    }
356    // Field weld: a staff up from the elbow with a pennant toward the tail,
357    // tall enough to clear the label chip at the elbow.
358    if symbol.field_weld {
359        let top = at(0.0, (RING + 1.0) * h);
360        drawn.polylines.push(vec![elbow, top]);
361        drawn.arrows.push([top, at(0.0, (RING + 0.4) * h), at(0.9 * h, (RING + 0.7) * h)]);
362    }
363    // Tail: a fork at the far end, with the process text beyond it.
364    if !tail.is_empty() {
365        let end = at(line_length, 0.0);
366        let k = 0.8 * h * std::f64::consts::FRAC_1_SQRT_2;
367        drawn.polylines.push(vec![at(line_length + k, k), end, at(line_length + k, -k)]);
368        let x = line_length + k + 0.3 * h + text_width(&tail, h) * 0.5;
369        texts.push(run(&tail, at(x, 0.0), u, v, h));
370    }
371
372    // The texts are runs, as for every PMI type: the 3D PDF and STEP stroke
373    // them, the viewport strokes them for a symbol (it has no chip text).
374    drawn.text_anchor = elbow;
375    drawn.texts = texts;
376    drawn
377}
378
379fn run(text: &str, anchor: [f64; 3], right: [f64; 3], up: [f64; 3], height: f64) -> TextRun {
380    TextRun { text: text.to_string(), anchor, right, up, height }
381}
382