Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 42 additions & 9 deletions crates/diagnostics/src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ pub fn read(path: &Path, binary: bool, rebuild: bool) -> Result<Body, String> {
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();
Expand All @@ -76,8 +80,15 @@ pub fn faces(body: &Body) -> Result<Vec<FaceInfo>, 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()
}
Expand Down Expand Up @@ -108,14 +119,27 @@ pub fn mesh(body: &mut Body, edges: &[EdgeInfo]) -> Result<Mesh, String> {
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,
})
}
Expand All @@ -129,8 +153,17 @@ fn diagonal(points: impl Iterator<Item = [f64; 3]>) -> f64 {
*h = h.max(v);
}
}
let d = lo.iter().zip(&hi).map(|(l, h)| (h - l) * (h - l)).sum::<f64>().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::<f64>()
.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.
Expand Down
35 changes: 28 additions & 7 deletions crates/diagnostics/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())?;
Expand All @@ -88,15 +91,25 @@ fn parse(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
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" => {
Expand All @@ -119,7 +132,10 @@ fn parse(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
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)
Expand All @@ -130,10 +146,15 @@ fn number<T: std::str::FromStr>(s: &str) -> Result<T, String> {
}

fn pair<T: std::str::FromStr>(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<Vec<usize>, String> {
s.split(',').filter(|t| !t.trim().is_empty()).map(number).collect()
s.split(',')
.filter(|t| !t.trim().is_empty())
.map(number)
.collect()
}
12 changes: 10 additions & 2 deletions crates/diagnostics/src/png.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ pub fn encode(width: usize, height: usize, rgb: &[u8]) -> Vec<u8> {
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
}
Expand All @@ -34,7 +38,11 @@ fn crc32<'a>(bytes: impl Iterator<Item = &'a u8>) -> 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
Expand Down
73 changes: 61 additions & 12 deletions crates/diagnostics/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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],
]
}
}

Expand All @@ -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);
Expand All @@ -94,15 +108,22 @@ 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);
}
}
// An edge lies on its faces, which the mesh only approximates: a visible edge may sit
// 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);
Expand All @@ -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)];
Expand All @@ -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
Expand All @@ -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();
Expand All @@ -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.
Expand All @@ -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);
Expand Down
Loading
Loading