SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 169/509: kernel: an intersection curve is where SMLib's imprint cuts, exactly (and 3 more)
jyvikoab9c676627bc
diff --git a/apps/solidcraft-cli/src/kernel_cases.rs b/apps/solidcraft-cli/src/kernel_cases.rsindex eeddf32e07..549ad11cd2 100644--- a/apps/solidcraft-cli/src/kernel_cases.rs+++ b/apps/solidcraft-cli/src/kernel_cases.rs@@ -129,7 +129,7 @@ fn case_name(dir: &str) -> (String, String) {(name(p.parent()), name(Some(p)))}-fn check_case(dir: &str) -> Value {+fn check_case(dir: &str, dumps: Option<&std::path::Path>) -> Value {let (area, name) = case_name(dir);let mut out = json!({"case": name, "area": area, "kernel": kernel()});let want = match read_json(&format!("{dir}/expected.json")) {@@ -167,6 +167,18 @@ fn check_case(dir: &str) -> Value {let outcome = want["outcome"].as_str().unwrap_or("solid");let refused = outcome == "refused";let may_refuse = refused || outcome == "solid_or_refused";+ // The SMLib calls that fail in this case leave their inputs in its own folder.+ if let Some(root) = dumps {+ let folder = root.join(format!("{area}-{name}"));+ if let Err(e) = std::fs::create_dir_all(&folder)+ .map_err(|e| e.to_string())+ .and_then(|()| solidcraft_engine::kernel::smlib_dump_dir(Some(&folder)).map_err(|e| e.to_string()))+ {+ out["status"] = json!("fail");+ out["error"] = json!(format!("--dumps: {}: {e}", folder.display()));+ return out;+ }+ }let mut s = solidcraft_engine::Session::default();let clock = std::time::Instant::now();let ran = s.run_script(&commands);@@ -331,7 +343,15 @@ pub fn run(args: &[String]) -> Result<(), String> {if dirs.is_empty() {return Err("kernel-cases: give one or more case directories (each with recipe.json and expected.json)".into());}- let results: Vec<Value> = dirs.iter().map(|d| check_case(d)).collect();+ // `--dumps=DIR`: each case's failing SMLib calls leave their inputs in DIR/<area>-<case>.+ let dumps = args.iter().find_map(|a| a.strip_prefix("--dumps=")).map(std::path::PathBuf::from);+ if dumps.as_ref().is_some_and(|d| d.as_os_str().is_empty()) {+ return Err("kernel-cases: --dumps= needs a folder".into());+ }+ let results: Vec<Value> = dirs.iter().map(|d| check_case(d, dumps.as_deref())).collect();+ if dumps.is_some() {+ solidcraft_engine::kernel::smlib_dump_dir(None).map_err(|e| format!("kernel-cases: --dumps: {e}"))?;+ }report(args, &results);let bad = results.iter().filter(|r| matches!(r["status"].as_str(), Some("fail" | "crash"))).count();if bad > 0 { Err(format!("{bad} kernel case(s) failed")) } else { Ok(()) }diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rsindex 4fffaff44d..1bd2627a12 100644--- a/apps/solidcraft-cli/src/main.rs+++ b/apps/solidcraft-cli/src/main.rs@@ -15,7 +15,7 @@//! solidcraft-cli commands the command registry as JSON//! solidcraft-cli recipe <recipe.json> translate an oracle recipe to a script//! solidcraft-cli oracle <case-dir>... replay recipes and compare with expected.json-//! solidcraft-cli kernel-cases [--json] <case-dir>... the kernel regression rig (tests/kernel-cases)+//! solidcraft-cli kernel-cases [--json] [--dumps=DIR] <case-dir>... the kernel regression rig (tests/kernel-cases)//! solidcraft-cli mcp [--headless] [--in design|script] [--connect HOST:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]//! [--param-check off|warn|strict]//! MCP server on stdio (docs/mcp.md)@@ -82,7 +82,7 @@ const USAGE_RECIPE: &str = " solidcraft-cli recipe <recipe.json>\n";/// `oracle`'s lines in the usage.const USAGE_ORACLE: &str = " solidcraft-cli oracle <case-dir>... [--json]\n";/// `kernel-cases`'s lines in the usage.-const USAGE_KERNEL_CASES: &str = " solidcraft-cli kernel-cases <case-dir>... [--json]\n (the kernel regression rig, tests/kernel-cases; SOLIDCRAFT_KERNEL picks the kernel)\n";+const USAGE_KERNEL_CASES: &str = " solidcraft-cli kernel-cases <case-dir>... [--json] [--dumps=DIR]\n (the kernel regression rig, tests/kernel-cases; SOLIDCRAFT_KERNEL picks the kernel; --dumps: each case's\n failing SMLib calls leave their inputs for replay in DIR/<area>-<case>)\n";/// `fuzz`'s lines in the usage.const USAGE_FUZZ: &str =" solidcraft-cli fuzz [--from N] [--count N] [--jobs J] [--timeout S] [--steps N] [--minimise] [--out DIR] [--report FILE]\n";diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rsindex 5250175973..14357bbae1 100644--- a/crates/doc/src/project.rs+++ b/crates/doc/src/project.rs@@ -213,10 +213,15 @@ fn resolve_uncached(Vec::new()}LinkSource::Intersection { a, b } => {- let (ma, fa) = crate::project3d::mesh_of(st, a).ok_or_else(|| lost(&a.describe()))?;- let (mb, fb) = crate::project3d::mesh_of(st, b).ok_or_else(|| lost(&b.describe()))?;- wires = crate::project3d::mesh_intersection(&ma, fa, &mb, fb);- exact = vec![Vec::new(); wires.len()];+ // Where the bodies (or faces) meet, as the edges SMLib's imprint of one by the other+ // makes: each its exact record curve, its points at the display tolerance.+ let (ba, fa) = crate::project3d::part_of(st, a).ok_or_else(|| lost(&a.describe()))?;+ let (bb, fb) = crate::project3d::part_of(st, b).ok_or_else(|| lost(&b.describe()))?;+ let chord = (ba.body.size().max(bb.body.size()) * 1e-3).max(1e-3);+ for e in crate::kernel::meeting_edges(&ba.body, fa, &bb.body, fb, chord)? {+ wires.push(e.points);+ exact.push(vec![WireCurve { curve: e.curve, interval: e.interval }]);+ }Vec::new()}LinkSource::Iso { body, at, dir } => {diff --git a/crates/doc/src/project3d.rs b/crates/doc/src/project3d.rsindex 42f23a37c5..893f8ad427 100644--- a/crates/doc/src/project3d.rs+++ b/crates/doc/src/project3d.rs@@ -1,26 +1,20 @@-//! 3D sketch curves from the model: curves projected onto faces, intersection curves of bodies-//! and faces (on their display meshes), and spun profiles.--use std::collections::BTreeMap;-use std::sync::Arc;+//! 3D sketch curves from the model: curves projected onto faces (on their display meshes), the+//! bodies and faces an intersection curve is taken on, and spun profiles.use solidcraft_geom::{Mesh, Plane, Vec2, Vec3};use solidcraft_sketch::LinkSource;use crate::eval::ModelState;-/// Most triangle pairs examined by one intersection.-const MAX_PAIRS: usize = 20_000_000;--/// The mesh (and face, for a face source) of a body or face reference.-pub(crate) fn mesh_of(st: &ModelState, src: &LinkSource) -> Option<(Arc<Mesh>, Option<u32>)> {+/// The body of a body or face reference, and the face (its index in the body's face order) for a+/// face reference: the face nearest its point, on the named body or else the nearest body.+pub(crate) fn part_of<'a>(st: &'a ModelState, src: &LinkSource) -> Option<(&'a crate::ModelBody, Option<usize>)> {match src {- LinkSource::Body { body } => Some((st.body(body)?.mesh(), None)),+ LinkSource::Body { body } => Some((st.body(body)?, None)),LinkSource::Face { body, at } => {let b = st.body(body).or_else(|| st.bodies.iter().min_by(|x, y| dist_to(&x.mesh(), *at).total_cmp(&dist_to(&y.mesh(), *at))))?;- let m = b.mesh();- let (f, _, _) = crate::project::nearest_face(&m, *at)?;- Some((m, Some(f)))+ let (f, _, _) = crate::project::nearest_face(&b.mesh(), *at)?;+ Some((b, usize::try_from(f).ok()))}_ => None,}@@ -99,160 +93,6 @@ pub(crate) fn onto_face(m: &Mesh, f: u32, pts: &[Vec3], dir: Vec3) -> Vec<Vec<Veout}-/// Segment where two triangles cross (None when they do not, or are coplanar).-fn tri_tri(a: &[Vec3; 3], b: &[Vec3; 3]) -> Option<(Vec3, Vec3)> {- let nb = (b[1] - b[0]).cross(b[2] - b[0]).normalized()?;- let na = (a[1] - a[0]).cross(a[2] - a[0]).normalized()?;- // Points where one triangle's edges pass through the other's plane.- let cut = |t: &[Vec3; 3], n: Vec3, o: Vec3| -> Option<(Vec3, Vec3)> {- let h: Vec<f64> = t.iter().map(|p| (*p - o).dot(n)).collect();- if h.iter().all(|x| *x > 1e-12) || h.iter().all(|x| *x < -1e-12) {- return None;- }- let mut pts = Vec::new();- for (i, j) in [(0usize, 1usize), (1, 2), (2, 0)] {- let (hi, hj) = (h[i], h[j]);- if (hi > 0.0) != (hj > 0.0) {- pts.push(t[i].lerp(t[j], hi / (hi - hj)));- } else if hi == 0.0 {- pts.push(t[i]);- }- }- match pts[..] {- [p, q, ..] => Some((p, q)),- _ => None,- }- };- if na.cross(nb).len() < 1e-9 {- return None;- }- let (a0, a1) = cut(a, nb, b[0])?;- let (b0, b1) = cut(b, na, a[0])?;- // Overlap of the two segments on the common line.- let dir = na.cross(nb);- let pr = |p: Vec3| p.dot(dir);- let (sa0, sa1) = if pr(a0) <= pr(a1) { (a0, a1) } else { (a1, a0) };- let (sb0, sb1) = if pr(b0) <= pr(b1) { (b0, b1) } else { (b1, b0) };- let lo = if pr(sa0) >= pr(sb0) { sa0 } else { sb0 };- let hi = if pr(sa1) <= pr(sb1) { sa1 } else { sb1 };- (pr(hi) - pr(lo) > 1e-12).then_some((lo, hi))-}--/// Where two meshes (or faces of them) meet, as polylines.-pub(crate) fn mesh_intersection(ma: &Mesh, fa: Option<u32>, mb: &Mesh, fb: Option<u32>) -> Vec<Vec<Vec3>> {- let (ta, tb) = (tris(ma, fa), tris(mb, fb));- let bbox = |t: &[Vec3; 3]| (t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2]));- // Uniform grid over B.- let lo = tb.iter().fold(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), |m, t| m.min(bbox(t).0));- let hi = tb.iter().fold(Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |m, t| m.max(bbox(t).1));- if !(lo.is_finite() && hi.is_finite()) {- return Vec::new();- }- let n = ((tb.len() as f64).cbrt().ceil() as usize).clamp(1, 48);- let ext = hi - lo;- let cell = |p: Vec3| -> [usize; 3] {- let f = |v: f64, l: f64, e: f64| if e > 1e-12 { (((v - l) / e) * n as f64).floor().clamp(0.0, (n - 1) as f64) as usize } else { 0 };- [f(p.x, lo.x, ext.x), f(p.y, lo.y, ext.y), f(p.z, lo.z, ext.z)]- };- let mut grid: BTreeMap<[usize; 3], Vec<usize>> = BTreeMap::new();- for (i, t) in tb.iter().enumerate() {- let (b0, b1) = bbox(t);- let (c0, c1) = (cell(b0), cell(b1));- for x in c0[0]..=c1[0] {- for y in c0[1]..=c1[1] {- for z in c0[2]..=c1[2] {- grid.entry([x, y, z]).or_default().push(i);- }- }- }- }- let mut segs: Vec<(Vec3, Vec3)> = Vec::new();- let mut pairs = 0usize;- for t in &ta {- let (b0, b1) = bbox(t);- if b1.x < lo.x || b1.y < lo.y || b1.z < lo.z || b0.x > hi.x || b0.y > hi.y || b0.z > hi.z {- continue;- }- let (c0, c1) = (cell(b0), cell(b1));- let mut cand: Vec<usize> = Vec::new();- for x in c0[0]..=c1[0] {- for y in c0[1]..=c1[1] {- for z in c0[2]..=c1[2] {- if let Some(v) = grid.get(&[x, y, z]) {- cand.extend(v);- }- }- }- }- cand.sort_unstable();- cand.dedup();- for j in cand {- pairs += 1;- if pairs > MAX_PAIRS {- break;- }- if let Some(u) = tb.get(j)- && let Some(sg) = tri_tri(t, u)- {- segs.push(sg);- }- }- }- chain3(&segs, ma.bounds().diagonal().max(mb.bounds().diagonal()).max(1e-9))-}--/// Chain 3D segments into polylines by shared end points.-fn chain3(segs: &[(Vec3, Vec3)], size: f64) -> Vec<Vec<Vec3>> {- let q = size * 1e-7;- let key = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64);- let mut adj: BTreeMap<(i64, i64, i64), (Vec3, Vec<usize>)> = BTreeMap::new();- let mut uniq: Vec<((i64, i64, i64), (i64, i64, i64))> = Vec::new();- let mut seen = std::collections::BTreeSet::new();- for (a, b) in segs {- let (ka, kb) = (key(*a), key(*b));- if ka == kb {- continue;- }- let k = if ka <= kb { (ka, kb) } else { (kb, ka) };- if !seen.insert(k) {- continue;- }- let i = uniq.len();- uniq.push(k);- adj.entry(ka).or_insert_with(|| (*a, Vec::new())).1.push(i);- adj.entry(kb).or_insert_with(|| (*b, Vec::new())).1.push(i);- }- let mut used = vec![false; uniq.len()];- let mut out = Vec::new();- let starts: Vec<(i64, i64, i64)> = adj.iter().filter(|(_, v)| v.1.len() != 2).map(|(k, _)| *k).chain(adj.keys().copied()).collect();- for s in starts {- while let Some(first) = adj.get(&s).and_then(|v| v.1.iter().copied().find(|e| !used.get(*e).copied().unwrap_or(true))) {- let mut chain = vec![adj.get(&s).map(|v| v.0).unwrap_or_default()];- let mut cur = s;- let mut e = first;- loop {- if let Some(u) = used.get_mut(e) {- *u = true;- }- let Some(&(ka, kb)) = uniq.get(e) else { break };- cur = if ka == cur { kb } else { ka };- chain.push(adj.get(&cur).map(|v| v.0).unwrap_or_default());- let Some(next) = adj- .get(&cur)- .and_then(|v| if v.1.len() == 2 { v.1.iter().copied().find(|x| !used.get(*x).copied().unwrap_or(true)) } else { None })- else {- break;- };- e = next;- }- if chain.len() >= 2 {- out.push(chain);- }- }- }- out-}-/// Outline of a body spun about the axis `origin + t·dir`: the largest distance from the axis/// at each station along it, laid into the sketch plane on the side of the axis the plane's/// in-plane perpendicular points to.diff --git a/crates/kernel/src/intersection.rs b/crates/kernel/src/intersection.rsnew file mode 100644index 0000000000..2bf8c5a07e--- /dev/null+++ b/crates/kernel/src/intersection.rs@@ -0,0 +1,62 @@+//! Where two bodies meet, each whole or one face of it: the edges SMLib's imprint of the first by+//! the second makes (`capi/include/smlib.h`, "Imprint": each face the tool meets is cut along the+//! intersection). SMLib intersects the faces' surfaces and trims each curve to both faces, so an+//! edge it makes is exactly where they meet: its record curve (a B-spline SMLib fitted within its+//! tolerance, or the line, circle or ellipse it is) on its interval. Which edges are new comes from+//! the imprint's own history: an edge no edge of either operand became.++use solidcraft_geom::Vec3;+use solidcraft_geom::brep::Curve;++use crate::body::{Body, MeshTolerance};+use crate::{KernelError, Result};++/// One edge where two bodies meet.+#[derive(Clone, Debug, PartialEq)]+pub struct MeetingEdge {+ /// The edge's record curve, exactly as SMLib made it.+ pub curve: Curve,+ /// Its interval on `curve`.+ pub interval: [f64; 2],+ /// Its points at the chord tolerance asked for, from its start to its end.+ pub points: Vec<Vec3>,+}++fn failed(what: &str, e: impl std::fmt::Display) -> KernelError {+ KernelError::Failed(format!("SMLib intersection curve: {what}: {e}"))+}++/// `body` itself, or its face `face` (in its face order) alone as a surface body.+fn part(body: &Body, face: Option<usize>) -> Result<Body> {+ match face {+ None => Ok(body.clone()),+ Some(f) if f < body.record().faces.len() => crate::surfaces::taken(body, body.record(), &[(f, false)]),+ Some(f) => Err(KernelError::Invalid(format!("the body has no face {f}"))),+ }+}++/// Where `a` (or its face `a_face`) meets `b` (or its face `b_face`): every edge SMLib's imprint+/// of the one by the other makes, its points at `chord` mm. Empty where they do not meet.+pub fn meeting_edges(a: &Body, a_face: Option<usize>, b: &Body, b_face: Option<usize>, chord: f64) -> Result<Vec<MeetingEdge>> {+ let (a, b) = (part(a, a_face)?, part(b, b_face)?);+ let ta = a.smlib()?.tagged(0).map_err(|e| failed("tag", e))?;+ let tb = b.smlib()?.tagged(1).map_err(|e| failed("tag", e))?;+ let Some(cut) = ta.imprint(&tb).map_err(|e| failed("imprint", e))? else { return Ok(Vec::new()) };+ let history = cut.history().map_err(|e| failed("history", e))?;+ let (body, order) = crate::native::body_from_smlib_ordered(&cut)?;+ let order = order.ok_or_else(|| failed("history", "the imprint's edges cannot be numbered"))?;+ let mesh = body.mesh(&MeshTolerance::chord(chord))?;+ let record = body.record();+ let mut out = Vec::new();+ for (i, edge) in history.edges.iter().enumerate() {+ if !edge.origins.is_empty() {+ continue;+ }+ let at = if order.edges.is_empty() { Some(i) } else { order.edges.get(i).copied() };+ let (Some(e), Some(points)) = (at.and_then(|k| record.edges.get(k)), at.and_then(|k| mesh.edges.get(k))) else {+ return Err(failed("history", format!("edge {i} is not in the imprinted body")));+ };+ out.push(MeetingEdge { curve: e.curve.clone(), interval: e.interval, points: points.clone() });+ }+ Ok(out)+}diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rsindex 0c53bbb1c3..5ba7c43db4 100644--- a/crates/kernel/src/lib.rs+++ b/crates/kernel/src/lib.rs@@ -47,6 +47,7 @@ mod helix;pub mod history;mod iges_in;mod iges_out;+mod intersection;#[cfg(test)]mod intersection_curve_tests;#[cfg(test)]@@ -178,6 +179,7 @@ pub use fill::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, patch_edges_crowned,pub use helix::{loft_to_point, sweep_helix, sweep_helix_mesh};pub use iges_in::{MAX_IGES_BYTES, iges_import, iges_to_step};pub use iges_out::iges_export_bodies;+pub use intersection::{MeetingEdge, meeting_edges};pub use lip::{raise_band, rim_band};pub use loft_blend::loft_blend;pub use matchsurf::{match_surface, seam_continuity};@@ -217,7 +219,7 @@ pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at};pub use topo::{TopoCounts, merged_topology, seam_flags};pub use tspline::tspline_sheet;-pub use validity::{SmlibCheck, Validity, smlib_built, validity};+pub use validity::{SmlibCheck, Validity, smlib_built, smlib_dump_dir, validity};pub use whole_face::{WholeFace, cut_takes_only_the_face, cut_tool, face_prism, matching_face};#[derive(Debug, Clone, PartialEq, thiserror::Error)]diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rsindex 8603af49f6..1991747eff 100644--- a/crates/kernel/src/surfaces.rs+++ b/crates/kernel/src/surfaces.rs@@ -366,7 +366,7 @@ pub(crate) fn all_new(body: Body, operands: &[&Body]) -> Result<Body> {/// The faces `picked` of `body` (its record `r`; each with whether to turn it over) as their own/// body, each the body's face (Kept), every edge the body's.-fn taken(body: &Body, r: &Brep, picked: &[(usize, bool)]) -> Result<Body> {+pub(crate) fn taken(body: &Body, r: &Brep, picked: &[(usize, bool)]) -> Result<Body> {let c = Parts::of(r, picked)?.canonical()?;let faces = c.faces.iter().map(|p| picked.get(*p).map_or(0, |(f, _)| *f)).map(|f| record::from_face(0, f, Change::Kept)).collect();let h = record_history(&c.brep, 1, faces, |e, _, _| c.edges.get(e).map(|&edge| EdgeOrigin::Edge { operand: 0, edge }).into_iter().collect());diff --git a/crates/kernel/src/validity.rs b/crates/kernel/src/validity.rsindex 52cb851295..e5dd336ee2 100644--- a/crates/kernel/src/validity.rs+++ b/crates/kernel/src/validity.rs@@ -59,3 +59,17 @@ pub fn smlib_built() -> bool {cfg!(feature = "smlib")}+/// Where every SMLib call that fails from now on leaves its inputs for replay (the C API's+/// `smlib_set_dump_dir`: the call's arguments and B-reps, which `smlib_brep_read` reads back);+/// `None` stops it. A build without SMLib makes no calls to dump.+pub fn smlib_dump_dir(dir: Option<&std::path::Path>) -> crate::Result<()> {+ #[cfg(feature = "smlib")]+ {+ solidcraft_smlib::set_dump_dir(dir).map_err(|e| crate::KernelError::Failed(format!("SMLib dump folder: {e}")))+ }+ #[cfg(not(feature = "smlib"))]+ {+ let _ = dir;+ Ok(())+ }+}diff --git a/crates/sketch/src/wire.rs b/crates/sketch/src/wire.rsindex efd903bdb6..5d9893103e 100644--- a/crates/sketch/src/wire.rs+++ b/crates/sketch/src/wire.rs@@ -63,9 +63,9 @@ pub struct Wire {#[serde(default, skip_serializing_if = "Option::is_none")]pub arc: Option<WireArc>,/// A linked curve's exact geometry where its source has one (an included edge or sketch- /// curve): record curves end to end along `pts`, in `space` coordinates. Empty for a curve- /// known only as its points (projected onto a face, intersection and iso curves). Set when- /// the link is resolved, with `pts`.+ /// curve, an intersection curve): record curves end to end along `pts`, in `space`+ /// coordinates. Empty for a curve known only as its points (projected onto a face, iso+ /// curves). Set when the link is resolved, with `pts`.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub exact: Vec<WireCurve>,}diff --git a/tests/kernel-cases/README.md b/tests/kernel-cases/README.mdindex 67733cf247..119e22bd40 100644--- a/tests/kernel-cases/README.md+++ b/tests/kernel-cases/README.md@@ -8,6 +8,7 @@ them. `cargo xtask kernel-cases` runs them and writes [`docs/kernel-cases.md`](.cargo xtask kernel-cases # the default kernelcargo xtask kernel-cases --kernel both --cli target/release/solidcraft-cli # and SMLibcargo run -p solidcraft-cli -- kernel-cases tests/kernel-cases/booleans/<id> # one case+cargo run -p solidcraft-cli --features smlib -- kernel-cases --dumps=/tmp/dumps <case-dir> # failing SMLib calls leave replayable inputs```For the `smlib` column, build `solidcraft-cli` with `--features smlib` (after