1use brep_kernel::feature_pipeline::pmi::layout::TextRun;
17use brep_kernel::PmiPresentation;
18use serde_json::{json, Value};
19
20pub const WELD_CALLOUT: &str = "weldCallout";
22
23fn 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
43pub 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
59pub 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#[derive(Debug, Clone, PartialEq)]
86pub struct WeldSymbol {
87 pub standard: Standard,
88 pub side: Side,
89 pub legs: (f64, Option<f64>),
91 pub length: f64,
92 pub pitch: f64,
93 pub all_around: bool,
94 pub field_weld: bool,
95 pub tail: String,
97}
98
99pub type Evaluate<'a> = &'a dyn Fn(&str) -> Option<f64>;
102
103fn 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
115pub 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 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 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 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
190fn 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#[derive(Debug, Clone, Copy)]
199pub struct Frame {
200 pub right: [f64; 3],
201 pub up: [f64; 3],
202 pub height: f64,
204 pub arrow: f64,
206}
207
208impl Frame {
209 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 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
244pub 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
250const RING: f64 = 2.2;
254
255fn text_width(text: &str, height: f64) -> f64 {
258 text.chars().count() as f64 * height * 0.8
259}
260
261pub 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 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 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 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 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 drawn.polylines.push(vec![at(0.0, 0.0), at(line_length, 0.0)]);
298
299 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 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 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 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 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 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 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 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 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