//! The kernel regression rig: replay `tests/kernel-cases///recipe.json` (an oracle
//! recipe or a command script) and grade the result against the case's own `expected.json`:
//! closed-form numbers where the case has them, and always the invariants (the operation's
//! outcome, one closed valid solid per body, the expected counts). One kernel per run; kernels
//! are never compared with each other. See tests/kernel-cases/README.md.
use serde_json::{Value, json};
use crate::oracle::{ABS_FRAC, Checks, REL_TOL, totals, v3};
use crate::{read_json, recipe};
/// The kernel the cases run on: SMLib, the only one.
fn kernel() -> String {
"smlib".into()
}
/// How many cases a chain of `base` recipes may go through (a ladder case builds on the one
/// before it, which builds on the one before that).
const MAX_BASE_DEPTH: usize = 32;
/// The case's commands: a script as is, or an oracle recipe translated. In a string, `$CASE` is
/// the case directory (input files such as `input.step`) and `$OUT` a scratch directory for files
/// the case writes (an export), outside the repository. A script with `"base": ""` (relative to this case's directory) runs that case's commands first: a ladder
/// case starts from the previous tier's finished part without copying its commands.
fn script(dir: &str, out: &str, recipe: &Value) -> Result {
script_at(dir, out, recipe, 0)
}
fn script_at(dir: &str, out: &str, recipe: &Value, depth: usize) -> Result {
let s = if recipe.get("commands").is_some() || recipe.is_array() { recipe.clone() } else { recipe::to_script(recipe)? };
let text = serde_json::to_string(&s).map_err(|e| e.to_string())?;
let inner = |p: &str| -> Result {
let j = serde_json::to_string(p).map_err(|e| e.to_string())?;
Ok(j.get(1..j.len().saturating_sub(1)).unwrap_or("").to_string())
};
let own: Value = serde_json::from_str(&text.replace("$CASE", &inner(dir)?).replace("$OUT", &inner(out)?)).map_err(|e| e.to_string())?;
let Some(base) = recipe.get("base").and_then(Value::as_str) else { return Ok(own) };
if depth >= MAX_BASE_DEPTH {
return Err(format!("`base` chain deeper than {MAX_BASE_DEPTH} cases"));
}
let base_dir = std::path::Path::new(dir).join(base).to_string_lossy().to_string();
let base_script = read_json(&format!("{base_dir}/recipe.json"))
.and_then(|r| script_at(&base_dir, out, &r, depth + 1))
.map_err(|e| format!("base {base}: {e}"))?;
let list = |v: &Value| v.get("commands").or(Some(v)).and_then(Value::as_array).cloned().unwrap_or_default();
let mut commands = list(&base_script);
commands.extend(list(&own));
Ok(json!({"commands": commands}))
}
/// A scratch directory for one case's output files.
fn scratch(area: &str, name: &str) -> Result {
let d = std::env::temp_dir().join(format!("solidcraft-kernel-cases-{}", std::process::id())).join(format!("{area}-{name}"));
std::fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?;
Ok(d.to_string_lossy().to_string())
}
/// Chord tolerance of the mesh a `watertight` case is checked on (mm).
const MESH_TOL: f64 = 0.01;
/// A mesh's edges used by one triangle only (open) and by more than two (over-shared). Vertices
/// closer than `weld` (mm) are one vertex: a mesh repeats a vertex for each face, and faces
/// meeting at an edge may place it a rounding error apart.
fn open_edges(positions: &[solidcraft_engine::geom::Vec3], triangles: &[[u32; 3]], weld: f64) -> (usize, usize) {
use std::collections::HashMap;
let weld = if weld.is_finite() && weld > 0.0 { weld } else { 1e-4 };
let cell = |p: &solidcraft_engine::geom::Vec3| [p.x, p.y, p.z].map(|x| (x / weld).floor() as i64);
// Union-find over positions, joining each vertex with any within `weld` in the 27 cells round it.
let mut parent: Vec = (0..positions.len()).collect();
fn find(parent: &mut [usize], mut i: usize) -> usize {
while let Some(&p) = parent.get(i) {
if p == i {
break;
}
let gp = parent.get(p).copied().unwrap_or(p);
if let Some(slot) = parent.get_mut(i) {
*slot = gp;
}
i = p;
}
i
}
let mut grid: HashMap<[i64; 3], Vec> = HashMap::new();
for (i, p) in positions.iter().enumerate() {
let c = cell(p);
for dx in -1..=1 {
for dy in -1..=1 {
for dz in -1..=1 {
let Some(near) = grid.get(&[c[0] + dx, c[1] + dy, c[2] + dz]) else { continue };
for &j in near {
if positions.get(j).is_some_and(|q| q.dist(*p) <= weld) {
let (a, b) = (find(&mut parent, i), find(&mut parent, j));
if let Some(slot) = parent.get_mut(a) {
*slot = b;
}
}
}
}
}
}
grid.entry(c).or_default().push(i);
}
let mut uses: HashMap<(usize, usize), usize> = HashMap::new();
for t in triangles {
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
let (a, b) = (find(&mut parent, a as usize), find(&mut parent, b as usize));
if a != b {
*uses.entry((a.min(b), a.max(b))).or_default() += 1;
}
}
}
(uses.values().filter(|&&n| n == 1).count(), uses.values().filter(|&&n| n > 2).count())
}
/// An error that means "this kernel can't do it yet", not a wrong answer.
/// Stations along each seam the `continuity` check samples.
const SEAM_SAMPLES: usize = 65;
/// A seam is tangent (G1), and two seams meeting at a vertex turn there, past this angle (°).
const SEAM_ANGLE_DEG: f64 = 1.0;
/// The `continuity` check's measure of `body`: over the tangent seams lying wholly within
/// `within` of `near`, the worst curvature jump (1/mm) at every station and at the stations at
/// least `clear` (mm, along the seam) from each vertex where two of those seams turn (a corner of
/// the patch's boundary, where its neighbours' own G1 seams end and no surface is G2 to both),
/// with how many seams and stations clear there were. An error where the seams can't be measured.
fn curvature_jumps(body: &solidcraft_engine::kernel::Body, near: [f64; 3], within: f64, clear: f64) -> Result {
use solidcraft_engine::geom::Vec3;
let tol =
solidcraft_engine::kernel::ContinuityTolerances { gap_mm: 1e-3, angle_deg: SEAM_ANGLE_DEG, curvature_per_mm: 0.0, ..Default::default() };
let report = solidcraft_engine::kernel::seam_diagnostics(body, &[], SEAM_SAMPLES, tol).map_err(|e| e.to_string())?;
let at = Vec3::new(near[0], near[1], near[2]);
let seams: Vec<_> = report
.seams
.iter()
.filter(|s| s.normal_angle_deg.value <= SEAM_ANGLE_DEG && s.points.len() >= 2 && s.points.iter().all(|p| p.dist(at) <= within))
.collect();
// Each seam's end directions, pointing into it.
let ends = |s: &solidcraft_engine::kernel::SeamReport| -> Option<[(Vec3, Vec3); 2]> {
let (p0, p1) = (*s.points.first()?, *s.points.last()?);
let (q0, q1) = (*s.points.get(1)?, *s.points.get(s.points.len() - 2)?);
Some([(p0, (q0 - p0).normalized()?), (p1, (q1 - p1).normalized()?)])
};
let all_ends: Vec<(Vec3, Vec3)> = seams.iter().filter_map(|s| ends(s)).flatten().collect();
let weld = 1e-6 * within.max(1.0);
let cos = SEAM_ANGLE_DEG.to_radians().cos();
// A vertex turns where another seam leaves it other than straight on.
let turns = |p: Vec3, d: Vec3| all_ends.iter().any(|(q, e)| q.dist(p) <= weld && (*e - d).len() > 1e-9 && -e.dot(d) < cos);
let (mut worst, mut worst_clear, mut stations) = (0.0f64, 0.0f64, 0usize);
for s in &seams {
let Some(e) = ends(s) else { continue };
let turning: Vec = e.iter().filter(|(p, d)| turns(*p, *d)).map(|(p, _)| *p).collect();
// Arc length along the seam to each station, from its start.
let mut along = vec![0.0f64; s.points.len()];
for k in 1..s.points.len() {
along[k] = along[k - 1] + s.points[k].dist(s.points[k - 1]);
}
let length = along.last().copied().unwrap_or(0.0);
for (k, st) in s.stations.iter().enumerate() {
worst = worst.max(st.curvature_jump_per_mm);
let a = along.get(k).copied().unwrap_or(0.0);
let from_turn = turning.iter().map(|p| if p.dist(s.points[0]) <= weld { a } else { length - a }).fold(f64::INFINITY, f64::min);
if from_turn >= clear {
worst_clear = worst_clear.max(st.curvature_jump_per_mm);
stations += 1;
}
}
}
Ok(json!({"seams": seams.len(), "stations_clear": stations, "worst_per_mm": worst, "worst_clear_per_mm": worst_clear}))
}
/// The seams a `continuity: {order, edges}` check measures on `b`, by edge index, with what
/// each lies between: `blend` (the default), every seam of a face a fillet or chamfer made (a
/// round, a chamfer face or a corner patch) with the faces either side of the edge it replaced,
/// and every seam of a corner patch with the rounds it joins: what the blend is built to meet.
/// Where two rounds meet without a patch, their seam is the input's (tangent only where the
/// rounded edges were) and is not one. `corner`, those of them on a corner patch. A list of
/// points `[[x,y,z], …]`, the edges nearest them, as Continuity Analysis picks them. An error for
/// anything else, or a point near no edge.
fn continuity_seams(b: &solidcraft_engine::doc::ModelBody, edges: &Value) -> Result, String> {
use solidcraft_engine::doc::naming::BlendSeamKind;
if let Some(points) = edges.as_array() {
let picks = points
.iter()
.map(|p| v3(p).map(|[x, y, z]| solidcraft_engine::kernel::EdgePick::Point(solidcraft_engine::geom::Vec3::new(x, y, z))))
.collect::