From 5a4e482e9c5d72f1274c0f666a8b2c3606b8489c Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:57:25 -0400 Subject: [PATCH] Wave 260/509: Formatting: rustfmt over the rebased branch (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 562a5bd33 jyviko: Formatting: rustfmt over the rebased branch - bc15221fa jyviko: The desktop app links SMLib by default - e476aba94 jyviko: SMLib in the browser: built with wasi-sdk for wasm32-unknown-unknown - e1ad6ec1a jyviko: SMLib links prebuilt: one build per commit, pinned by SHA-256 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- Cargo.lock | 1 + apps/solidcraft-web/Cargo.toml | 3 + apps/solidcraft/Cargo.toml | 5 +- crates/doc/src/eval.rs | 17 +-- crates/doc/src/eval_thread.rs | 7 +- crates/doc/src/model_cache.rs | 8 +- crates/engine/src/cmd/component_extract.rs | 9 +- .../src/cmd/config_certificate_tests.rs | 3 +- crates/engine/src/cmd/features.rs | 11 +- crates/engine/src/cosmetic_threads.rs | 3 +- crates/engine/src/tests.rs | 7 +- crates/geom/src/brep.rs | 11 +- crates/geom/src/brep/tests.rs | 3 +- crates/geom/src/tess.rs | 8 +- crates/kernel/src/fill.rs | 3 +- crates/kernel/src/intersection_curve_tests.rs | 9 +- crates/kernel/src/lib.rs | 5 +- crates/kernel/src/polyhedron.rs | 9 +- crates/kernel/src/prism.rs | 4 +- crates/kernel/src/smooth_edges.rs | 1 - crates/kernel/src/step_in/parallel.rs | 3 +- crates/kernel/src/step_in/tests.rs | 11 +- crates/kernel/src/surfaces.rs | 9 +- crates/sketch/src/wire.rs | 10 +- crates/smlib/Cargo.toml | 4 + crates/smlib/SMLIB_PREBUILT | 10 ++ crates/smlib/SMLIB_REV | 2 +- crates/smlib/build.rs | 102 +++++++++++-- crates/smlib/src/ffi.rs | 144 ++++++++++++++++++ crates/smlib/src/ops.rs | 10 +- crates/step/src/topology.rs | 3 +- crates/step/src/topology/seams.rs | 7 +- crates/ui-egui/src/browser.rs | 4 +- crates/ui-egui/src/context_menu.rs | 3 +- crates/ui-egui/src/dialogs_all_tests.rs | 5 +- .../ui-egui/src/dimension_create_ui_tests.rs | 3 +- crates/ui-egui/src/hole_refs.rs | 4 +- crates/ui-egui/src/sketch_dims_tests.rs | 3 +- scripts/fetch-smlib.sh | 107 +++++++++++-- 39 files changed, 486 insertions(+), 85 deletions(-) create mode 100644 crates/smlib/SMLIB_PREBUILT diff --git a/Cargo.lock b/Cargo.lock index 15c547f20..fd5e712ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4262,6 +4262,7 @@ dependencies = [ "log", "serde_json", "solidcraft-geom", + "web-time", ] [[package]] diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.toml index 2339990a3..cb189f7dc 100644 --- a/apps/solidcraft-web/Cargo.toml +++ b/apps/solidcraft-web/Cargo.toml @@ -16,6 +16,9 @@ path = "src/main.rs" [features] default = [] bundled-render-library = ["solidcraft-engine/bundled-render-library"] +# Link SMLib into the kernel (solidcraft-engine/smlib): needs scripts/fetch-smlib.sh and wasi-sdk in +# WASI_SDK_PATH (crates/smlib/build.rs). Off by default until CI has wasi-sdk. +smlib = ["solidcraft-engine/smlib"] [dependencies] solidcraft-engine = { workspace = true } diff --git a/apps/solidcraft/Cargo.toml b/apps/solidcraft/Cargo.toml index 85ba05660..8ffa40e89 100644 --- a/apps/solidcraft/Cargo.toml +++ b/apps/solidcraft/Cargo.toml @@ -8,9 +8,12 @@ publish = false default-run = "solidcraft" [features] -default = ["raytrace-cpu", "bundled-render-library"] +default = ["raytrace-cpu", "bundled-render-library", "smlib"] bundled-render-library = ["solidcraft-engine/bundled-render-library"] raytrace-cpu = ["solidcraft-engine/raytrace-cpu"] +# Link SMLib into the kernel (solidcraft-engine/smlib; needs scripts/fetch-smlib.sh). SMLib is the +# only kernel, so without it the app models nothing. +smlib = ["solidcraft-engine/smlib"] # The workspace lints, except unsafe_code: denied, not forbidden, so that src/open_documents.rs # (macOS file-open events), src/native_crash.rs (Windows exception filter), src/native_crash_macos.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index b082bc724..5b9fe430b 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1962,13 +1962,7 @@ impl Model { Err(e) => Some(e.to_string().trim_start_matches("the operation failed: ").to_string()), }; if !self.no_cache { - let e = CachedEval { - error: error.clone(), - warning: warning.clone(), - ms, - bytes: state.added_bytes(&before), - state: state.clone(), - }; + let e = CachedEval { error: error.clone(), warning: warning.clone(), ms, bytes: state.added_bytes(&before), state: state.clone() }; if let Some(k) = &self.kept.0 { k.put(key, &e); } @@ -2165,9 +2159,9 @@ pub fn draft_corner_options(ss: &SolvedSketch, sel: &ProfileSel, distance: f64, /// line nor an arc), then the tangent rule, with a note in `notes` saying where and why. fn draft_corner_for(ss: &SolvedSketch, r: &Region2, distance: f64, taper: f64, notes: &mut Vec) -> Result { let reports = kernel::draft_corners(r, distance, taper)?; - let inexact = reports.iter().find(|c| { - c.options.iter().any(|o| o.rule == kernel::DraftCorner::PreserveCurvature && o.fill == Err(kernel::CornerRefusal::NotExact)) - }); + let inexact = reports + .iter() + .find(|c| c.options.iter().any(|o| o.rule == kernel::DraftCorner::PreserveCurvature && o.fill == Err(kernel::CornerRefusal::NotExact))); Ok(match inexact { Some(c) => { notes.push(format!( @@ -4394,7 +4388,8 @@ fn feature_tools_with_constructor( let tools: Vec = regions .iter() .map(|r| { - let roles = crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone(), thin: thin_roles.as_ref() }; + let roles = + crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone(), thin: thin_roles.as_ref() }; let corner = match extent.corner { Some(c) => c, None => draft_corner_for(&ss, r, len, taper, &mut notes)?, diff --git a/crates/doc/src/eval_thread.rs b/crates/doc/src/eval_thread.rs index be2ff80fa..01fcd35b6 100644 --- a/crates/doc/src/eval_thread.rs +++ b/crates/doc/src/eval_thread.rs @@ -173,9 +173,10 @@ pub(super) fn thread_on(st: &ModelState, feature: u64, p: Vec3, ask: &ThreadAsk) let tapped = match (ask.tapped, ask.designation) { (false, _) => None, (true, None) => return Err(DocError::Invalid("a tapped hole needs a designation".into())), - (true, Some(name)) => Some(crate::parse_tapped_thread(name).ok_or_else(|| { - DocError::Invalid(format!("unknown tapped thread `{name}` (ISO metric or a catalogued UNC/UNF, G or Rp size)")) - })?), + (true, Some(name)) => Some( + crate::parse_tapped_thread(name) + .ok_or_else(|| DocError::Invalid(format!("unknown tapped thread `{name}` (ISO metric or a catalogued UNC/UNF, G or Rp size)")))?, + ), }; let size = match (&tapped, ask.designation) { (Some(t), _) => crate::thread_forms::ThreadSize { form, major: t.major_diameter, pitch: t.pitch, lead: t.pitch }, diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs index f6f03a984..e32cf82fe 100644 --- a/crates/doc/src/model_cache.rs +++ b/crates/doc/src/model_cache.rs @@ -623,13 +623,7 @@ impl Model { let local = fingerprint(doc, 0, f, &vals, false, &model.step_digests) ^ placement_digest(doc, f, Some(&before)); cache.put( cache_key(f, r.fingerprint, local, ctx, &before), - CachedEval { - error: None, - warning: r.warning.clone(), - ms: r.ms, - bytes: r.state.retained_bytes(), - state: r.state.clone(), - }, + CachedEval { error: None, warning: r.warning.clone(), ms: r.ms, bytes: r.state.retained_bytes(), state: r.state.clone() }, ); before = r.state.clone(); } diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs index 5562d5caf..fab3b78bd 100644 --- a/crates/engine/src/cmd/component_extract.rs +++ b/crates/engine/src/cmd/component_extract.rs @@ -718,7 +718,8 @@ mod tests { } fn volumes(s: &Session) -> BTreeMap { - s.world_state().unwrap() + s.world_state() + .unwrap() .bodies .iter() .map(|b| (b.name.clone(), (solidcraft_kernel::measure(&b.body).unwrap().volume * 1000.0).round() as i64)) @@ -726,7 +727,8 @@ mod tests { } fn centroids(s: &Session) -> BTreeMap { - s.world_state().unwrap() + s.world_state() + .unwrap() .bodies .iter() .map(|b| { @@ -740,7 +742,8 @@ mod tests { /// coarser than what a link's STEP round trip changes in a round face. fn shapes(s: &Session) -> Vec<[i64; 4]> { let mut out: Vec<[i64; 4]> = s - .world_state().unwrap() + .world_state() + .unwrap() .bodies .iter() .map(|b| { diff --git a/crates/engine/src/cmd/config_certificate_tests.rs b/crates/engine/src/cmd/config_certificate_tests.rs index ae7b451aa..61d926c53 100644 --- a/crates/engine/src/cmd/config_certificate_tests.rs +++ b/crates/engine/src/cmd/config_certificate_tests.rs @@ -115,7 +115,8 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam // and numbering the pieces of its faces as that build did (#3902); saved before joins split // off pieces that touch only along an edge or at a point, it keeps them in // one body. - let anchored = solidcraft_doc::Feature { shell_piece_order: true, kernel_piece_order: true, touching: solidcraft_doc::Touching::OneBody, ..anchored }; + let anchored = + solidcraft_doc::Feature { shell_piece_order: true, kernel_piece_order: true, touching: solidcraft_doc::Touching::OneBody, ..anchored }; assert_eq!(reopened.doc.feature(anchored.id).unwrap(), &anchored); // Names saved before format 14 keep naming the face they named, marked so they are found as // the build that saved them found them. diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index bc037b534..09d9c80c6 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1453,7 +1453,16 @@ fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result> { match b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol)) { // An edge where the faces meet tangentially (the spans of a spline wall // meeting) can't be blended either: nobody means it by a pick. - Ok(m) => Some((size, m.edges, m.seams.iter().zip(&m.smooth_edges).map(|(s, t)| *s || *t).chain(m.seams.iter().skip(m.smooth_edges.len()).copied()).collect())), + Ok(m) => Some(( + size, + m.edges, + m.seams + .iter() + .zip(&m.smooth_edges) + .map(|(s, t)| *s || *t) + .chain(m.seams.iter().skip(m.smooth_edges.len()).copied()) + .collect(), + )), Err(_) => b.body.edges(tol).ok().map(|edges| (size, edges.into_iter().map(|e| e.points).collect(), Vec::new())), } }) diff --git a/crates/engine/src/cosmetic_threads.rs b/crates/engine/src/cosmetic_threads.rs index eff988adc..6dd592069 100644 --- a/crates/engine/src/cosmetic_threads.rs +++ b/crates/engine/src/cosmetic_threads.rs @@ -353,7 +353,8 @@ mod tests { &crate::view::Palette::DEFAULT, Default::default(), true, - ).unwrap(); + ) + .unwrap(); assert!(scene.lines.iter().any(|l| l.width == 0.85 && !l.on_top)); let marked = crate::render::render(&scene, &cam, 320, 240).rgba; scene.lines.retain(|l| l.width != 0.85); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a9d8c3b03..950f1750e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3657,7 +3657,12 @@ fn an_exact_pick_of_a_region_cut_by_the_face_outline_takes_only_that_region() { let state = s2.model.state(); let Some(solidcraft_doc::FeatureKind::Extrude { profiles, .. }) = s2.doc.features.last().map(|f| &f.kind) else { panic!("an extrude") }; let count = solidcraft_doc::profile_selection_indices(state.sketch(id).unwrap(), profiles).unwrap().len(); - let v = state.bodies.iter().filter(|b| b.name.starts_with("Pad")).map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume).sum(); + let v = state + .bodies + .iter() + .filter(|b| b.name.starts_with("Pad")) + .map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume) + .sum(); (v, count) }; for (profiles, want, n) in [ diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rs index dbc3cab74..df6f33e8a 100644 --- a/crates/geom/src/brep.rs +++ b/crates/geom/src/brep.rs @@ -591,7 +591,10 @@ impl Brep { )?; } // A circle or ellipse is a label: its geometry is its NURBS form. - require(e.nurbs.is_some() || !matches!(e.curve, Curve::Circle { .. } | Curve::Ellipse { .. }), "a circle or ellipse without its NURBS form")?; + require( + e.nurbs.is_some() || !matches!(e.curve, Curve::Circle { .. } | Curve::Ellipse { .. }), + "a circle or ellipse without its NURBS form", + )?; interval(&e.interval, curve_natural(e.parameters()))?; require(e.vertices.iter().all(|&v| (v as usize) < self.vertices.len()), "edge vertices")?; tolerance(e.tolerance)?; @@ -619,7 +622,11 @@ impl Brep { f.nurbs.is_some() || !matches!( f.surface, - Surface::Cylinder { .. } | Surface::Cone { .. } | Surface::Sphere { .. } | Surface::Torus { .. } | Surface::PlacedRevolution { .. } + Surface::Cylinder { .. } + | Surface::Cone { .. } + | Surface::Sphere { .. } + | Surface::Torus { .. } + | Surface::PlacedRevolution { .. } ), "a cylinder, cone, sphere, torus or revolution without its NURBS form", )?; diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs index cf03070c0..02fd84fe1 100644 --- a/crates/geom/src/brep/tests.rs +++ b/crates/geom/src/brep/tests.rs @@ -814,7 +814,8 @@ fn a_hole_beside_the_seam_lies_in_its_face_turn() { let cylinder = Surface::Cylinder { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; let s = -10f64.to_radians(); let at = |a: f64, z: f64| [r * a.cos(), r * a.sin(), z]; - let ring = |z: f64| Curve::Circle { frame: Frame { origin: [0., 0., z], x_axis: [s.cos(), s.sin(), 0.], y_axis: [-s.sin(), s.cos(), 0.] }, radius: r }; + let ring = + |z: f64| Curve::Circle { frame: Frame { origin: [0., 0., z], x_axis: [s.cos(), s.sin(), 0.], y_axis: [-s.sin(), s.cos(), 0.] }, radius: r }; let (bottom, top) = (ring(0.), ring(h)); let seam = Curve::Line { start: at(s, 0.), end: at(s, h) }; let (a0, a1) = (15f64.to_radians(), 25f64.to_radians()); diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rs index fac3a0a91..67828bab8 100644 --- a/crates/geom/src/tess.rs +++ b/crates/geom/src/tess.rs @@ -268,12 +268,10 @@ impl EvalSurface { fn interval(&self, d: usize) -> Option<(f64, f64)> { match self { EvalSurface::Plane { .. } => None, - EvalSurface::Nurbs { degree, knots, count, .. } => { - Some((*knots.get(d)?.get(*degree.get(d)?)?, *knots.get(d)?.get(*count.get(d)?)?)) + EvalSurface::Nurbs { degree, knots, count, .. } => Some((*knots.get(d)?.get(*degree.get(d)?)?, *knots.get(d)?.get(*count.get(d)?)?)), + EvalSurface::Revolved { profile, swap, .. } => { + (d == usize::from(*swap)).then(|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?))).flatten() } - EvalSurface::Revolved { profile, swap, .. } => (d == usize::from(*swap)) - .then(|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?))) - .flatten(), } } diff --git a/crates/kernel/src/fill.rs b/crates/kernel/src/fill.rs index 58e6d3df1..bf4983514 100644 --- a/crates/kernel/src/fill.rs +++ b/crates/kernel/src/fill.rs @@ -785,7 +785,8 @@ fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap b::Brep { }; let curve = |k: usize| if k == 0 { traced.clone() } else { Curve::Line { start: corners[k], end: corners[(k + 1) % 3] } }; let edges = (0..3) - .map(|k| b::Edge { nurbs: None, curve: curve(k), interval: [0.0, 1.0], vertices: [k as u32, ((k + 1) % 3) as u32], tolerance: 1e-6, uses: Vec::new() }) + .map(|k| b::Edge { + nurbs: None, + curve: curve(k), + interval: [0.0, 1.0], + vertices: [k as u32, ((k + 1) % 3) as u32], + tolerance: 1e-6, + uses: Vec::new(), + }) .collect(); let uses = (0..3) .map(|k| b::OrientedEdge { diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 72719b057..510bb57af 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -151,7 +151,10 @@ mod untouched_faces_tests; mod validity; pub mod watch; -pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each, fillet_setback, tangent_chain}; +pub use blend::{ + ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each, fillet_setback, + tangent_chain, +}; pub use blend_corner::fillet_radii; pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper}; pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, MeshTolerance, Paint}; diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rs index c308d0326..3f9766b73 100644 --- a/crates/kernel/src/polyhedron.rs +++ b/crates/kernel/src/polyhedron.rs @@ -161,7 +161,14 @@ fn polyhedron_record(hs: &[HalfSpace], verts: &[Vec3], faces: &[(usize, Vec crate::Result { /// and brought back as a body: the part SMLib made of the file. A solid the reader or SMLib /// refuses is not imported, with the reason. pub(super) fn smlib_part(ex: &Exchange, item: u64, units: Units) -> std::result::Result<(Part, Vec), Failure> { - let solid = solidcraft_step::topology::read_solid_with(ex, item, units, &solidcraft_smlib::pcurves::SmlibTrims).map_err(|msg| Failure { read: true, msg })?; + let solid = solidcraft_step::topology::read_solid_with(ex, item, units, &solidcraft_smlib::pcurves::SmlibTrims) + .map_err(|msg| Failure { read: true, msg })?; let failed = |e: KernelError| Failure { read: false, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() }; let (brep, smlib_order) = crate::native::smlib_record_ordered(&solid.brep).map_err(failed)?; let (body, body_order) = crate::native::body_from_smlib_ordered(&brep).map_err(failed)?; diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index e9d3c173c..56abfd5eb 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -471,7 +471,16 @@ fn cube_entities() -> String { let (p, q) = (pts[*a], pts[*b]); let d = (q.0 - p.0, q.1 - p.1, q.2 - p.2); s += &format!("#{}=DIRECTION('',({}.,{}.,{}.));\n#{}=VECTOR('',#{},1.);\n", 600 + 2 * k, d.0, d.1, d.2, 601 + 2 * k, 600 + 2 * k); - s += &format!("#{}=LINE('',#{},#{});\n#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", 300 + k, 200 + a, 601 + 2 * k, 320 + k, 210 + a, 210 + b, 300 + k); + s += &format!( + "#{}=LINE('',#{},#{});\n#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", + 300 + k, + 200 + a, + 601 + 2 * k, + 320 + k, + 210 + a, + 210 + b, + 300 + k + ); } // Faces: (edge, forward?) loops counter-clockwise seen from outside, and plane frames. let faces: [(&[(usize, bool)], (i32, i32, i32), (i32, i32, i32)); 6] = [ diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index a99d6f93b..6fb52f9e6 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -829,7 +829,14 @@ pub fn extend(body: &Body, at: &[Vec3], distance: f64) -> Result { .iter() .enumerate() .map(|(i, e)| { - Ok(b::pcurve::EdgeUse { edge: index(i)?, curve: e.parameters(), interval: e.interval, forward: true, tolerance: e.tolerance, given: None }) + Ok(b::pcurve::EdgeUse { + edge: index(i)?, + curve: e.parameters(), + interval: e.interval, + forward: true, + tolerance: e.tolerance, + given: None, + }) }) .collect::>>()?; let surface = b::Surface::Plane { origin: a3(origin), u_axis: a3(du), v_axis: a3(dv) }; diff --git a/crates/sketch/src/wire.rs b/crates/sketch/src/wire.rs index 5d9893103..a99611085 100644 --- a/crates/sketch/src/wire.rs +++ b/crates/sketch/src/wire.rs @@ -335,7 +335,15 @@ impl Sketch { Some(o) => o.clone(), None => self.fresh("w")?, }; - self.wires.push(Wire { id: wid, pts, space: WireSpace::Component, link: Some(id.to_string()), fit: Vec::new(), arc: None, exact: Vec::new() }); + self.wires.push(Wire { + id: wid, + pts, + space: WireSpace::Component, + link: Some(id.to_string()), + fit: Vec::new(), + arc: None, + exact: Vec::new(), + }); } Ok(()) } diff --git a/crates/smlib/Cargo.toml b/crates/smlib/Cargo.toml index c7f117395..16290aa71 100644 --- a/crates/smlib/Cargo.toml +++ b/crates/smlib/Cargo.toml @@ -28,6 +28,10 @@ native = [] log = { workspace = true } solidcraft-geom = { workspace = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +# The clocks SMLib's C library asks for in a browser build (src/ffi.rs). +web-time = { workspace = true } + [build-dependencies] cc = { version = "1.2", features = ["parallel"] } diff --git a/crates/smlib/SMLIB_PREBUILT b/crates/smlib/SMLIB_PREBUILT new file mode 100644 index 000000000..4d57ce5ac --- /dev/null +++ b/crates/smlib/SMLIB_PREBUILT @@ -0,0 +1,10 @@ +# Rust target, SHA-256 of smlib-.tar.gz in the release prebuilt- of +# tangency-labs/smlib. Written by scripts/fetch-smlib.sh --pin; never edited by hand. +aarch64-apple-darwin 09ce8b7cc7598f2600ab2b117b9d1a5ebfecddaad0ce21b80c731bc6671b3673 +aarch64-pc-windows-msvc e36e4810b4cfdcdcf7fae1d30f5f25313aba92668fcda68452415fb30174d4a3 +aarch64-unknown-linux-gnu 1e6d149632160bc298b3b7c43b029e4155569c8172c4e59c9b8d614ca78893e1 +i686-pc-windows-msvc 5c731edbd96e7d7b608aad755bbb0cc18c2bd90699862cf227cc3338ec22dc3b +wasm32-unknown-unknown 9dceb0fb9b9253e231cc5b929f93924c4ee80566685302bf6bbb906988ade46e +x86_64-apple-darwin a30676477cd12e7f9e3c98744fb6f96a27b8fcbfe6dfb2478a6c79e6dac7a29a +x86_64-pc-windows-msvc 72f3ba519fe7a76c278cda772c00a6189c211f52d4c4c1584f7dc2da8c7fc2cb +x86_64-unknown-linux-gnu 4c00ac33f3feb547fb151104580d56c291e7879c4773805539b0033fe27a4962 diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV index ca36ab7eb..84e9f578b 100644 --- a/crates/smlib/SMLIB_REV +++ b/crates/smlib/SMLIB_REV @@ -1 +1 @@ -a15b5a2885384a9d10e76a68ba8b79526faccb09 +8b57e7e8ace9e7886ce9936cfe45f3ed947c4006 diff --git a/crates/smlib/build.rs b/crates/smlib/build.rs index bc9f0af6f..f9eb2f311 100644 --- a/crates/smlib/build.rs +++ b/crates/smlib/build.rs @@ -1,16 +1,22 @@ -//! Builds SMLib, SM_API and their C API (tangency-labs/smlib, at the commit in `SMLIB_REV`) into -//! static libraries, when the `native` feature is on. The sources come from -//! `SOLIDCRAFT_SMLIB_DIR`, or from `target/smlib-` as `scripts/fetch-smlib.sh` leaves them. +//! Links SMLib, SM_API and their C API (tangency-labs/smlib, at the commit in `SMLIB_REV`) as +//! static libraries, when the `native` feature is on. In order: +//! - `SOLIDCRAFT_SMLIB_DIR`: a checkout, compiled here; +//! - the prebuilt library for the target, as `scripts/fetch-smlib.sh` leaves it in +//! `target/smlib--prebuilt/`, when its SHA-256 is the one in `SMLIB_PREBUILT`; +//! - the sources in `target/smlib-` (`scripts/fetch-smlib.sh --source`), compiled here. //! -//! The file lists, defines and include order follow the fork's `capi/CMakeLists.txt`: SMLib/inc -//! and SM_API/inc each have a StdAfx.h, so each part must find its own first. +//! The prebuilt libraries come from the fork's `capi/CMakeLists.txt`. The compiled path follows +//! it: the same file lists, defines and include order (SMLib/inc and SM_API/inc each have a +//! StdAfx.h, so each part must find its own first). use std::path::{Path, PathBuf}; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=SMLIB_REV"); + println!("cargo:rerun-if-changed=SMLIB_PREBUILT"); println!("cargo:rerun-if-env-changed=SOLIDCRAFT_SMLIB_DIR"); + println!("cargo:rerun-if-env-changed=WASI_SDK_PATH"); if std::env::var_os("CARGO_FEATURE_NATIVE").is_none() { return; } @@ -24,14 +30,26 @@ fn main() { fn build() -> Result<(), String> { let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").map_err(|e| e.to_string())?); let rev = std::fs::read_to_string(manifest.join("SMLIB_REV")).map_err(|e| format!("SMLIB_REV: {e}"))?.trim().to_string(); + let rev12 = rev.get(..12).unwrap_or(&rev); + let target = std::env::var("TARGET").unwrap_or_default(); + let fetched = manifest.join("../../target"); let root = match std::env::var_os("SOLIDCRAFT_SMLIB_DIR") { Some(d) => PathBuf::from(d), - None => manifest.join("../../target").join(format!("smlib-{}", rev.get(..12).unwrap_or(&rev))), + None => { + let prebuilt = fetched.join(format!("smlib-{rev12}-prebuilt")).join(&target); + if let Some(sha) = pinned(&manifest, &target)? { + println!("cargo:rerun-if-changed={}", prebuilt.join(".sha256").display()); + let have = std::fs::read_to_string(prebuilt.join(".sha256")).unwrap_or_default(); + if have.trim() == sha { + return link_prebuilt(&prebuilt, &target); + } + } + fetched.join(format!("smlib-{rev12}")) + } }; if !root.join("capi/include/smlib.h").is_file() { return Err(format!( - "the SMLib sources are not at {} (feature `native`): run scripts/fetch-smlib.sh, or set SOLIDCRAFT_SMLIB_DIR to a tangency-labs/smlib checkout at {rev}", - root.display() + "SMLib {rev} for {target} is not fetched (feature `native`): run scripts/fetch-smlib.sh {target}, or set SOLIDCRAFT_SMLIB_DIR to a tangency-labs/smlib checkout at that commit" )); } println!("cargo:rerun-if-changed={}", root.join("capi").display()); @@ -40,8 +58,8 @@ fn build() -> Result<(), String> { let src = root.join("source"); let core = sources(&src.join("SMLib/src"), &["StdAfx.cpp", "SmDllMain.cpp"])?; let api = sources(&src.join("SM_API/src"), &["StdAfx.cpp"])?; - let target = std::env::var("TARGET").unwrap_or_default(); let msvc = target.contains("msvc"); + let wasi = if target == "wasm32-unknown-unknown" { Some(wasi_sdk()?) } else { None }; let base = || { let mut b = cc::Build::new(); @@ -49,6 +67,17 @@ fn build() -> Result<(), String> { // Rust links the MSVC runtime as a DLL; the cc crate's default (/MD) matches. if msvc { b.flag("/EHsc").flag("/bigobj"); + } else { + // No fused multiply-add, as the prebuilt libraries (capi/CMakeLists.txt): SMLib's + // tangent cases decide on the last bits. MSVC does not contract by default. + b.flag("-ffp-contract=off"); + } + if let Some(sdk) = &wasi { + b.compiler(sdk.join("bin/clang++")).archiver(sdk.join("bin/llvm-ar")).target(WASI_TARGET); + b.flag(format!("--sysroot={}", sdk.join("share/wasi-sysroot").display())).flag("-fwasm-exceptions"); + // The exnref encoding, as wasi-sdk's libc++ and Rust use: a module may not mix it with + // the legacy one clang still defaults to. + b.flag("-mllvm").flag("-wasm-use-legacy-eh=false"); } b }; @@ -77,9 +106,64 @@ fn build() -> Result<(), String> { k.files(&core).include(src.join("SMLib/inc")); quiet(&mut k); k.try_compile("smlib_core").map_err(|e| e.to_string())?; + + // The C++ runtime and the C library SMLib needs, from wasi-sdk: the exception-handling build of + // libc++. The few WASI calls libc makes are answered by src/wasi.rs. + if let Some(sdk) = &wasi { + let lib = sdk.join("share/wasi-sysroot/lib").join(WASI_TARGET); + println!("cargo:rustc-link-search=native={}", lib.join("eh").display()); + println!("cargo:rustc-link-search=native={}", lib.display()); + for l in ["c++", "c++abi", "unwind", "c"] { + println!("cargo:rustc-link-lib=static={l}"); + } + } Ok(()) } +/// The SHA-256 `SMLIB_PREBUILT` pins for `target`'s prebuilt archive, if there is one. +fn pinned(manifest: &Path, target: &str) -> Result, String> { + let pins = std::fs::read_to_string(manifest.join("SMLIB_PREBUILT")).map_err(|e| format!("SMLIB_PREBUILT: {e}"))?; + Ok(pins.lines().filter(|l| !l.starts_with('#')).find_map(|l| { + let mut f = l.split_whitespace(); + (f.next() == Some(target)).then(|| f.next().map(str::to_string)).flatten() + })) +} + +/// Links the prebuilt C API in `dir` (one archive, `smlib`) and the C++ runtime it was compiled +/// against: the system's, or for wasm wasi-sdk's, which the archive carries. +fn link_prebuilt(dir: &Path, target: &str) -> Result<(), String> { + let lib = dir.join("lib"); + if !lib.is_dir() { + return Err(format!("{} has no lib folder: run scripts/fetch-smlib.sh {target} again", dir.display())); + } + println!("cargo:rustc-link-search=native={}", lib.display()); + println!("cargo:rustc-link-lib=static=smlib"); + if target == "wasm32-unknown-unknown" { + for l in ["c++", "c++abi", "unwind", "c"] { + println!("cargo:rustc-link-lib=static={l}"); + } + } else if target.contains("apple") { + println!("cargo:rustc-link-lib=c++"); + } else if !target.contains("msvc") { + println!("cargo:rustc-link-lib=stdc++"); + } + Ok(()) +} + +/// The C target SMLib is compiled for inside a `wasm32-unknown-unknown` build: wasi-sdk's, the +/// one with a C++ standard library. +const WASI_TARGET: &str = "wasm32-wasip1"; + +/// wasi-sdk, from `WASI_SDK_PATH` (github.com/WebAssembly/wasi-sdk, release 34 or later). +fn wasi_sdk() -> Result { + let sdk = + std::env::var_os("WASI_SDK_PATH").map(PathBuf::from).ok_or("building SMLib for wasm32-unknown-unknown needs wasi-sdk: set WASI_SDK_PATH")?; + if !sdk.join("bin/clang++").is_file() { + return Err(format!("WASI_SDK_PATH={} has no bin/clang++", sdk.display())); + } + Ok(sdk) +} + /// The `.cpp` files in `dir`, sorted, without `skip`. fn sources(dir: &Path, skip: &[&str]) -> Result, String> { let mut v: Vec = std::fs::read_dir(dir) diff --git a/crates/smlib/src/ffi.rs b/crates/smlib/src/ffi.rs index 6f4f2554b..136da360e 100644 --- a/crates/smlib/src/ffi.rs +++ b/crates/smlib/src/ffi.rs @@ -259,3 +259,147 @@ mod primitive_calls { } pub use primitive_calls::*; + +// ---- WASI calls (wasm32-unknown-unknown) ------------------------------------------------------- + +/// In a browser build SMLib is compiled against wasi-sdk's C library (build.rs), which calls a few +/// WASI functions. The page has no WASI host, so they are defined here, where wasm-ld finds them +/// before it would leave them as imports. There is no file system or environment: those calls fail +/// with WASI's own error codes. The clocks are the page's (the C API times every call). What +/// C writes to stdout or stderr goes to the `log` crate (target `smlib`). +#[cfg(all(feature = "native", target_arch = "wasm32", target_os = "unknown"))] +mod wasi { + const SUCCESS: i32 = 0; + const BADF: i32 = 8; + const INVAL: i32 = 28; + const NOSYS: i32 = 52; + const NOTCAPABLE: i32 = 76; + + /// One `__wasi_ciovec_t`: a buffer and its length. + #[repr(C)] + struct Ciovec { + buf: *const u8, + len: usize, + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_write(fd: i32, iovs: *const Ciovec, n: usize, written: *mut usize) -> i32 { + if !(1..=2).contains(&fd) { + return BADF; + } + let mut text = Vec::new(); + for i in 0..n { + // libc passes `n` valid iovecs, each a valid buffer, for the call's duration. + let v = unsafe { &*iovs.add(i) }; + if !v.buf.is_null() { + text.extend_from_slice(unsafe { std::slice::from_raw_parts(v.buf, v.len) }); + } + } + for line in String::from_utf8_lossy(&text).lines().filter(|l| !l.trim().is_empty()) { + log::debug!(target: "smlib", "{line}"); + } + if !written.is_null() { + unsafe { *written = text.len() }; + } + SUCCESS + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_environ_sizes_get(count: *mut usize, size: *mut usize) -> i32 { + if !count.is_null() && !size.is_null() { + unsafe { + *count = 0; + *size = 0; + } + } + SUCCESS + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_environ_get(_: *mut *mut u8, _: *mut u8) -> i32 { + SUCCESS + } + + /// Clock 0 is the wall clock; the others (monotonic, process and thread time) all count from + /// the first call, through the page's monotonic clock. + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_clock_time_get(id: i32, _: i64, time: *mut u64) -> i32 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let d = match id { + 0 => match web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH) { + Ok(d) => d, + Err(_) => return NOSYS, + }, + 1..=3 => START.get_or_init(web_time::Instant::now).elapsed(), + _ => return INVAL, + }; + if time.is_null() { + return INVAL; + } + unsafe { *time = u64::try_from(d.as_nanos()).unwrap_or(u64::MAX) }; + SUCCESS + } + + /// No preopened directories: libc stops looking at the first descriptor that is not one. + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_prestat_get(_: i32, _: *mut u8) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_prestat_dir_name(_: i32, _: *mut u8, _: usize) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_fdstat_get(_: i32, _: *mut u8) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_fdstat_set_flags(_: i32, _: i32) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_close(_: i32) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_read(_: i32, _: *const Ciovec, _: usize, _: *mut usize) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_seek(_: i32, _: i64, _: i32, _: *mut u64) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_fd_renumber(_: i32, _: i32) -> i32 { + BADF + } + + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_path_open( + _: i32, + _: i32, + _: *const u8, + _: usize, + _: i32, + _: i64, + _: i64, + _: i32, + _: *mut i32, + ) -> i32 { + NOTCAPABLE + } + + /// C's `exit` and `abort`: the C API catches everything, so this is a kernel defect; stop the + /// module as a native build would stop the process. + #[unsafe(no_mangle)] + extern "C" fn __imported_wasi_snapshot_preview1_proc_exit(_: i32) -> ! { + std::arch::wasm32::unreachable() + } +} diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs index dbe331c9a..54742054c 100644 --- a/crates/smlib/src/ops.rs +++ b/crates/smlib/src/ops.rs @@ -155,7 +155,15 @@ impl Brep { /// `setbacks[j]` along each of its edges from the vertex (one distance per corner, as SMLib /// keeps it). A corner SMLib builds no setback on (some edge there not blended, a chamfer) is /// [`Error::Unsupported`]; a setback as long as an edge there, [`Error::NoRoom`]. - pub fn blend_setback(&self, kind: Blend, edges: &[[f64; 3]], sizes: &[f64], corners: &[[f64; 3]], setbacks: &[f64], tolerance: f64) -> Result { + pub fn blend_setback( + &self, + kind: Blend, + edges: &[[f64; 3]], + sizes: &[f64], + corners: &[[f64; 3]], + setbacks: &[f64], + tolerance: f64, + ) -> Result { init()?; if edges.len() > MAX_POINTS || edges.is_empty() diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rs index cd983b4df..cfbec97fb 100644 --- a/crates/step/src/topology.rs +++ b/crates/step/src/topology.rs @@ -1029,7 +1029,8 @@ impl<'b, 'a> Builder<'b, 'a> { } _ => None, }; - let pcs = pcurve::pcurves_within(&surface, &uses_of(&self.edges, &edge_loops, made.as_ref())?, tol, box_on_form).map_err(|e| e.to_string())?; + let pcs = + pcurve::pcurves_within(&surface, &uses_of(&self.edges, &edge_loops, made.as_ref())?, tol, box_on_form).map_err(|e| e.to_string())?; // Signed areas of the loops that close in (u, v). let periods = natural_periods(&surface); // Each use starts near where the one before it ends, along a bounded direction that diff --git a/crates/step/src/topology/seams.rs b/crates/step/src/topology/seams.rs index 710f5fb7d..ef2afae54 100644 --- a/crates/step/src/topology/seams.rs +++ b/crates/step/src/topology/seams.rs @@ -236,9 +236,10 @@ impl Builder<'_, '_> { /// A vertex of the loop is on one of the axis's poles (within its tolerance). fn through_pole(&self, es: &[(u32, bool)], ax: &Axis) -> bool { es.iter().any(|&u| { - self.start(u).ok().and_then(|v| self.vertices.get(v as usize)).is_some_and(|x| { - ax.poles.iter().flatten().any(|p| Vec3::from(x.point).dist(*p) <= self.tol.max(x.tolerance)) - }) + self.start(u) + .ok() + .and_then(|v| self.vertices.get(v as usize)) + .is_some_and(|x| ax.poles.iter().flatten().any(|p| Vec3::from(x.point).dist(*p) <= self.tol.max(x.tolerance))) }) } diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 52a352303..0a57d811d 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -36,7 +36,9 @@ pub(crate) fn reveal_body(app: &mut SolveApp, body: &str) { app.tree.reveal_feature = None; app.tree.reveal = Some(body.to_string()); let state = app.session.model.state(); - let Some(source) = crate::open_meshing::session_world(&app.session).body(body).map(|selected| selected.definition_name().to_string()) else { return }; + let Some(source) = crate::open_meshing::session_world(&app.session).body(body).map(|selected| selected.definition_name().to_string()) else { + return; + }; let Some(component) = state.body(&source).map(|definition| definition.component) else { return }; // Every component's first placement keeps the definition's name, so the owner must match too. let Some((_, path, _)) = app diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 353d6f948..062deece5 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1202,7 +1202,8 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } "ui.isolate" => { // The picked bodies stay (shown first if they were hidden), everything else goes. - let others: Vec = crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).filter(|b| !bodies.contains(b)).collect(); + let others: Vec = + crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).filter(|b| !bodies.contains(b)).collect(); if !bodies.is_empty() { let _ = app.run("browser.visibility", json!({ "items": bodies, "visible": true })); } diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index ae2840d83..7f2716c1b 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -714,7 +714,10 @@ fn face_editor_refills_named_faces_after_sketch_resize() { fn draft_uses_the_picked_solid_beside_a_hidden_overlapping_mesh() { use solidcraft_engine::doc::{Document, MeshData, naming}; - let mesh = solidcraft_engine::kernel::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 10.0)).unwrap().mesh(&solidcraft_engine::kernel::MeshTolerance::chord(0.01)).unwrap(); + let mesh = solidcraft_engine::kernel::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 10.0)) + .unwrap() + .mesh(&solidcraft_engine::kernel::MeshTolerance::chord(0.01)) + .unwrap(); let mut doc = Document::default(); doc.add_feature( FeatureKind::MeshImport { diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs index f438dc9e0..ad5d749db 100644 --- a/crates/ui-egui/src/dimension_create_ui_tests.rs +++ b/crates/ui-egui/src/dimension_create_ui_tests.rs @@ -1160,7 +1160,8 @@ fn model_text(h: &Harness, param: &str) -> [f32; 2] { let sk = h .app .session - .world_state().unwrap() + .world_state() + .unwrap() .sketch(h.app.session.doc.features.iter().find(|f| f.name.starts_with("Sketch")).unwrap().id) .unwrap() .sketch diff --git a/crates/ui-egui/src/hole_refs.rs b/crates/ui-egui/src/hole_refs.rs index d80a6a1be..5a9d3a8a2 100644 --- a/crates/ui-egui/src/hole_refs.rs +++ b/crates/ui-egui/src/hole_refs.rs @@ -147,7 +147,9 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { Some(sn) if sn.distance != refs.distance => { let values: Option> = picked.iter().map(|k| refs.distance.get(*k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); - if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&crate::open_meshing::session_world(s), f, *c)) { + if let Some(c) = + values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&crate::open_meshing::session_world(s), f, *c)) + { to = c; } } diff --git a/crates/ui-egui/src/sketch_dims_tests.rs b/crates/ui-egui/src/sketch_dims_tests.rs index 06fe19923..b1478a01d 100644 --- a/crates/ui-egui/src/sketch_dims_tests.rs +++ b/crates/ui-egui/src/sketch_dims_tests.rs @@ -141,7 +141,8 @@ fn clicking_a_parameter_suggestion_fills_the_length_box() { h.frames(1); assert_focus(&h, 0); assert_eq!(h.app.tool.as_ref().unwrap().dims[0].value, "width"); - let sketch = |h: &Harness| crate::open_meshing::session_world(&h.app.session).sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.len(); + let sketch = + |h: &Harness| crate::open_meshing::session_world(&h.app.session).sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.len(); assert_eq!(sketch(&h), 0, "the click on the list placed no point"); h.step(&json!({"key": "Enter"})).unwrap(); let state = crate::open_meshing::session_world(&h.app.session); diff --git a/scripts/fetch-smlib.sh b/scripts/fetch-smlib.sh index d73143db0..8fb37dcfc 100755 --- a/scripts/fetch-smlib.sh +++ b/scripts/fetch-smlib.sh @@ -1,20 +1,95 @@ #!/usr/bin/env bash -# Fetches the SMLib sources solidcraft-smlib builds (feature `native`): tangency-labs/smlib at -# the commit in crates/smlib/SMLIB_REV, only the parts the build reads (source/SMLib, -# source/SM_API, capi), into target/smlib-. OpenCASCADE is not part of the fork. +# Fetches SMLib for solidcraft-smlib (feature `native`), at the commit in crates/smlib/SMLIB_REV. +# +# scripts/fetch-smlib.sh [TARGET...] the prebuilt C API library for each Rust target (default: +# the host's), checked against crates/smlib/SMLIB_PREBUILT, +# into target/smlib--prebuilt/; the sources +# for a target with no prebuilt library +# scripts/fetch-smlib.sh --source the sources (source/SMLib, source/SM_API, capi), into +# target/smlib- or SOLIDCRAFT_SMLIB_DIR, to compile +# scripts/fetch-smlib.sh --pin writes SMLIB_PREBUILT from the release of SMLIB_REV +# +# The libraries are the release prebuilt- of tangency-labs/smlib (its prebuilt.yml). +# OpenCASCADE is not part of the fork. set -euo pipefail root="$(cd "$(dirname "$0")/.." && pwd)" rev="$(tr -d '[:space:]' < "$root/crates/smlib/SMLIB_REV")" -dest="${SOLIDCRAFT_SMLIB_DIR:-$root/target/smlib-${rev:0:12}}" -if [ -f "$dest/capi/include/smlib.h" ] && [ "$(git -C "$dest" rev-parse HEAD 2>/dev/null)" = "$rev" ]; then - echo "SMLib $rev already at $dest" - exit 0 -fi -rm -rf "$dest" -mkdir -p "$dest" -git -C "$dest" init -q -git -C "$dest" remote add origin https://github.com/tangency-labs/smlib.git -git -C "$dest" sparse-checkout set --no-cone /source/SMLib/ /source/SM_API/ /capi/ /LICENSE -git -C "$dest" fetch -q --depth 1 --filter=blob:none origin "$rev" -git -C "$dest" checkout -q FETCH_HEAD -echo "SMLib $rev at $dest" +pins="$root/crates/smlib/SMLIB_PREBUILT" +release="https://github.com/tangency-labs/smlib/releases/download/prebuilt-$rev" + +sha256() { + if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi +} + +fetch_source() { + local dest="${SOLIDCRAFT_SMLIB_DIR:-$root/target/smlib-${rev:0:12}}" + if [ -f "$dest/capi/include/smlib.h" ] && [ "$(git -C "$dest" rev-parse HEAD 2>/dev/null)" = "$rev" ]; then + echo "SMLib sources $rev already at $dest" + return + fi + rm -rf "$dest" + mkdir -p "$dest" + git -C "$dest" init -q + git -C "$dest" remote add origin https://github.com/tangency-labs/smlib.git + git -C "$dest" sparse-checkout set --no-cone /source/SMLib/ /source/SM_API/ /capi/ /LICENSE + git -C "$dest" fetch -q --depth 1 --filter=blob:none origin "$rev" + git -C "$dest" checkout -q FETCH_HEAD + echo "SMLib sources $rev at $dest" +} + +fetch_prebuilt() { + local target="$1" want dest tmp + want="$(awk -v t="$target" '$1 == t { print $2 }' "$pins")" + if [ -z "$want" ]; then + echo "no prebuilt SMLib for $target: fetching the sources to compile" + fetch_source + return + fi + dest="$root/target/smlib-${rev:0:12}-prebuilt/$target" + if [ "$(cat "$dest/.sha256" 2>/dev/null)" = "$want" ]; then + echo "SMLib $rev for $target already at $dest" + return + fi + tmp="$(mktemp -d)" + trap 'rm -rf "$tmp"' RETURN + curl -fsSL --retry 3 -o "$tmp/smlib.tar.gz" "$release/smlib-$target.tar.gz" + if [ "$(sha256 "$tmp/smlib.tar.gz")" != "$want" ]; then + echo "smlib-$target.tar.gz does not match its SHA-256 in crates/smlib/SMLIB_PREBUILT" >&2 + exit 1 + fi + tar -xzf "$tmp/smlib.tar.gz" -C "$tmp" + if [ "$(tr -d '[:space:]' < "$tmp/smlib-$target/REV")" != "$rev" ]; then + echo "smlib-$target.tar.gz was built from another commit than SMLIB_REV" >&2 + exit 1 + fi + rm -rf "$dest" + mkdir -p "$(dirname "$dest")" + mv "$tmp/smlib-$target" "$dest" + echo "$want" > "$dest/.sha256" + echo "SMLib $rev for $target at $dest" +} + +case "${1:-}" in + --source) + fetch_source + ;; + --pin) + tmp="$(mktemp -d)" + trap 'rm -rf "$tmp"' EXIT + curl -fsSL --retry 3 -o "$tmp/SHA256SUMS" "$release/SHA256SUMS" + { + echo "# Rust target, SHA-256 of smlib-.tar.gz in the release prebuilt- of" + echo "# tangency-labs/smlib. Written by scripts/fetch-smlib.sh --pin; never edited by hand." + sed -E 's/^([0-9a-f]{64}) +smlib-(.*)\.tar\.gz$/\2 \1/' "$tmp/SHA256SUMS" | sort + } > "$pins" + echo "pinned $(grep -vc '^#' "$pins") prebuilt targets of $rev" + ;; + *) + if [ $# -eq 0 ]; then + set -- "$(rustc -vV | sed -n 's/^host: //p')" + fi + for target in "$@"; do + fetch_prebuilt "$target" + done + ;; +esac