diff --git a/crates/diagnostics/src/body.rs b/crates/diagnostics/src/body.rs index 72d1e2ada1..178a7b802f 100644 --- a/crates/diagnostics/src/body.rs +++ b/crates/diagnostics/src/body.rs @@ -61,7 +61,11 @@ pub fn read(path: &Path, binary: bool, rebuild: bool) -> Result { records: &mut records, next_key: 1u64 << 50, }; - let kind = if binary { FileType::Binary } else { FileType::Ascii }; + let kind = if binary { + FileType::Binary + } else { + FileType::Ascii + }; p7::read_from_file(&mut kernel, &mut brep, bytes, kind, rebuild, &mut env).map_err(fail)?; brep.use_arena_naming().map_err(fail)?; brep.refresh_cached_topology(); @@ -76,8 +80,15 @@ pub fn faces(body: &Body) -> Result, String> { .into_iter() .map(|f| { let face = b.face(f).map_err(|e| e.to_string())?; - let surface = face.surface.as_ref().map_or("none", |s| surface_name(s.kind())); - Ok(FaceInfo { index: f.index() as usize, surface, tolerance: face.tolerance }) + let surface = face + .surface + .as_ref() + .map_or("none", |s| surface_name(s.kind())); + Ok(FaceInfo { + index: f.index() as usize, + surface, + tolerance: face.tolerance, + }) }) .collect() } @@ -108,14 +119,27 @@ pub fn mesh(body: &mut Body, edges: &[EdgeInfo]) -> Result { let (record, order) = solidcore_convert::brep::to_record(&mut body.kernel, &mut body.brep) .map_err(|e| format!("converting to the record: {e}"))?; let tolerance = solidcore_tess::MeshTolerance::display_of(size); - let (plan, _) = solidcore_tess::plan(&record, &tolerance, size).map_err(|e| format!("meshing: {e}"))?; + let (plan, _) = + solidcore_tess::plan(&record, &tolerance, size).map_err(|e| format!("meshing: {e}"))?; let (mesh, refused) = plan.evaluate(); - let kernel_face = |record_face: usize| order.faces.get(record_face).map_or(usize::MAX, |f| f.index() as usize); + let kernel_face = |record_face: usize| { + order + .faces + .get(record_face) + .map_or(usize::MAX, |f| f.index() as usize) + }; Ok(Mesh { positions: mesh.positions.iter().map(|p| [p.x, p.y, p.z]).collect(), triangles: mesh.triangles, - triangle_face: mesh.tri_face.iter().map(|&f| kernel_face(f as usize)).collect(), - refused: refused.iter().map(|r| (kernel_face(r.face), r.reason.clone())).collect(), + triangle_face: mesh + .tri_face + .iter() + .map(|&f| kernel_face(f as usize)) + .collect(), + refused: refused + .iter() + .map(|r| (kernel_face(r.face), r.reason.clone())) + .collect(), size, }) } @@ -129,8 +153,17 @@ fn diagonal(points: impl Iterator) -> f64 { *h = h.max(v); } } - let d = lo.iter().zip(&hi).map(|(l, h)| (h - l) * (h - l)).sum::().sqrt(); - if d.is_finite() && d > 0.0 { d } else { 1.0 } + let d = lo + .iter() + .zip(&hi) + .map(|(l, h)| (h - l) * (h - l)) + .sum::() + .sqrt(); + if d.is_finite() && d > 0.0 { + d + } else { + 1.0 + } } /// The name of a surface's kind, as the report and the summary print it. diff --git a/crates/diagnostics/src/main.rs b/crates/diagnostics/src/main.rs index e07d13bb8c..2193d99c72 100644 --- a/crates/diagnostics/src/main.rs +++ b/crates/diagnostics/src/main.rs @@ -69,7 +69,10 @@ fn run(o: &Options) -> Result<(), String> { .map_or_else(|| "body".to_owned(), |s| s.to_string_lossy().into_owned()); std::fs::create_dir_all(&o.out).map_err(|e| format!("{}: {e}", o.out.display()))?; let png_path = o.out.join(format!("{stem}.png")); - write(&png_path, &png::encode(picture.width, picture.height, &picture.rgb))?; + write( + &png_path, + &png::encode(picture.width, picture.height, &picture.rgb), + )?; let report = report::build(&o.file, &body, &faces, &edges, &mesh, o.view, &frame); let json_path = o.out.join(format!("{stem}.json")); let text = serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?; @@ -88,15 +91,25 @@ fn parse(mut args: impl Iterator) -> Result { let mut o = Options { file: PathBuf::new(), out: PathBuf::from("."), - view: render::View { azimuth: -35.0, elevation: 30.0 }, + view: render::View { + azimuth: -35.0, + elevation: 30.0, + }, width: 1200, height: 900, - style: render::Style { highlight: Vec::new(), see_through: Vec::new(), edges_above: 1e-4 }, + style: render::Style { + highlight: Vec::new(), + see_through: Vec::new(), + edges_above: 1e-4, + }, binary: false, rebuild: false, }; while let Some(a) = args.next() { - let mut value = || args.next().ok_or_else(|| format!("{a} needs a value\n{USAGE}")); + let mut value = || { + args.next() + .ok_or_else(|| format!("{a} needs a value\n{USAGE}")) + }; match a.as_str() { "--out" => o.out = PathBuf::from(value()?), "--view" => { @@ -119,7 +132,10 @@ fn parse(mut args: impl Iterator) -> Result { if !(16..=8192).contains(&o.width) || !(16..=8192).contains(&o.height) { return Err("--size must be between 16x16 and 8192x8192".to_owned()); } - if !o.style.edges_above.is_finite() || !o.view.azimuth.is_finite() || !o.view.elevation.is_finite() { + if !o.style.edges_above.is_finite() + || !o.view.azimuth.is_finite() + || !o.view.elevation.is_finite() + { return Err("--view and --edges-above must be finite".to_owned()); } Ok(o) @@ -130,10 +146,15 @@ fn number(s: &str) -> Result { } fn pair(s: &str, sep: char) -> Result<[T; 2], String> { - let (a, b) = s.split_once(sep).ok_or_else(|| format!("expected two values separated by {sep:?}: {s}"))?; + let (a, b) = s + .split_once(sep) + .ok_or_else(|| format!("expected two values separated by {sep:?}: {s}"))?; Ok([number(a)?, number(b)?]) } fn list(s: &str) -> Result, String> { - s.split(',').filter(|t| !t.trim().is_empty()).map(number).collect() + s.split(',') + .filter(|t| !t.trim().is_empty()) + .map(number) + .collect() } diff --git a/crates/diagnostics/src/png.rs b/crates/diagnostics/src/png.rs index ff70ad20e7..319d7eb79c 100644 --- a/crates/diagnostics/src/png.rs +++ b/crates/diagnostics/src/png.rs @@ -15,7 +15,11 @@ pub fn encode(width: usize, height: usize, rgb: &[u8]) -> Vec { header.extend_from_slice(&[8, 2, 0, 0, 0]); let mut out = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; chunk(&mut out, *b"IHDR", &header); - chunk(&mut out, *b"IDAT", &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6)); + chunk( + &mut out, + *b"IDAT", + &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6), + ); chunk(&mut out, *b"IEND", &[]); out } @@ -34,7 +38,11 @@ fn crc32<'a>(bytes: impl Iterator) -> u32 { for &b in bytes { crc ^= u32::from(b); for _ in 0..8 { - crc = if crc & 1 == 1 { (crc >> 1) ^ 0xedb8_8320 } else { crc >> 1 }; + crc = if crc & 1 == 1 { + (crc >> 1) ^ 0xedb8_8320 + } else { + crc >> 1 + }; } } !crc diff --git a/crates/diagnostics/src/render.rs b/crates/diagnostics/src/render.rs index 3171eb9dc4..b8c2487a06 100644 --- a/crates/diagnostics/src/render.rs +++ b/crates/diagnostics/src/render.rs @@ -52,7 +52,10 @@ impl Frame { /// The pixel of the picture a model point projects to. pub fn pixel(&self, p: [f64; 3]) -> [f64; 2] { let [x, y, _] = self.view.project(p); - [x * self.scale + self.offset[0], y * self.scale + self.offset[1]] + [ + x * self.scale + self.offset[0], + y * self.scale + self.offset[1], + ] } } @@ -67,10 +70,21 @@ const EDGE: [f64; 3] = [0.333, 0.333, 0.333]; const LARGE_EDGE: [f64; 3] = [0.0, 0.0, 0.0]; /// Draws the mesh and the edges in a `width` × `height` picture. -pub fn draw(mesh: &Mesh, edges: &[EdgeInfo], view: View, style: &Style, width: usize, height: usize) -> (Picture, Frame) { +pub fn draw( + mesh: &Mesh, + edges: &[EdgeInfo], + view: View, + style: &Style, + width: usize, + height: usize, +) -> (Picture, Frame) { let frame = fit(mesh, edges, view, width, height); let mut c = Canvas::new(width * SS, height * SS); - let fine = Frame { scale: frame.scale * SS as f64, offset: frame.offset.map(|o| o * SS as f64), view }; + let fine = Frame { + scale: frame.scale * SS as f64, + offset: frame.offset.map(|o| o * SS as f64), + view, + }; let point = |i: u32| mesh.positions.get(i as usize).copied(); let screen = |p: [f64; 3]| { let [x, y] = fine.pixel(p); @@ -94,7 +108,11 @@ pub fn draw(mesh: &Mesh, edges: &[EdgeInfo], view: View, style: &Style, width: u FACE }; let colour = base.map(|v| v * shade(view, a, b, d)); - let alpha = if see_through { Some(SEE_THROUGH_ALPHA) } else { None }; + let alpha = if see_through { + Some(SEE_THROUGH_ALPHA) + } else { + None + }; c.triangle([screen(a), screen(b), screen(d)], colour, alpha); } } @@ -102,7 +120,10 @@ pub fn draw(mesh: &Mesh, edges: &[EdgeInfo], view: View, style: &Style, width: u // up to the mesh's chord tolerance behind them. let slack = mesh.size * 3e-3; for large in [false, true] { - for e in edges.iter().filter(|e| (e.tolerance > style.edges_above) == large) { + for e in edges + .iter() + .filter(|e| (e.tolerance > style.edges_above) == large) + { let pts: Vec<[f64; 3]> = e.points.iter().map(|&p| screen(p)).collect(); if large { c.polyline(&pts, 2.5 * SS as f64, LARGE_EDGE, None); @@ -117,7 +138,10 @@ pub fn draw(mesh: &Mesh, edges: &[EdgeInfo], view: View, style: &Style, width: u /// The frame that fits the mesh and the edges in the picture with a 4% margin, centred. fn fit(mesh: &Mesh, edges: &[EdgeInfo], view: View, width: usize, height: usize) -> Frame { let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); - let all = mesh.positions.iter().chain(edges.iter().flat_map(|e| e.points.iter())); + let all = mesh + .positions + .iter() + .chain(edges.iter().flat_map(|e| e.points.iter())); for &p in all { let [x, y, _] = view.project(p); lo = [lo[0].min(x), lo[1].min(y)]; @@ -132,8 +156,16 @@ fn fit(mesh: &Mesh, edges: &[EdgeInfo], view: View, width: usize, height: usize) (w - extent[0] * scale) / 2.0 - lo[0] * scale, (h - extent[1] * scale) / 2.0 - lo[1] * scale, ]; - let offset = if offset.iter().all(|o| o.is_finite()) { offset } else { [0.0, 0.0] }; - Frame { scale, offset, view } + let offset = if offset.iter().all(|o| o.is_finite()) { + offset + } else { + [0.0, 0.0] + }; + Frame { + scale, + offset, + view, + } } /// Lambert shading of a triangle's plane, lit from over the viewer's left shoulder, both @@ -142,7 +174,11 @@ fn shade(view: View, a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> f64 { let [a, b, c] = [a, b, c].map(|p| view.project(p)); let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; - let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let n = [ + u[1] * v[2] - u[2] * v[1], + u[2] * v[0] - u[0] * v[2], + u[0] * v[1] - u[1] * v[0], + ]; let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); let light = [-0.40, -0.60, -0.70]; let light_len = (0.40f64 * 0.40 + 0.60 * 0.60 + 0.70 * 0.70).sqrt(); @@ -164,7 +200,12 @@ struct Canvas { impl Canvas { fn new(width: usize, height: usize) -> Self { - Canvas { width, height, depth: vec![f64::INFINITY; width * height], rgb: vec![BACKGROUND; width * height] } + Canvas { + width, + height, + depth: vec![f64::INFINITY; width * height], + rgb: vec![BACKGROUND; width * height], + } } /// The pixel range `[lo, hi]` covers, clamped to the canvas. @@ -181,8 +222,16 @@ impl Canvas { if area.abs() < 1e-12 || !area.is_finite() { return; } - let xs = Self::span(a[0].min(b[0]).min(c[0]), a[0].max(b[0]).max(c[0]), self.width); - let ys = Self::span(a[1].min(b[1]).min(c[1]), a[1].max(b[1]).max(c[1]), self.height); + let xs = Self::span( + a[0].min(b[0]).min(c[0]), + a[0].max(b[0]).max(c[0]), + self.width, + ); + let ys = Self::span( + a[1].min(b[1]).min(c[1]), + a[1].max(b[1]).max(c[1]), + self.height, + ); for y in ys { for x in xs.clone() { let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); diff --git a/crates/diagnostics/src/report.rs b/crates/diagnostics/src/report.rs index badc8b5cf4..f06fff0da2 100644 --- a/crates/diagnostics/src/report.rs +++ b/crates/diagnostics/src/report.rs @@ -3,7 +3,7 @@ use std::fmt::Write; use std::path::Path; -use serde_json::{Value, json}; +use serde_json::{json, Value}; use crate::body::{Body, EdgeInfo, FaceInfo, Mesh}; use crate::render::{Frame, View}; @@ -47,7 +47,11 @@ pub fn build( }) }) .collect(); - let refused: Vec = mesh.refused.iter().map(|(f, why)| json!({"face": f, "reason": why})).collect(); + let refused: Vec = mesh + .refused + .iter() + .map(|(f, why)| json!({"face": f, "reason": why})) + .collect(); json!({ "file": file.display().to_string(), "body_tolerance": body.brep.tolerance(), @@ -72,7 +76,11 @@ pub fn summary(body: &Body, edges: &[EdgeInfo], mesh: &Mesh) -> String { let mut by_size: Vec<&EdgeInfo> = edges.iter().collect(); by_size.sort_by(|a, b| b.tolerance.total_cmp(&a.tolerance)); for e in by_size.iter().take(LARGEST) { - let _ = writeln!(s, " edge {:>4} tolerance {:.3e} faces {:?}", e.index, e.tolerance, e.faces); + let _ = writeln!( + s, + " edge {:>4} tolerance {:.3e} faces {:?}", + e.index, e.tolerance, e.faces + ); } s } @@ -83,7 +91,8 @@ fn face_centres(mesh: &Mesh, faces: &[FaceInfo]) -> Vec> { let slot = |f: usize| faces.iter().position(|x| x.index == f); let point = |i: u32| mesh.positions.get(i as usize).copied(); for (t, &f) in mesh.triangles.iter().zip(&mesh.triangle_face) { - let (Some(k), Some(a), Some(b), Some(c)) = (slot(f), point(t[0]), point(t[1]), point(t[2])) else { + let (Some(k), Some(a), Some(b), Some(c)) = (slot(f), point(t[0]), point(t[1]), point(t[2])) + else { continue; }; let area = triangle_area(a, b, c); @@ -97,13 +106,19 @@ fn face_centres(mesh: &Mesh, faces: &[FaceInfo]) -> Vec> { *total += area; } } - sums.into_iter().map(|(s, a)| (a > 0.0).then(|| s.map(|v| v / a))).collect() + sums.into_iter() + .map(|(s, a)| (a > 0.0).then(|| s.map(|v| v / a))) + .collect() } fn triangle_area(a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> f64 { let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; - let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let n = [ + u[1] * v[2] - u[2] * v[1], + u[2] * v[0] - u[0] * v[2], + u[0] * v[1] - u[1] * v[0], + ]; 0.5 * (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt() } @@ -112,7 +127,10 @@ fn distance(a: [f64; 3], b: [f64; 3]) -> f64 { } fn length(points: &[[f64; 3]]) -> f64 { - points.windows(2).filter_map(|w| Some(distance(*w.first()?, *w.get(1)?))).sum() + points + .windows(2) + .filter_map(|w| Some(distance(*w.first()?, *w.get(1)?))) + .sum() } /// The point halfway along the polyline. @@ -123,7 +141,11 @@ fn halfway(points: &[[f64; 3]]) -> Option<[f64; 3]> { let d = distance(a, b); if d >= left && d > 0.0 { let t = left / d; - return Some([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]); + return Some([ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, + ]); } left -= d; }