diff --git a/apps/solidcraft-cli/src/kernel_cases.rs b/apps/solidcraft-cli/src/kernel_cases.rs index d07d8ca17..4cf618080 100644 --- a/apps/solidcraft-cli/src/kernel_cases.rs +++ b/apps/solidcraft-cli/src/kernel_cases.rs @@ -633,7 +633,7 @@ fn flat_pattern_checks(c: &mut Checks, want: &Value, results: &[Value], rel: f64 } } -fn check_case(dir: &str, dumps: Option<&std::path::Path>) -> Value { +fn check_case(dir: &str, dumps: Option<&std::path::Path>, validation: solidcraft_engine::kernel::Validation) -> 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")) { @@ -692,6 +692,7 @@ fn check_case(dir: &str, dumps: Option<&std::path::Path>) -> Value { } } let mut s = solidcraft_engine::Session::default(); + s.set_validation(validation); let clock = std::time::Instant::now(); let ran = s.run_script(&commands); // The commands' own time, without process start or grading: the ladder's timing golden. @@ -945,7 +946,14 @@ pub fn run(args: &[String]) -> Result<(), String> { 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 = dirs.iter().map(|d| check_case(d, dumps.as_deref())).collect(); + // `--validation=MODE`: the cases' features are checked under MODE (each_step, each_feature, + // off; default each_feature, the app's default). + let validation = match args.iter().find_map(|a| a.strip_prefix("--validation=")) { + Some(m) => solidcraft_engine::kernel::Validation::parse(m) + .ok_or_else(|| format!("kernel-cases: --validation= must be each_step, each_feature or off, not `{m}`"))?, + None => solidcraft_engine::kernel::Validation::default(), + }; + let results: Vec = dirs.iter().map(|d| check_case(d, dumps.as_deref(), validation)).collect(); if dumps.is_some() { solidcraft_engine::kernel::smlib_dump_dir(None).map_err(|e| format!("kernel-cases: --dumps: {e}"))?; } diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index d9cd5a7bb..190081347 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -1,7 +1,7 @@ //! SolidCraft headless command line. //! //! ```text -//! solidcraft-cli run [--in design|part.step|mesh.3mf] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors] +//! solidcraft-cli run [--in design|part.step|mesh.3mf] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors] [--validation MODE] //! solidcraft-cli eval [--in design.solidcraft|part.step] [--json-out FILE] (alias: inspect) measurements as JSON //! solidcraft-cli script [--out script.json] the design's history as a command script //! solidcraft-cli bench-open [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] loading timings as JSON lines @@ -15,7 +15,7 @@ //! solidcraft-cli commands the command registry as JSON //! solidcraft-cli recipe translate an oracle recipe to a script //! solidcraft-cli oracle ... replay recipes and compare with expected.json -//! solidcraft-cli kernel-cases [--json] [--dumps=DIR] ... the kernel regression rig (tests/kernel-cases) +//! solidcraft-cli kernel-cases [--json] [--dumps=DIR] [--validation=MODE] ... 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) @@ -59,7 +59,7 @@ struct Command { } /// `run`'s lines in the usage. -const USAGE_RUN: &str = " solidcraft-cli run [--in design.solidcraft|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--profile-out trace.json] [--json-out FILE] [--allow-errors]\n solidcraft-cli run --in [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n (--profile also records where the time goes, SMLib's calls, kernel operations, features, commands and import stages,\n and prints the table to stderr: count, total, self time and longest per span; --profile-out FILE writes the spans\n as a Chrome trace for chrome://tracing or ui.perfetto.dev; SOLIDCRAFT_PROFILE=1 does the same for any command)\n"; +const USAGE_RUN: &str = " solidcraft-cli run [--in design.solidcraft|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--profile-out trace.json] [--json-out FILE] [--allow-errors] [--validation each_step|each_feature|off]\n solidcraft-cli run --in [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--validation: when SMLib's full check runs on the features computed (diagnostics.validation), default each_feature)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n (--profile also records where the time goes, SMLib's calls, kernel operations, features, commands and import stages,\n and prints the table to stderr: count, total, self time and longest per span; --profile-out FILE writes the spans\n as a Chrome trace for chrome://tracing or ui.perfetto.dev; SOLIDCRAFT_PROFILE=1 does the same for any command)\n"; /// `eval`'s lines in the usage. const USAGE_EVAL: &str = " solidcraft-cli eval [--in design.solidcraft|part.step] [--json-out FILE] [--profile] [--profile-out trace.json] (alias: inspect)\n solidcraft-cli eval --in [--json-out FILE]\n (with both inputs, runs the positional script on --in before measuring; does not automatically save the modified design)\n (--json-out FILE writes the JSON that run (with --results, else the measurement) and eval print to FILE instead of stdout,\n as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark)\n (--profile and --profile-out as for run)\n"; /// `script`'s lines in the usage. @@ -83,7 +83,7 @@ const USAGE_RECIPE: &str = " solidcraft-cli recipe \n"; /// `oracle`'s lines in the usage. const USAGE_ORACLE: &str = " solidcraft-cli oracle ... [--json]\n"; /// `kernel-cases`'s lines in the usage. -const USAGE_KERNEL_CASES: &str = " solidcraft-cli kernel-cases ... [--json] [--dumps=DIR]\n (the kernel regression rig, tests/kernel-cases, on SMLib; --dumps: each case's\n failing SMLib calls leave their inputs for replay in DIR/-)\n"; +const USAGE_KERNEL_CASES: &str = " solidcraft-cli kernel-cases ... [--json] [--dumps=DIR] [--validation=each_step|each_feature|off]\n (the kernel regression rig, tests/kernel-cases, on SMLib; --dumps: each case's\n failing SMLib calls leave their inputs for replay in DIR/-; --validation: when SMLib's\n full check runs (diagnostics.validation), default each_feature)\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"; @@ -278,8 +278,15 @@ pub fn load(path: &str) -> Result { /// `load`, with scripts and recipes run at the parameter-check level `check`, which the /// session keeps. fn load_checked(path: &str, check: solidcraft_engine::schema::ParamCheck) -> Result { + load_with(path, check, solidcraft_engine::kernel::Validation::default()) +} + +/// `load_checked`, the features computed under `validation` (`diagnostics.validation`), which +/// the session keeps. +fn load_with(path: &str, check: solidcraft_engine::schema::ParamCheck, validation: solidcraft_engine::kernel::Validation) -> Result { let mut s = Session::default(); s.param_check = check; + s.set_validation(validation); if solidcraft_engine::io::is_step_path(path) || solidcraft_engine::io::is_mesh_path(path) { s.execute("doc.open", &json!({"path": path})).map_err(|e| e.to_string())?; return Ok(s); @@ -287,7 +294,7 @@ fn load_checked(path: &str, check: solidcraft_engine::schema::ParamCheck) -> Res let bytes = solidcraft_engine::io::vfs::read(path, solidcraft_engine::io::MAX_DESIGN_BYTES).map_err(|e| format!("{path}: {e}"))?; if solidcraft_engine::io::is_design_container(&bytes) { let doc = solidcraft_engine::io::read_design(&bytes).map_err(|e| format!("{path}: {e}"))?; - let mut session = Session::opened_at(doc, None, Some(path)); + let mut session = Session::opened_at_validating(doc, None, Some(path), validation); session.param_check = check; return Ok(session); } @@ -377,10 +384,11 @@ fn cmd_run(args: &[String]) -> Result<(), String> { known_args( "run", args, - &["--in", "--out", "--save", "--json-out", "--profile-out"], + &["--in", "--out", "--save", "--json-out", "--profile-out", "--validation"], &["--quiet", "--results", "--timings", "--profile", "--allow-errors"], true, )?; + let validation = validation_flag("run", args)?; let base = flag(args, "--in"); let path = positional(args); if path.is_none() && base.is_none() { @@ -395,8 +403,12 @@ fn cmd_run(args: &[String]) -> Result<(), String> { let (mut s, results) = if want_results || timings { // Collect every command's result or time (scripts only), then process requested files too. let mut s = match base { - Some(b) => load(b)?, - None => Session::default(), + Some(b) => load_with(b, solidcraft_engine::schema::ParamCheck::Off, validation)?, + None => { + let mut s = Session::default(); + s.set_validation(validation); + s + } }; let needs = if want_results { "--results needs a script" } else { "--timings needs a script" }; let v = read_json(path.ok_or(needs)?)?; @@ -411,7 +423,7 @@ fn cmd_run(args: &[String]) -> Result<(), String> { }; (s, Some(out)) } else { - (open(base, path)?, None) + (open_validating(base, path, validation)?, None) }; // A feature that fails leaves the bodies as they were before it (a parameter change can // break a feature without failing the command that made it): writing them would hand out @@ -438,6 +450,12 @@ fn cmd_run(args: &[String]) -> Result<(), String> { /// The session `run`, `eval` and `snapshot` start from: `--in` (a design or STEP file) with the /// positional script run on top of it, or either one alone. fn open(base: Option<&str>, path: Option<&String>) -> Result { + open_validating(base, path, solidcraft_engine::kernel::Validation::default()) +} + +/// [`open`], the features computed under `validation`. +fn open_validating(base: Option<&str>, path: Option<&String>, validation: solidcraft_engine::kernel::Validation) -> Result { + let load = |p: &str| load_with(p, solidcraft_engine::schema::ParamCheck::Off, validation); match (base, path) { (Some(b), Some(p)) => { let mut s = load(b)?; @@ -450,6 +468,15 @@ fn open(base: Option<&str>, path: Option<&String>) -> Result { } } +/// `--validation MODE` (`diagnostics.validation`): the default, each_feature, when not given. +fn validation_flag(cmd: &str, args: &[String]) -> Result { + match flag(args, "--validation") { + Some(m) => solidcraft_engine::kernel::Validation::parse(m) + .ok_or_else(|| format!("{cmd}: --validation must be each_step, each_feature or off, not `{m}`")), + None => Ok(solidcraft_engine::kernel::Validation::default()), + } +} + /// Refuses an option `cmd` doesn't take, and one missing its value: a typo, or another /// command's option, would otherwise be ignored without a word. `positionals` says whether the /// command takes a word of its own (a file, a seed): `fuzz` takes none, and would start a run. diff --git a/apps/solidcraft-cli/tests/corpus/README.md b/apps/solidcraft-cli/tests/corpus/README.md index d9266d8b9..31d3f0582 100644 --- a/apps/solidcraft-cli/tests/corpus/README.md +++ b/apps/solidcraft-cli/tests/corpus/README.md @@ -1,10 +1,12 @@ # Design file corpus Designs saved by older SolidCraft builds. `tests/design_corpus.rs` opens each one with the -current build and checks that it evaluates as it did when saved (the `.expected.json` next to -it is `solidcraft-cli eval` of that file by the build that saved it: bodies, volumes, areas, -world bounding boxes), that it is upgraded to the current file format, and that damaged and -hostile variants of it never panic. +current build and checks that it is upgraded to the current file format, that it evaluates +(a feature may fail only by asking for a reference it lost to be picked again; what it rebuilds +to is today's), and that damaged and hostile variants of it never panic. The `.expected.json` +next to each is `solidcraft-cli eval` of that file by the build that saved it (bodies, volumes, +areas, world bounding boxes), kept as a record of what that build made; no test compares with +it. | File | Saved by | Era | |---|---|---| diff --git a/apps/solidcraft-cli/tests/design_corpus.rs b/apps/solidcraft-cli/tests/design_corpus.rs index 9eb0cfdcb..957eef5d6 100644 --- a/apps/solidcraft-cli/tests/design_corpus.rs +++ b/apps/solidcraft-cli/tests/design_corpus.rs @@ -1,5 +1,6 @@ -//! Designs saved by older SolidCraft builds (tests/corpus, see its README) open and evaluate as -//! they did when they were saved; damaged and hostile design files never panic. +//! Designs saved by older SolidCraft builds (tests/corpus, see its README) open, are upgraded to +//! the current format and evaluate (what they rebuild to today is today's, not what the build +//! that saved them made); damaged and hostile design files never panic. use std::path::{Path, PathBuf}; @@ -21,67 +22,24 @@ fn open(path: &Path) -> Session { s } -/// Differences that are deliberate behaviour changes made before the file format had versions -/// (no migration can tell those files apart): (file, check, why). -const KNOWN: [(&str, &str, &str); 2] = [ - ( - "m0-revolve-primitives", - "Body1 bbox", - "partial revolves turn toward the sketch normal since ac43365 (as most parametric CAD tools do); M0 turned them the other way", - ), - ("components-arm", "body_count", "Measure counted only the root component's bodies then; it measures every placed body now"), -]; - -fn known(file: &str, check: &str) -> bool { - KNOWN.iter().any(|(f, c, _)| *f == file && *c == check) -} - -/// Volumes and areas then came from coarser tessellation (and curved booleans and fillets have -/// become exact since): the same part within this relative tolerance (the oracle's). -const REL: f64 = 1e-3; - -fn close(a: f64, b: f64, rel: f64) -> bool { - (a - b).abs() <= rel * b.abs().max(1.0) -} - +/// Every corpus design opens, is upgraded to the current format, evaluates, and saves and reads +/// back the same. A feature may fail only by asking for a reference it lost to be picked again +/// (a name saved before format 14 finds nothing today). #[test] -fn old_designs_open_and_evaluate_as_saved() { +fn old_designs_open_upgrade_and_evaluate() { let mut problems = Vec::new(); for p in corpus() { let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); - let want: Value = serde_json::from_slice(&std::fs::read(p.with_extension("expected.json")).unwrap()).unwrap(); let mut s = open(&p); for r in &s.model.results { - if let Some(e) = &r.error { + if let Some(e) = r.error.as_deref().filter(|e| solidcraft_engine::doc::reselect_parts(e).is_none()) { problems.push(format!("{name}: feature {}: {e}", r.id)); } } assert_eq!(s.doc.format, solidcraft_engine::doc::format::format_string(solidcraft_engine::doc::format::FORMAT), "{name}: upgraded"); let got = s.execute("inspect.measure", &json!({})).unwrap(); - if got["body_count"] != want["body_count"] && !known(&name, "body_count") { - problems.push(format!("{name}: {} bodies, saved with {}", got["body_count"], want["body_count"])); - } - for w in want["bodies"].as_array().into_iter().flatten() { - let bname = w["name"].as_str().unwrap_or_default(); - let Some(g) = got["bodies"].as_array().into_iter().flatten().find(|g| g["name"] == w["name"]) else { - problems.push(format!("{name}: body {bname} missing")); - continue; - }; - for k in ["volume_mm3", "area_mm2"] { - let (a, b) = (g[k].as_f64().unwrap_or(f64::NAN), w[k].as_f64().unwrap_or(f64::NAN)); - if !close(a, b, REL) { - problems.push(format!("{name}: {bname} {k} {a} (saved {b})")); - } - } - if known(&name, &format!("{bname} bbox")) { - continue; - } - for (end, i) in [("min", 0), ("min", 1), ("min", 2), ("max", 0), ("max", 1), ("max", 2)] { - let (a, b) = (g["bbox"][end][i].as_f64().unwrap_or(f64::NAN), w["bbox"][end][i].as_f64().unwrap_or(f64::NAN)); - if (a - b).abs() > 1e-3 * b.abs().max(1.0) { - problems.push(format!("{name}: {bname} bbox {end}[{i}] {a} (saved {b})")); - } - } + if got["body_count"].as_u64().unwrap_or(0) == 0 { + problems.push(format!("{name}: no bodies")); } // Saved again, it reads back the same. let again = solidcraft_engine::doc::Document::from_json(&s.doc.to_json()).unwrap(); @@ -94,40 +52,48 @@ fn old_designs_open_and_evaluate_as_saved() { } /// Names saved before format 14 were worked out from geometry, pieces of a split face numbered by -/// where their centres lay (`F2:top#2`). They keep naming the faces they named: marked as such, -/// they are found as the build that saved them found them, without new notes. +/// where their centres lay (`F2:top#2`). They open marked as such and find no face or edge today: +/// each feature holding one fails, asking for its reference to be picked again, and the rest of +/// the design builds. #[test] -fn names_saved_before_exact_history_find_the_faces_they_named() { +fn names_saved_before_exact_history_ask_for_their_faces_again() { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/naming-split-pieces.solidcraft"); let s = open(&path); let feature = |name: &str| s.doc.features.iter().find(|f| f.name == name).unwrap_or_else(|| panic!("{name}")); assert_eq!(feature("Round").edge_names, vec!["?F2:side:l2|F2:top#2".to_string()]); assert_eq!(feature("Bevel").edge_names, vec!["?F2:side:l4|F2:top#1".to_string()]); assert_eq!(feature("Raise").face_names, vec!["?F2:top#1".to_string()]); - for r in &s.model.results { - assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning); + let asked = |name: &str| { + let r = s.model.result(feature(name).id).unwrap_or_else(|| panic!("{name}")); + r.error.as_deref().and_then(solidcraft_engine::doc::reselect_parts).map(|(f, reference)| (f.to_string(), reference.to_string())) + }; + assert_eq!(asked("Round"), Some(("Round".into(), "?F2:side:l2|F2:top#2".into()))); + assert_eq!(asked("Bevel"), Some(("Bevel".into(), "?F2:side:l4|F2:top#1".into()))); + assert_eq!(asked("Raise"), Some(("Raise".into(), "?F2:top#1".into()))); + for r in s.model.results.iter().filter(|r| !["Round", "Bevel", "Raise"].contains(&r.name.as_str())) { + assert!(r.error.is_none(), "{}: {:?}", r.name, r.error); } - // The raised piece is the left one, as saved (the stored point is on it). - let state = s.model.state(); - let solid = |p: [f64; 3]| state.bodies.iter().any(|b| b.body.contains(solidcraft_engine::geom::Vec3::new(p[0], p[1], p[2]))); - assert!(solid([7.0, 15.0, 11.0]) && !solid([32.0, 15.0, 11.0])); + assert!(!s.model.state().bodies.is_empty()); } -/// Body names saved before format 14 name the pieces of a split body in the kernel's shell order. -/// The features after the split that refer to a piece by its body name still find that piece: -/// the far one stays `Body1` (chamfered), the near one `Body1 (1)` (filleted, coloured). +/// Body names saved before format 14 named the pieces of a split body in the kernel's shell +/// order: such a design opens with every feature marked `shell_piece_order` and evaluates, each +/// body name it stores naming a piece. (Which piece takes which name is not promised to be as it +/// was saved.) Its fillet and chamfer hold edge names saved then, which find nothing today: they +/// ask for their edges to be picked again. #[test] -fn body_names_saved_before_exact_history_keep_their_pieces() { +fn body_names_saved_before_exact_history_open_marked_and_evaluate() { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/split-body-pieces.solidcraft"); let s = open(&path); assert!(s.doc.features.iter().all(|f| f.shell_piece_order), "every saved feature keeps the shell order"); for r in &s.model.results { - assert!(r.error.is_none() && r.warning.is_none(), "{}: {:?} {:?}", r.name, r.error, r.warning); + let asked = r.error.as_deref().and_then(solidcraft_engine::doc::reselect_parts); + assert!(r.error.is_none() || asked.is_some_and(|(_, reference)| reference.starts_with('?')), "{}: {:?}", r.name, r.error); } let state = s.model.state(); - let piece = |name: &str| state.bodies.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("{name}")); - let solid = |name: &str, p: [f64; 3]| piece(name).body.contains(solidcraft_engine::geom::Vec3::new(p[0], p[1], p[2])); - assert!(solid("Body1", [20.0, 24.0, 5.0]) && solid("Body1 (1)", [20.0, 6.0, 5.0])); + for name in ["Body1", "Body1 (1)"] { + assert!(state.bodies.iter().any(|b| b.name == name), "{name}"); + } assert!(s.doc.appearances.bodies.contains_key("Body1 (1)")); } @@ -173,6 +139,7 @@ fn flat_face_attachments() -> Vec<(String, String, usize, Option<(u32, bool)>, O for p in corpus() { let name = p.file_stem().unwrap_or_default().to_string_lossy().to_string(); let mut s = open(&p); + let failed_on_open: Vec = s.model.results.iter().filter(|r| r.error.is_some()).map(|r| r.id).collect(); let state = s.model.state(); let placed = s.placed_document(); let mut picks = Vec::new(); @@ -224,7 +191,8 @@ fn flat_face_attachments() -> Vec<(String, String, usize, Option<(u32, bool)>, O let known = known_without_attachment(&name, &body, normal, distance); out.push((name.clone(), body, index, known, problem)); } - assert!(s.model.results.iter().all(|r| r.error.is_none()), "{name}: left with errors after undo"); + let failed: Vec = s.model.results.iter().filter(|r| r.error.is_some()).map(|r| r.id).collect(); + assert_eq!(failed, failed_on_open, "{name}: undo leaves the features that failed on opening, and only those, failed"); } out } diff --git a/apps/solidcraft-cli/tests/model_cache.rs b/apps/solidcraft-cli/tests/model_cache.rs index c08d5948b..c53a07e8b 100644 --- a/apps/solidcraft-cli/tests/model_cache.rs +++ b/apps/solidcraft-cli/tests/model_cache.rs @@ -288,3 +288,27 @@ fn undoing_an_edit_after_opening_reuses_the_saved_results() { let _ = std::fs::remove_file(&path); let _ = std::fs::remove_file(format!("{}.bak", path.display())); } + +/// A saved model holds the results of the body check mode it was evaluated under: opened under +/// the same mode it is taken as it is, under another the design is evaluated again. +#[test] +fn a_model_saved_under_another_check_mode_is_evaluated_again() { + let plate = solidcraft_engine::sample::samples().into_iter().find(|s| s.name == "Sample Plate").unwrap(); + let mut built = Session::default(); + for c in (plate.script)()["commands"].as_array().unwrap() { + built.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap(); + } + let path = temp("mode"); + built.execute("file.save_as", &json!({"path": path.to_string_lossy()})).unwrap(); + let same = open(&path); + assert_eq!(same.model.validation(), built.model.validation()); + assert_eq!(same.model.recomputed, 0, "taken from the file"); + let mut other = Session::default(); + other.set_validation(solidcraft_engine::kernel::Validation::EachStep); + assert_ne!(other.validation(), built.model.validation()); + other.execute("doc.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(other.validation(), solidcraft_engine::kernel::Validation::EachStep); + assert!(other.model.recomputed > 0, "evaluated again under its own mode"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.bak", path.display())); +} diff --git a/apps/solidcraft-cli/tests/naming_corpus.rs b/apps/solidcraft-cli/tests/naming_corpus.rs index 48e75db6b..a78e00508 100644 --- a/apps/solidcraft-cli/tests/naming_corpus.rs +++ b/apps/solidcraft-cli/tests/naming_corpus.rs @@ -1,10 +1,11 @@ -//! Every design of the corpus loads, every name it stores still finds a face or an edge, and -//! two builds of it name its faces and edges alike. The stored names are the fillet and chamfer -//! edges, the faces a feature picks, the face a sketch sits on and the sheet metal edges; one -//! that finds nothing (`gone`, a sketch's face `lost`) fails the test, and so does a design that -//! no longer loads. A build's names are each face's and edge's name with where it is (its area -//! and centre, its length and middle); the second build must give the same, and its stored -//! names must find the same faces and edges. +//! Every design of the corpus loads, two builds of it name its faces and edges alike, and a +//! name it stores that no longer finds its face or edge fails its feature. The stored names are +//! the fillet and chamfer edges, the faces a feature picks, the face a sketch sits on and the +//! sheet metal edges; one that finds nothing (`gone`, a sketch's face `lost`) must leave its +//! feature failed (it asks for the reference to be picked again, never takes another face or +//! edge), and a design that no longer loads fails the test. A build's names are each face's and +//! edge's name with where it is (its area and centre, its length and middle); the second build +//! must give the same, and its stored names must find the same faces and edges. //! //! Face and edge indices are left out: they are the kernel's order, which a rebuild need not //! keep (a fillet's or a boolean's faces come out in another order from one build to the next). @@ -109,7 +110,7 @@ fn load(source: &Source) -> Result { } /// What decides a name beyond its text: `[geometric]` when it was worked out from geometry, not -/// exact history; how a stored name was found. +/// exact history. fn flags(list: &[(bool, &str)]) -> String { let set: Vec<&str> = list.iter().filter(|(on, _)| *on).map(|(_, f)| *f).collect(); if set.is_empty() { String::new() } else { format!(" [{}]", set.join(", ")) } @@ -175,14 +176,7 @@ fn record_refs(out: &mut Vec<(String, bool)>, s: &Session, f: &Feature) { ("not checked (a cylindrical emboss finds its face on its own body)".to_string(), true) } else { match naming::locate_face_on_body(&fst, f.kind.face_body(), n, p) { - Some(hit) => ( - format!( - "{}{}", - face_label(&fst, hit.body, hit.face), - flags(&[(hit.split, "split"), (hit.merged, "merged"), (!hit.verified, "geometric"), (hit.legacy, "legacy")]) - ), - true, - ), + Some(hit) => (format!("{}{}", face_label(&fst, hit.body, hit.face), flags(&[(!hit.verified, "geometric")])), true), None => ("gone".into(), false), } }; @@ -198,7 +192,7 @@ fn record_refs(out: &mut Vec<(String, bool)>, s: &Session, f: &Feature) { "{} edge {}{}", b.name, naming::edge_names(b).get(hit.edge).map(String::as_str).unwrap_or("?"), - flags(&[(hit.split, "split"), (!hit.verified, "geometric"), (hit.legacy, "legacy")]) + flags(&[(!hit.verified, "geometric")]) ), true, ), @@ -253,7 +247,7 @@ fn record_refs(out: &mut Vec<(String, bool)>, s: &Session, f: &Feature) { } } // The face a sketch sits on. - if let FeatureKind::Sketch { plane: PlaneRef::Face { name, anchor, .. }, .. } = &f.kind { + if let FeatureKind::Sketch { plane: PlaneRef::Face { name, anchor, at, .. }, .. } = &f.kind { let mut ok = true; let status = match doc.sketch_face_attachment(f.id, &s.model) { FaceAttachmentStatus::Healthy { target, .. } => { @@ -281,26 +275,20 @@ fn record_refs(out: &mut Vec<(String, bool)>, s: &Session, f: &Feature) { ok = false; format!("lost: {message}") } - FaceAttachmentStatus::Legacy { .. } => { - // Found by its name among the faces facing the same way, nearest the pick. - let fst = solidcraft_engine::doc::state_in_frame(doc, &before, f.component).unwrap(); - let mut list: Vec = match name { - Some(n) => fst - .bodies - .iter() - .filter(|b| !b.body.is_mesh()) - .flat_map(|b| { - let names = naming::face_names(b); - naming::faces_with_stem(b, n) - .into_iter() - .map(move |i| format!("{} face {}", b.name, names.get(i).map(String::as_str).unwrap_or("?"))) - }) - .collect(), - None => Vec::new(), - }; - list.sort(); - if list.is_empty() { "legacy, by its pick".into() } else { format!("legacy, by name among {}", list.join("; ")) } - } + FaceAttachmentStatus::Legacy { .. } => match name { + // The face its name finds, as the sketch finds it. + Some(n) => { + let fst = solidcraft_engine::doc::state_in_frame(doc, &before, f.component).unwrap(); + match naming::locate_face(&fst, n, *at) { + Some(hit) => format!("by name: {}{}", face_label(&fst, hit.body, hit.face), flags(&[(!hit.verified, "geometric")])), + None => { + ok = false; + "by name: gone".into() + } + } + } + None => "by its pick".into(), + }, FaceAttachmentStatus::Sheet { .. } => "sheet face".into(), FaceAttachmentStatus::Fixed { .. } => "fixed".into(), }; @@ -328,7 +316,13 @@ fn build(s: &Session) -> Build { let names = s.model.state().bodies.iter().flat_map(placed_names).collect(); let mut refs = Vec::new(); for f in s.doc.features.iter().filter(|f| !f.suppressed) { + let from = refs.len(); record_refs(&mut refs, s, f); + // A name that finds nothing is sound when its feature fails: it asks for the reference + // to be picked again. + if s.model.result(f.id).is_some_and(|r| r.error.is_some()) { + refs.iter_mut().skip(from).for_each(|(_, ok)| *ok = true); + } } Build { names, refs } } @@ -367,7 +361,7 @@ const UNSTABLE: [(&str, &str); 1] = [( )]; #[test] -fn corpus_designs_keep_their_references_and_name_alike_every_build() { +fn corpus_designs_name_alike_every_build_and_fail_where_a_reference_is_gone() { let designs = designs(); let next = std::sync::atomic::AtomicUsize::new(0); let results = std::sync::Mutex::new(Vec::new()); @@ -395,7 +389,7 @@ fn corpus_designs_keep_their_references_and_name_alike_every_build() { }; let lost: Vec<&str> = first.refs.iter().filter(|(_, ok)| !ok).map(|(r, _)| r.as_str()).collect(); if !lost.is_empty() { - problems.push(format!("{name}: stored names that find nothing:\n {}", lost.join("\n "))); + problems.push(format!("{name}: stored names that find nothing, in features that build:\n {}", lost.join("\n "))); } let apart = differences(first, second, 40); if !apart.is_empty() { diff --git a/assets/locales/pending/import-refuses-unbuildable-brep.json b/assets/locales/pending/import-refuses-unbuildable-brep.json new file mode 100644 index 000000000..46f015ab6 --- /dev/null +++ b/assets/locales/pending/import-refuses-unbuildable-brep.json @@ -0,0 +1,30 @@ +{ + "en": { + "import_report.refused_one": "1 part couldn't be made into a solid and was not imported.", + "import_report.refused_other": "{count} parts couldn't be made into solids and were not imported." + }, + "ar": { + "import_report.refused_one": "تعذّر تحويل جزء واحد إلى مجسم، فلم يُستورد.", + "import_report.refused_other": "تعذّر تحويل {count} أجزاء إلى مجسمات، فلم تُستورد." + }, + "de": { + "import_report.refused_one": "1 Teil konnte nicht zu einem Volumenkörper werden und wurde nicht importiert.", + "import_report.refused_other": "{count} Teile konnten nicht zu Volumenkörpern werden und wurden nicht importiert." + }, + "he": { + "import_report.refused_one": "לא ניתן היה להפוך חלק אחד לגוף מוצק והוא לא יובא.", + "import_report.refused_other": "לא ניתן היה להפוך {count} חלקים לגופים מוצקים והם לא יובאו." + }, + "ja": { + "import_report.refused_one": "1 個のパーツをソリッドにできず、読み込みませんでした。", + "import_report.refused_other": "{count} 個のパーツをソリッドにできず、読み込みませんでした。" + }, + "ko": { + "import_report.refused_one": "부품 1개를 솔리드로 만들지 못해 가져오지 않았습니다.", + "import_report.refused_other": "부품 {count}개를 솔리드로 만들지 못해 가져오지 않았습니다." + }, + "zh": { + "import_report.refused_one": "1 个零件无法生成实体,未导入。", + "import_report.refused_other": "{count} 个零件无法生成实体,未导入。" + } +} diff --git a/assets/locales/pending/import-report-words.json b/assets/locales/pending/import-report-words.json index f1267216b..a41975947 100644 --- a/assets/locales/pending/import-report-words.json +++ b/assets/locales/pending/import-report-words.json @@ -6,8 +6,6 @@ "import_report.hint": "Exporting these parts again from the program that made them may fix this. Copy Warning Message has the details.", "import_report.left_out_one": "1 face couldn't be repaired and is missing.", "import_report.left_out_other": "{count} faces couldn't be repaired and are missing.", - "import_report.mesh_one": "1 part couldn't be made into a solid and is shown as a mesh.", - "import_report.mesh_other": "{count} parts couldn't be made into solids and are shown as meshes.", "import_report.not_imported_one": "1 part couldn't be imported.", "import_report.not_imported_other": "{count} parts couldn't be imported.", "import_report.not_shown_one": "1 face couldn't be drawn and is hidden.", @@ -27,8 +25,6 @@ "import_report.hint": "قد يحل ذلك تصدير هذه الأجزاء مرة أخرى من البرنامج الذي أنشأها. يحتوي «نسخ رسالة التحذير» على التفاصيل.", "import_report.left_out_one": "تعذّر إصلاح وجه واحد وهو مفقود.", "import_report.left_out_other": "تعذّر إصلاح {count} أوجه وهي مفقودة.", - "import_report.mesh_one": "تعذّر تحويل جزء واحد إلى مجسم، فهو معروض كشبكة.", - "import_report.mesh_other": "تعذّر تحويل {count} أجزاء إلى مجسمات، فهي معروضة كشبكات.", "import_report.not_imported_one": "تعذّر استيراد جزء واحد.", "import_report.not_imported_other": "تعذّر استيراد {count} أجزاء.", "import_report.not_shown_one": "تعذّر رسم وجه واحد وهو مخفي.", @@ -48,8 +44,6 @@ "import_report.hint": "Die Teile erneut aus dem Programm zu exportieren, mit dem sie erstellt wurden, kann das beheben. „Warnmeldung kopieren“ enthält die Details.", "import_report.left_out_one": "1 Fläche konnte nicht repariert werden und fehlt.", "import_report.left_out_other": "{count} Flächen konnten nicht repariert werden und fehlen.", - "import_report.mesh_one": "1 Teil konnte nicht zu einem Volumenkörper werden und wird als Netz gezeigt.", - "import_report.mesh_other": "{count} Teile konnten nicht zu Volumenkörpern werden und werden als Netze gezeigt.", "import_report.not_imported_one": "1 Teil konnte nicht importiert werden.", "import_report.not_imported_other": "{count} Teile konnten nicht importiert werden.", "import_report.not_shown_one": "1 Fläche konnte nicht gezeichnet werden und ist ausgeblendet.", @@ -69,8 +63,6 @@ "import_report.hint": "ייצוא מחדש של החלקים האלה מהתוכנה שיצרה אותם עשוי לפתור זאת. ב„העתקת הודעת האזהרה” יש את הפרטים.", "import_report.left_out_one": "לא ניתן היה לתקן פאה אחת והיא חסרה.", "import_report.left_out_other": "לא ניתן היה לתקן {count} פאות והן חסרות.", - "import_report.mesh_one": "לא ניתן היה להפוך חלק אחד לגוף מוצק והוא מוצג כרשת.", - "import_report.mesh_other": "לא ניתן היה להפוך {count} חלקים לגופים מוצקים והם מוצגים כרשתות.", "import_report.not_imported_one": "לא ניתן היה לייבא חלק אחד.", "import_report.not_imported_other": "לא ניתן היה לייבא {count} חלקים.", "import_report.not_shown_one": "לא ניתן היה לצייר פאה אחת והיא מוסתרת.", @@ -90,8 +82,6 @@ "import_report.hint": "作成元のプログラムからこれらのパーツを書き出し直すと直ることがあります。詳細は「警告メッセージをコピー」で確認できます。", "import_report.left_out_one": "1 個の面を修復できず、欠けています。", "import_report.left_out_other": "{count} 個の面を修復できず、欠けています。", - "import_report.mesh_one": "1 個のパーツをソリッドにできず、メッシュで表示しています。", - "import_report.mesh_other": "{count} 個のパーツをソリッドにできず、メッシュで表示しています。", "import_report.not_imported_one": "1 個のパーツを読み込めませんでした。", "import_report.not_imported_other": "{count} 個のパーツを読み込めませんでした。", "import_report.not_shown_one": "1 個の面を描画できず、非表示です。", @@ -111,8 +101,6 @@ "import_report.hint": "이 부품을 만든 프로그램에서 다시 내보내면 해결될 수 있습니다. 세부 정보는 경고 메시지 복사에 있습니다.", "import_report.left_out_one": "면 1개를 복구하지 못해 빠져 있습니다.", "import_report.left_out_other": "면 {count}개를 복구하지 못해 빠져 있습니다.", - "import_report.mesh_one": "부품 1개를 솔리드로 만들지 못해 메시로 표시합니다.", - "import_report.mesh_other": "부품 {count}개를 솔리드로 만들지 못해 메시로 표시합니다.", "import_report.not_imported_one": "부품 1개를 가져오지 못했습니다.", "import_report.not_imported_other": "부품 {count}개를 가져오지 못했습니다.", "import_report.not_shown_one": "면 1개를 그리지 못해 숨겨져 있습니다.", @@ -132,8 +120,6 @@ "import_report.hint": "从创建这些零件的程序重新导出可能会解决此问题。“复制警告消息”中有详细信息。", "import_report.left_out_one": "1 个面无法修复,已缺失。", "import_report.left_out_other": "{count} 个面无法修复,已缺失。", - "import_report.mesh_one": "1 个零件无法生成实体,以网格显示。", - "import_report.mesh_other": "{count} 个零件无法生成实体,以网格显示。", "import_report.not_imported_one": "1 个零件无法导入。", "import_report.not_imported_other": "{count} 个零件无法导入。", "import_report.not_shown_one": "1 个面无法绘制,已隐藏。", diff --git a/assets/locales/pending/reference-reselect.json b/assets/locales/pending/reference-reselect.json new file mode 100644 index 000000000..2cea7dc5e --- /dev/null +++ b/assets/locales/pending/reference-reselect.json @@ -0,0 +1,23 @@ +{ + "ar": { + "diagnostic.reselect_reference": "{feature}: المرجع `{reference}` لم يعد موجودًا كما اختير؛ أعد اختياره" + }, + "de": { + "diagnostic.reselect_reference": "{feature}: Die Referenz `{reference}` existiert nicht mehr so, wie sie ausgewählt wurde; wählen Sie sie erneut aus" + }, + "en": { + "diagnostic.reselect_reference": "{feature}: the reference `{reference}` no longer exists as it was picked; reselect it" + }, + "he": { + "diagnostic.reselect_reference": "{feature}: ההפניה `{reference}` כבר אינה קיימת כפי שנבחרה; יש לבחור אותה מחדש" + }, + "ja": { + "diagnostic.reselect_reference": "{feature}: 参照 `{reference}` は選択したときのままでは存在しません。選択し直してください" + }, + "ko": { + "diagnostic.reselect_reference": "{feature}: 참조 `{reference}`이(가) 선택했을 때의 모습으로 더 이상 존재하지 않습니다. 다시 선택하세요" + }, + "zh": { + "diagnostic.reselect_reference": "{feature}:引用 `{reference}` 已不再是选择时的样子;请重新选择" + } +} diff --git a/assets/locales/pending/validation-once-per-feature.json b/assets/locales/pending/validation-once-per-feature.json new file mode 100644 index 000000000..9a517e102 --- /dev/null +++ b/assets/locales/pending/validation-once-per-feature.json @@ -0,0 +1,65 @@ +{ + "ar": { + "cmd.diagnostics_validation": "التحقق", + "prefs.validation": "التحقق من الأجسام", + "prefs.validation.each_feature": "مرة لكل ميزة", + "prefs.validation.each_step": "بعد كل خطوة", + "prefs.validation.label": "فحص النواة الكامل", + "prefs.validation.off": "متوقف (تجريبي)", + "prefs.validation_note": "مرة لكل ميزة: تُفحص الأجسام التي تنتجها الميزة مرة واحدة قبل الاحتفاظ بها، وتفشل الميزة إذا رُفض أحدها. بعد كل خطوة: يُفحص ناتج كل عملية سحب ودمج وتقويس، كما في السابق. متوقف: لا فحص، فقد يُحتفظ بجسم معيب." + }, + "de": { + "cmd.diagnostics_validation": "Prüfung", + "prefs.validation": "Körperprüfung", + "prefs.validation.each_feature": "Einmal je Feature", + "prefs.validation.each_step": "Nach jedem Schritt", + "prefs.validation.label": "Vollständige Kernel-Prüfung", + "prefs.validation.off": "Aus (experimentell)", + "prefs.validation_note": "Einmal je Feature: Die Körper, die ein Feature erzeugt, werden einmal geprüft, bevor sie übernommen werden; wird einer abgelehnt, schlägt das Feature fehl. Nach jedem Schritt: Das Ergebnis jedes Sweeps, jeder Boolesche Operation und jeder Rundung wird geprüft, wie bisher. Aus: keine Prüfung, ein fehlerhafter Körper kann bleiben." + }, + "en": { + "cmd.diagnostics_validation": "Validation", + "prefs.validation": "Body check", + "prefs.validation.each_feature": "Once per feature", + "prefs.validation.each_step": "After every step", + "prefs.validation.label": "Full kernel check", + "prefs.validation.off": "Off (experimental)", + "prefs.validation_note": "Once per feature: the bodies a feature makes are checked once before they are kept, and the feature fails if one is refused. After every step: the result of every sweep, boolean and blend is checked, as before. Off: no check, so a faulty body can be kept." + }, + "he": { + "cmd.diagnostics_validation": "אימות", + "prefs.validation": "בדיקת גופים", + "prefs.validation.each_feature": "פעם אחת לכל תכונה", + "prefs.validation.each_step": "אחרי כל שלב", + "prefs.validation.label": "הבדיקה המלאה של הקרנל", + "prefs.validation.off": "כבוי (ניסיוני)", + "prefs.validation_note": "פעם אחת לכל תכונה: הגופים שתכונה יוצרת נבדקים פעם אחת לפני שהם נשמרים, והתכונה נכשלת אם אחד מהם נדחה. אחרי כל שלב: התוצאה של כל סחיפה, פעולה בוליאנית ועיגול נבדקת, כמו קודם. כבוי: אין בדיקה, ולכן גוף פגום עלול להישמר." + }, + "ja": { + "cmd.diagnostics_validation": "検証", + "prefs.validation": "ボディのチェック", + "prefs.validation.each_feature": "フィーチャーごとに 1 回", + "prefs.validation.each_step": "各ステップの後", + "prefs.validation.label": "カーネルの完全チェック", + "prefs.validation.off": "オフ (試験的)", + "prefs.validation_note": "フィーチャーごとに 1 回: フィーチャーが作るボディを保持する前に 1 回チェックし、拒否されたものがあればフィーチャーは失敗します。各ステップの後: これまでどおり、スイープ、ブーリアン、ブレンドのたびに結果をチェックします。オフ: チェックしないため、不正なボディが残ることがあります。" + }, + "ko": { + "cmd.diagnostics_validation": "검증", + "prefs.validation": "바디 검사", + "prefs.validation.each_feature": "피처마다 한 번", + "prefs.validation.each_step": "모든 단계 후", + "prefs.validation.label": "커널 전체 검사", + "prefs.validation.off": "끄기 (실험적)", + "prefs.validation_note": "피처마다 한 번: 피처가 만든 바디를 유지하기 전에 한 번 검사하며, 하나라도 거부되면 피처가 실패합니다. 모든 단계 후: 이전처럼 스윕, 불리언, 블렌드마다 결과를 검사합니다. 끄기: 검사하지 않으므로 결함 있는 바디가 남을 수 있습니다." + }, + "zh": { + "cmd.diagnostics_validation": "验证", + "prefs.validation": "实体检查", + "prefs.validation.each_feature": "每个特征一次", + "prefs.validation.each_step": "每一步之后", + "prefs.validation.label": "内核完整检查", + "prefs.validation.off": "关闭(实验性)", + "prefs.validation_note": "每个特征一次:特征生成的实体在保留前检查一次,若有实体被拒绝,该特征失败。每一步之后:与以前一样,每次扫掠、布尔运算和倒圆后都检查结果。关闭:不检查,因此可能保留有缺陷的实体。" + } +} diff --git a/crates/doc/src/config_certificates.rs b/crates/doc/src/config_certificates.rs index f2080b01f..da5b3413a 100644 --- a/crates/doc/src/config_certificates.rs +++ b/crates/doc/src/config_certificates.rs @@ -842,8 +842,13 @@ impl Document { }; let mut indices: Vec = names.faces.iter().enumerate().filter(|(_, face)| piece_of(face)).map(|(index, _)| index).collect(); if indices.is_empty() { - indices = - names.info.iter().enumerate().filter(|(_, info)| info.aliases.iter().any(|alias| alias == name)).map(|(index, _)| index).collect(); + indices = names + .info + .iter() + .enumerate() + .filter(|(_, info)| info.synonyms.iter().chain(&info.aliases).any(|other| other == name)) + .map(|(index, _)| index) + .collect(); } if indices.is_empty() { return Err(DocError::Unknown(format!("face `{name}` on `{}` no longer exists", body.name))); diff --git a/crates/doc/src/config_shell_tests.rs b/crates/doc/src/config_shell_tests.rs index 48e9f04b3..06cd00f77 100644 --- a/crates/doc/src/config_shell_tests.rs +++ b/crates/doc/src/config_shell_tests.rs @@ -221,7 +221,7 @@ fn regularized_shell_keeps_legacy_and_explicit_single_face_projections_closed() let mut sketch = solidcraft_sketch::Sketch::new(); let link = sketch.add_link(solidcraft_sketch::LinkKind::Project, source, &legacy.geom).unwrap(); sketch.links[0].face_name = Some(crate::naming::face_names(body)[index].clone()); - let warnings = crate::project::refresh_links(&doc, &values, &state, &plane, &mut sketch); + let warnings = crate::project::refresh_links(&doc, &values, &state, &plane, &mut sketch).unwrap(); assert!(warnings.is_empty(), "{warnings:?}"); assert!(!sketch.links[0].lost); assert!(!sketch.update_link(&link, &explicit.geom).unwrap()); @@ -230,7 +230,7 @@ fn regularized_shell_keeps_legacy_and_explicit_single_face_projections_closed() } #[test] -fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material() { +fn saved_former_strip_projection_asks_for_its_face_again_without_expanding_healthy_material() { let (mut doc, _, _) = shell_document(); let mut model = Model::new(); model.evaluate(&doc); @@ -257,10 +257,9 @@ fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material ) .unwrap(); sketch.links[0].face_name = Some(former.clone()); - let original = sketch.clone(); let sk = doc .add_feature( - FeatureKind::Sketch { plane: PlaneRef::Face { plane, at: Vec3::new(20., 6., 1.), name: Some(former), anchor: None }, sketch }, + FeatureKind::Sketch { plane: PlaneRef::Face { plane, at: Vec3::new(20., 6., 1.), name: Some(former.clone()), anchor: None }, sketch }, Some("Saved strip sketch"), ) .unwrap(); @@ -288,27 +287,19 @@ fn saved_former_strip_projection_reports_lost_without_expanding_healthy_material let mut cold = Model::new(); cold.evaluate(&loaded); for current in [&model, &cold] { - let warning = current.results.iter().find(|r| r.id == sk).unwrap().warning.as_deref().unwrap(); - assert!(warning.contains("no longer exists; last geometry retained"), "{warning}"); - let state = current.state(); - let solved = state.sketch(sk).unwrap(); - assert!(solved.sketch.links[0].lost); - assert_eq!(solved.sketch.curves, original.curves); - assert_eq!(solved.sketch.points, original.points); - let material = state.bodies.iter().find(|body| body.feature == boss).unwrap(); - assert!( - (solidcraft_kernel::measure(&material.body).unwrap().volume - 24.).abs() < 1e-8, - "old24mm3 profile must not silently become120mm3 wall profile" - ); - let bounds = material.mesh().bounds(); - assert!((bounds.min.x - width).abs() < 1e-8 && (bounds.max.x - width - 1.).abs() < 1e-8); - assert!((bounds.max.y - 12.).abs() < 1e-8 && (bounds.max.z - 2.).abs() < 1e-8); + // The name was saved before format 14 (marked): it finds no face, so the sketch on it + // fails, asking for its face again, and so does the material made from it. + let result = current.results.iter().find(|r| r.id == sk).unwrap(); + let reference = format!("{}{former}", crate::naming::LEGACY_MARK); + assert_eq!(result.error.as_deref().and_then(crate::reselect_parts), Some(("Saved strip sketch", reference.as_str())), "{result:?}"); + assert!(current.results.iter().find(|r| r.id == boss).unwrap().error.is_some()); + assert!(current.state().bodies.iter().all(|body| body.feature != boss), "old 24 mm3 profile must not silently become the 120 mm3 wall"); } } } #[test] -fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { +fn saved_curved_strip_projection_asks_for_its_face_again_after_exact_wall_coalescence() { use solidcraft_sketch::{LinkKind, LinkSource, Sketch}; let mut doc = Document::new("saved curved strip"); doc.set_param("width", "80", Some("mm"), None).unwrap(); @@ -356,13 +347,13 @@ fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { // longest spread), from z = 0 to 2. Projected on YZ, the quarter round from (40, 24) to // (34, 30) is the rectangle y 24..30, z 0..2: its two arcs and its two straight sides. let former = format!("{stem}#1"); + let reference = former.clone(); let source = LinkSource::Face { body: "Case".into(), at }; let (a, b, c, d) = (Vec2::new(24., 0.), Vec2::new(30., 0.), Vec2::new(30., 2.), Vec2::new(24., 2.)); let geometry: Vec<_> = [(a, b), (b, c), (c, d), (d, a)].into_iter().map(|(p, q)| solidcraft_sketch::LinkGeom::Line(p, q)).collect(); let mut sketch = Sketch::new(); sketch.add_link(LinkKind::Project, source, &geometry).unwrap(); sketch.links[0].face_name = Some(former); - let original = sketch.clone(); let sk = doc .add_feature(FeatureKind::Sketch { plane: PlaneRef::Custom { plane: solidcraft_geom::Plane::YZ }, sketch }, Some("Saved corner strip")) .unwrap(); @@ -387,25 +378,21 @@ fn saved_curved_strip_projection_is_lost_after_exact_wall_coalescence() { let mut cold = Model::new(); cold.evaluate(&loaded); for current in [&model, &cold] { + // No face is the piece any more, and the whole wall is not it: the sketch fails, + // asking for its face again, and so does the material made from it. The case builds. let result = current.results.iter().find(|r| r.id == sk).unwrap(); - assert!(result.error.is_none()); - assert!(result.warning.as_deref().unwrap().contains("no longer exists; last geometry retained")); + assert_eq!(result.error.as_deref().and_then(crate::reselect_parts), Some(("Saved corner strip", reference.as_str())), "{result:?}"); + assert!(current.results.iter().find(|r| r.id == boss).unwrap().error.is_some()); + assert!(current.results.iter().filter(|r| r.id != sk && r.id != boss).all(|r| r.error.is_none()), "{:?}", current.results); let state = current.state(); - let solved = state.sketch(sk).unwrap(); - assert!(solved.sketch.links[0].lost); - assert_eq!(solved.sketch.points, original.points); - assert_eq!(solved.sketch.curves, original.curves); - let material = state.bodies.iter().find(|body| body.feature == boss).unwrap(); - assert!( - (solidcraft_kernel::measure(&material.body).unwrap().volume - 12.).abs() < 1e-7, - "two-mm strip cannot expand to a full thirty-mm wall" - ); + assert!(state.body("Case").is_some()); + assert!(state.bodies.iter().all(|body| body.feature != boss), "two-mm strip cannot expand to a full thirty-mm wall"); } } } #[test] -fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { +fn saved_stepped_tab_cut_piece_projection_asks_for_its_face_again_without_expanding_material() { use solidcraft_sketch::{LinkKind, LinkSource, Sketch}; let mut doc = Document::new("public stepped tab case"); doc.set_param("length", "40", Some("mm"), None).unwrap(); @@ -466,9 +453,8 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { let geometry: Vec<_> = (0..4).map(|i| solidcraft_sketch::LinkGeom::Line(corners[i], corners[(i + 1) % 4])).collect(); let mut sketch = Sketch::new(); sketch.add_link(LinkKind::Project, LinkSource::Face { body: "Case".into(), at }, &geometry).unwrap(); - sketch.links[0].face_name = Some(former); - let original = sketch.clone(); - let captured = original.points.iter().filter(|p| p.link.is_some()).map(|p| p.pos).collect::>(); + sketch.links[0].face_name = Some(former.clone()); + let captured = sketch.points.iter().filter(|p| p.link.is_some()).map(|p| p.pos).collect::>(); assert_eq!(captured.len(), 4); assert!(captured.iter().all(|p| (p.x == 10. || p.x == 20.) && (p.y == 0. || p.y == 20.))); let sk = doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Custom { plane }, sketch }, Some("Saved wall patch")).unwrap(); @@ -493,22 +479,13 @@ fn saved_stepped_tab_cut_piece_projection_is_lost_without_expanding_material() { let mut cold = Model::new(); cold.evaluate(&reopened); for current in [&model, &cold] { + // No face is the patch any more, and the whole wall is not it: the sketch fails, + // asking for its face again, and so does the stock made from it. let result = current.results.iter().find(|r| r.id == sk).unwrap(); - assert!(result.error.is_none(), "{result:?}"); - assert!(result.warning.as_deref().is_some_and(|w| w.contains("no longer exists; last geometry retained")), "{result:?}"); + assert_eq!(result.error.as_deref().and_then(crate::reselect_parts), Some(("Saved wall patch", former.as_str())), "{result:?}"); + assert!(current.results.iter().find(|r| r.id == material).unwrap().error.is_some()); let state = current.state(); - let saved = state.sketch(sk).unwrap(); - assert!(saved.sketch.links[0].lost); - assert_eq!(saved.sketch.points, original.points); - assert_eq!(saved.sketch.curves, original.curves); - let stock = state.bodies.iter().find(|b| b.feature == material).unwrap(); - assert!( - (solidcraft_kernel::measure(&stock.body).unwrap().volume - 200.).abs() < 1e-7, - "saved10x20 patch must not become30x20 wall; actualvolume={}, bounds={:?}, originalpoints={:?}", - solidcraft_kernel::measure(&stock.body).unwrap().volume, - stock.mesh().bounds(), - original.points - ); + assert!(state.bodies.iter().all(|b| b.feature != material), "saved 10 x 20 patch must not become the 30 x 20 wall"); let case = state.body("Case").unwrap(); let expected = length * 30. * 20. + 8. * 10. * 8. - (length - 2. * wall) * (30. - 2. * wall) * (20. - wall); assert!((solidcraft_kernel::measure(&case.body).unwrap().volume - expected).abs() < 1e-6); diff --git a/crates/doc/src/config_styles.rs b/crates/doc/src/config_styles.rs index 4201e4c3e..046643b70 100644 --- a/crates/doc/src/config_styles.rs +++ b/crates/doc/src/config_styles.rs @@ -279,13 +279,13 @@ impl Document { let count = body.body.face_sources().map_or(0, |sources| sources.len()); let mut indices: Vec<_> = (0..count).filter(|index| side(*index, true)).collect(); // A side drawn in collinear pieces is one face over all of them (#1788): a certificate - // made when the pieces were faces of their own finds it by the piece's name, which - // the joined face answers to. + // made when the pieces were faces of their own finds it by the piece's name, which is + // a name of the joined face too (one of its synonyms). if indices.is_empty() { let names = crate::naming::names(body); indices = (0..count) .filter(|index| { - side(*index, false) && crate::history_names::matches(&names, *index, &target.name) == Some(crate::history_names::Match::Alias) + side(*index, false) && crate::history_names::matches(&names, *index, &target.name) == Some(crate::history_names::Match::Exact) }) .collect(); } diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index 6b21b8465..720d6bcbb 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -141,16 +141,16 @@ fn construct<'a>(st: &'a ModelState, name: &str) -> Result<&'a ConstructGeom> { st.construct.iter().find(|c| c.name == name).map(|c| &c.geom).ok_or_else(|| DocError::Unknown(format!("construction `{name}`"))) } -/// The face picked: (body, face index, point on it). +/// The face picked: (body, face index, point on it). A face picked with a name is the face the +/// name finds, or the reference fails, asking for it to be picked again. fn face_of<'a>(st: &'a ModelState, at: Vec3, name: &Option) -> Result<(&'a ModelBody, usize, Vec3)> { // The named face itself: its nearest point to the old pick can lie on an edge it shares // (a corner round that a parameter moved away from the pick), where picking again by the // point finds the flat face beside it (#1255). - if let Some(hit) = name.as_deref().and_then(|n| crate::name_lookup::locate_face(st, n, at)) - && let Some(b) = st.bodies.get(hit.body).filter(|b| !b.body.is_mesh()) - && hit.face < b.body.face_count() - { - return Ok((b, hit.face, hit.point)); + if let Some(n) = name.as_deref() { + return crate::name_lookup::locate_face(st, n, at) + .and_then(|hit| st.bodies.get(hit.body).filter(|b| !b.body.is_mesh() && hit.face < b.body.face_count()).map(|b| (b, hit.face, hit.point))) + .ok_or_else(|| DocError::reselect(n)); } for b in bodies(st) { if let Some(fi) = crate::appearance::face_index_at(b, at) { @@ -165,16 +165,13 @@ fn edge_points(st: &ModelState, at: Vec3, name: &Option) -> Result(st: &'a ModelState, at: Vec3, name: &Option) -> Result<(&'a ModelBody, usize, Vec)> { let mut at = at; if let Some(n) = name { - for b in bodies(st) { - if let Ok((q, _)) = crate::naming::find_edge(b, n, at) { - at = q; - break; - } - } + at = bodies(st).find_map(|b| crate::naming::find_edge(b, n, at).ok()).ok_or_else(|| DocError::reselect(n.as_str()))?; } let mut best: Option<(f64, &ModelBody, usize, Vec)> = None; for b in bodies(st) { @@ -216,7 +213,7 @@ fn named_vertex(st: &ModelState, at: Vec3, names: &[String]) -> Option { .iter() .map(|n| { // The edge with that name itself, never the one nearest the old pick. - let on = bodies(st).find_map(|b| crate::naming::find_edge(b, n, at).ok())?.0; + let on = bodies(st).find_map(|b| crate::naming::find_edge(b, n, at).ok())?; let pts = edge_points(st, on, &None).ok()?; Some([*pts.first()?, *pts.last()?]) }) @@ -683,12 +680,15 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { impl GeoRef { /// Where a picked edge or face is now, found the way evaluation finds it (by its persistent - /// name, else at the picked point): a point on it. `None` for other references and for an + /// name when it has one, else at the picked point): a point on it. `None` for other references and for an /// edge or face that is gone. pub fn picked_point(&self, st: &ModelState) -> Option { match self { GeoRef::Edge { at, name } => { - let on = name.as_deref().and_then(|n| bodies(st).find_map(|b| crate::naming::find_edge(b, n, *at).ok())).map_or(*at, |(q, _)| q); + let on = match name.as_deref() { + Some(n) => bodies(st).find_map(|b| crate::naming::find_edge(b, n, *at).ok())?, + None => *at, + }; edge_pick(st, on, &None).ok().map(|_| on) } GeoRef::Face { at, name } => face_of(st, *at, name).ok().map(|(_, _, p)| p), diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 31b4bcc12..80bee4c70 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1032,6 +1032,8 @@ pub struct Model { primed: Option<(u64, Arc>)>, /// Shared with copies of this evaluator; states hold only a weak reference. frame_bodies: Arc>, + /// When SMLib's check runs on the features this model evaluates ([`Model::set_validation`]). + validation: kernel::Validation, } /// Parameters a feature uses directly (inputs, sketch dimensions and the expressions of a @@ -1361,6 +1363,33 @@ fn context_digest(doc: &Document, vals: &BTreeMap) -> u64 { h.finish() } +/// What the validation mode adds to the context digest: nothing for checking every step (how +/// every evaluation before the mode checked, so its results and saved caches stand), so a result +/// is taken from the cache only under the mode it was evaluated in. +fn validation_digest(validation: kernel::Validation) -> u64 { + match validation { + kernel::Validation::EachStep => 0, + v => { + let mut h = std::collections::hash_map::DefaultHasher::new(); + ("validation", v.id()).hash(&mut h); + h.finish() + } + } +} + +/// SMLib's check of every body a feature made or changed (in `after`, not in `before`, the +/// state it started from), once its steps left their checks to its end: the first that fails is +/// the feature's error, naming the body. +fn check_kept(before: &ModelState, after: &ModelState) -> kernel::Result<()> { + for b in &after.bodies { + if before.bodies.iter().any(|old| old.body.same_shape(&b.body)) { + continue; + } + kernel::check_kept(&b.body).map_err(|e| kernel::KernelError::Failed(format!("body `{}`: {e}", b.name)))?; + } + Ok(()) +} + /// Whether `after`, a state feature `f` evaluated to from `before` in an earlier evaluation, is /// still its result in `doc`: a feature saved before format 14 names the pieces it splits a body /// into as the later features pick them ([`crate::lineage::order_legacy_lumps`]), which neither @@ -1846,6 +1875,19 @@ impl Model { self.primed = None; } + /// When SMLib's check runs on the features this model evaluates. + pub fn validation(&self) -> kernel::Validation { + self.validation + } + + /// Check the features evaluated from now on under `validation` ([`kernel::Validation`]): + /// after every sweep, boolean and blend, once on the bodies each feature keeps, or not at + /// all. The results already there stand until their features are evaluated again; the cache + /// keeps results apart by mode, so one evaluated under another mode is not taken up. + pub fn set_validation(&mut self, validation: kernel::Validation) { + self.validation = validation; + } + /// Re-evaluate the document, reusing results up to the first changed feature. pub fn evaluate(&mut self, doc: &Document) { let _span = solidcraft_profile::span("doc", "evaluate"); @@ -1862,7 +1904,8 @@ impl Model { let mut recomputed = 0; let mut restored = 0; let marker = doc.marker.unwrap_or(usize::MAX); - let ctx = context_digest(doc, &vals); + let validation = self.validation; + let ctx = context_digest(doc, &vals) ^ validation_digest(validation); let previous_context = self.context; let mut rolled_results = std::mem::take(&mut self.rolled_results); self.context = ctx; @@ -2020,7 +2063,7 @@ impl Model { } Ok(None) => f, Err(e) => { - frame_error = Some(e.to_string()); + frame_error = Some(e.in_feature(&f.name).to_string()); f } }; @@ -2029,8 +2072,11 @@ impl Model { let r = match frame_error.or(bad_param) { Some(e) => Err(kernel::KernelError::Failed(e)), None => kernel::guard(&f.name, || { - eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report, &mut repair) - .map_err(|e| kernel::KernelError::Failed(e.to_string())) + let (r, deferred) = + kernel::validating(validation, || eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report, &mut repair)); + r.map_err(|e| kernel::KernelError::Failed(e.in_feature(&f.name).to_string()))?; + // The checks the feature's steps left to its end: the bodies it keeps. + if deferred { check_kept(&state, &next) } else { Ok(()) } }), }; if r.is_ok() { @@ -3437,18 +3483,18 @@ fn trusted_edge_name(f: &Feature, i: usize, p: Vec3) -> Option<&str> { } /// The body (index) an edge name finds an edge on, when one does: the one where the edge still -/// runs through the pick `p`, else where the name is one edge (not split), else the nearest. +/// runs through the pick `p`, else the nearest. fn named_body(st: &ModelState, name: &str, p: Vec3) -> Option { // Names start with the feature that made the face: only bodies with such a face can hold it. let bare = crate::naming::legacy_name(name).unwrap_or(name); let token = bare.find(':').map(|k| &bare[..=k]); - let mut best: Option<(usize, (bool, bool, f64))> = None; + let mut best: Option<(usize, (bool, f64))> = None; for (i, b) in st.bodies.iter().enumerate() { if b.body.is_mesh() || token.is_some_and(|t| !crate::naming::face_names(b).iter().any(|n| n.contains(t))) { continue; } let Ok(hit) = crate::naming::locate_edge(b, name, p) else { continue }; - let score = (hit.on_point, !hit.split, -hit.point.dist(p)); + let score = (hit.on_point, -hit.point.dist(p)); if best.as_ref().is_none_or(|(_, s)| score.partial_cmp(s).is_some_and(|o| o.is_gt())) { best = Some((i, score)); } @@ -3520,8 +3566,9 @@ fn blend_bodies(st: &ModelState, f: &Feature, body: &Option, pt Ok(out) } -/// The edges `idx` of blend `f` found on body `mb`: by name first; a name that is gone falls back -/// to the point, with a warning. +/// The edges `idx` of blend `f` found on body `mb`: by name, where the edge was stored with one. +/// A name that no longer finds exactly its edge fails the blend, asking for the edge to be picked +/// again; so does a name a build stored for the wrong body (see `trusted_edge_name`). fn blend_edges_on(mb: &ModelBody, f: &Feature, edges: &[crate::Position], idx: &[usize], warning: &mut Option) -> Result> { let pick = |i: usize| edges.get(i).map(|p| p.0).unwrap_or(Vec3::ZERO); if !f.edge_names.iter().any(|n| !n.is_empty()) { @@ -3532,51 +3579,34 @@ fn blend_edges_on(mb: &ModelBody, f: &Feature, edges: &[crate::Position], idx: & let (mut out, mut notes) = (Vec::new(), Vec::new()); for &i in idx { let p = pick(i); - let stored = f.edge_names.get(i).filter(|n| !n.is_empty()); - let trusted = trusted_edge_name(f, i, p); - // A name recorded on another body (see `trusted_edge_name`): the pick alone. - if stored.is_some() && trusted.is_none() { + let Some(stored) = f.edge_names.get(i).filter(|n| !n.is_empty()) else { + // An edge picked without a name: by its point. A pick on the axis of a round must not + // fall through to the tangency seam (#775). let mut w = None; - match resolve_edges(&mb.body, &[p], &[], &mut w) { - Ok(q) => out.extend(q), - Err(_) => notes.push("an edge reference was not found at its point and was skipped".to_string()), + let refs: Vec = f.edge_refs.get(i).cloned().into_iter().collect(); + let skipped = "edge `?` no longer exists and was skipped"; + if pick_lies_on_a_round_axis(&mb.body, p) { + notes.push(skipped.into()); + } else if let Ok(q) = resolve_edges(&mb.body, &[p], &refs, &mut w) { + out.extend(q); + notes.push("an edge reference without a name was found by its point".into()); + } else { + notes.push(skipped.into()); } - notes.extend(w); continue; + }; + let hit = + trusted_edge_name(f, i, p).and_then(|n| crate::naming::locate_edge(mb, n, p).ok()).ok_or_else(|| DocError::reselect(stored.as_str()))?; + if let Some(note) = hit.note(stored) { + notes.push(note); } - match trusted.map(|n| (n, crate::naming::locate_edge(mb, n, p))) { - Some((n, Ok(hit))) => { - if let Some(note) = hit.note(n) { - notes.push(note); - } - // The body changed since the pick: the pick may now sit at an end of the edge. - let moved = f.edge_refs.get(i).is_some_and(|r| { - let now = mb.mesh().bounds(); - let tight = (mb.body.size() * 2e-3).max(1e-3); - now.min.dist(r.min) > tight || now.max.dist(r.max) > tight - }); - out.push(if moved { off_the_ends(mb, hit.edge, hit.point) } else { hit.point }); - } - Some((_, Err(_))) | None => { - let mut w = None; - let refs: Vec = f.edge_refs.get(i).cloned().into_iter().collect(); - let skipped = format!("edge `{}` no longer exists and was skipped", stored.map(String::as_str).unwrap_or("?")); - // The name is gone. A pick on the axis of a round must not fall through to the - // tangency seam (#775). A sharp edge that moved still resolves from the point, - // which an edit relies on. - if pick_lies_on_a_round_axis(&mb.body, p) { - notes.push(skipped); - } else if let Ok(q) = resolve_edges(&mb.body, &[p], &refs, &mut w) { - out.extend(q); - notes.push(match stored { - Some(n) => format!("edge `{n}` no longer exists; using the edge at the picked point"), - None => "an edge reference without a name was found by its point".into(), - }); - } else { - notes.push(skipped); - } - } - } + // The body changed since the pick: the pick may now sit at an end of the edge. + let moved = f.edge_refs.get(i).is_some_and(|r| { + let now = mb.mesh().bounds(); + let tight = (mb.body.size() * 2e-3).max(1e-3); + now.min.dist(r.min) > tight || now.max.dist(r.max) > tight + }); + out.push(if moved { off_the_ends(mb, hit.edge, hit.point) } else { hit.point }); } if out.is_empty() { let why = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join("; ")) }; @@ -5666,9 +5696,9 @@ fn copied_features(doc: &Document, vals: &BTreeMap, st: &ModelSta /// `mats`' own (which keep the numbers they always had), each nested source in a block of its /// own, so no two copies of one feature share an instance. Suppressed sources copy nothing. /// `f` with each face point moved onto its named face (on the body the feature names, when it -/// names one and the face is there) in `state`, and notes for names that no longer find their -/// face. `None` when `f` names no face; an error when the frame the faces are looked up in -/// cannot be made (the feature fails with it). +/// names one and the face is there) in `state`, and notes on how the faces were found. `None` +/// when `f` names no face; an error when a name no longer finds its face (the feature asks for +/// it to be picked again), or when the frame the faces are looked up in cannot be made. fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Result)>> { // Cylindrical emboss resolves its named face in the selected body's frame // and certifies an analytic anchor; mesh projection here would undo that. @@ -5708,7 +5738,7 @@ fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Re _ => *p = hit.pick_point(&fst, *p), } } - None => notes.push(format!("face `{n}` no longer exists; using the face at the picked point")), + None => return Err(DocError::reselect(n.as_str())), } } Ok(Some((g, notes))) @@ -6233,53 +6263,27 @@ pub(crate) fn sheet_face_plane_in_frame(doc: &Document, st: &ModelState, comp: u }) } -/// The plane of the body face a sketch sits on, found again: among planar faces with the -/// picked plane's normal, the one nearest `at`. The picked frame moves along its normal onto it. -fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> (Plane, Option) { +/// The plane of the body face a sketch sits on, found again: the face its stored `name` finds, +/// which must still be planar and face the picked plane's way (else the sketch fails, asking for +/// its face to be picked again); without a name, among planar faces with the picked plane's +/// normal, the one nearest `at`. The picked frame moves along its normal onto it. +fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> Result<(Plane, Option)> { let n = picked.normal(); - // By name first: the face (or a piece of it) with that name, facing the same way. if let Some(name) = name { - // (distance from `at`, plane offset along n, what to say about how it was found) - let mut found: Option<(f64, f64, Option)> = None; - for b in st.bodies.iter().filter(|b| !b.body.is_mesh()) { - let named = crate::naming::faces_with_stem(b, name); - if named.is_empty() { - continue; - } - let tol = (b.body.size() * 1e-3).max(1e-3); - let Ok(faces) = b.body.faces(tol) else { continue }; - for f in faces { - let hit = named.contains(&f.index); - if let (true, Some(fnrm)) = (hit, f.plane_normal) - && fnrm.dot(n) > 1.0 - 1e-6 - { - let d = f.centroid.dist(at); - if found.as_ref().is_none_or(|x| d < x.0) { - // A name saved before format 14 is found as it was then, without a note. - let note = if crate::naming::legacy_name(name).is_some() { - None - } else if !crate::naming::face_has_name(b, f.index, name) { - Some(format!("face `{name}` was split; using the piece nearest the picked point")) - } else if !crate::naming::face_name_exact(b, f.index) && (f.centroid - at).dot(n).abs() > tol { - // Named from geometry and moved off the picked plane: geometry alone decided. - Some(format!("face `{name}` was found by geometry, not exact history; check it")) - } else { - None - }; - found = Some((d, f.centroid.dot(n), note)); - } - } - } + let hit = crate::naming::locate_face(st, name, at).ok_or_else(|| DocError::reselect(name))?; + let b = st.bodies.get(hit.body).ok_or_else(|| DocError::reselect(name))?; + let tol = (b.body.size() * 1e-3).max(1e-3); + let face = b.body.faces(tol)?.into_iter().find(|f| f.index == hit.face).ok_or_else(|| DocError::reselect(name))?; + if !face.plane_normal.is_some_and(|fnrm| fnrm.dot(n) > 1.0 - 1e-6) { + return Err(DocError::reselect(name)); } - if let Some((_, off, note)) = found { - return (picked.offset(off - picked.origin.dot(n)), note); - } - let (pl, w) = face_plane(st, picked, at, None); - let note = format!( - "the face `{name}` the sketch was on no longer exists; {}", - if w.is_some() { "the sketch stays where it was" } else { "using the face at the picked point" } - ); - return (pl, Some(note)); + let note = if !crate::naming::face_name_exact(b, hit.face) && (face.centroid - at).dot(n).abs() > tol { + // Named from geometry and moved off the picked plane: geometry alone decided. + Some(format!("face `{name}` was found by geometry, not exact history; check it")) + } else { + None + }; + return Ok((picked.offset(face.centroid.dot(n) - picked.origin.dot(n)), note)); } let mut best: Option<(f64, f64)> = None; // (distance from `at`, plane offset along n) for b in &st.bodies { @@ -6303,13 +6307,13 @@ fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> } } } - match best { + Ok(match best { Some((_, off)) => { let shift = off - picked.origin.dot(n); (picked.offset(shift), None) } None => (*picked, Some("the face the sketch was on is gone; the sketch stays where it was".into())), - } + }) } /// A chamfer, equal or by its second distance or angle. @@ -6403,7 +6407,7 @@ fn eval_feature( (None, plane) if crate::sheet::plane_sheet_face(plane).is_some() => { (doc.resolve_plane_in(vals, &sheet_face_plane_in_frame(doc, st, f.component, plane)?, 0, Some(&fst))?, None) } - (None, PlaneRef::Face { plane: picked, at, name, anchor: None }) => face_plane(&fst, picked, *at, name.as_deref()), + (None, PlaneRef::Face { plane: picked, at, name, anchor: None }) => face_plane(&fst, picked, *at, name.as_deref())?, (None, other) => (doc.resolve_plane_in(vals, other, 0, Some(&fst))?, None), }; let mut sk = sketch.clone(); @@ -6411,8 +6415,8 @@ fn eval_feature( // ones its expressions give come first. doc.apply_text_values(vals, &mut sk)?; let mut warns = match anchor { - Some(anchor) => crate::project::refresh_face_anchor_links(doc, vals, &fst, &plane, &mut sk, anchor), - None => crate::project::refresh_links(doc, vals, &fst, &plane, &mut sk), + Some(anchor) => crate::project::refresh_face_anchor_links(doc, vals, &fst, &plane, &mut sk, anchor)?, + None => crate::project::refresh_links(doc, vals, &fst, &plane, &mut sk)?, }; drop(fst); sk.refresh_offsets()?; @@ -7430,11 +7434,19 @@ pub fn face_point_state<'a>(doc: &Document, st: &'a ModelState, kind: &FeatureKi /// The names of the faces a feature's face points lie on (empty where none), found in /// [`face_point_state`]. A To / From point is named after the nearest face over every body, the /// one `object_height` resolves it to, not the first body with a face within tolerance: a part -/// resting a hair from the picked face would otherwise take its name. +/// resting a hair from the picked face would otherwise take its name. Another feature's point is +/// named on the bodies of the feature's own component first: each component's bodies lie in its +/// own coordinates there, where a part inserted twice has a face at the same point in each. pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, comp: u64) -> Result> { let pts = kind.face_points(); if !matches!(kind, FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. }) { - return Ok(crate::naming::face_names_at(st, &pts)); + let own = ModelState { bodies: st.bodies.iter().filter(|b| doc.model_body_component(b) == comp).cloned().collect(), ..ModelState::default() }; + let names = crate::naming::face_names_at(&own, &pts); + return Ok(names + .into_iter() + .zip(&pts) + .map(|(name, p)| if name.is_empty() { crate::naming::face_names_at(st, std::slice::from_ref(p)).pop().unwrap_or_default() } else { name }) + .collect()); } let fst = face_point_state(doc, st, kind, comp)?; let normal = match kind { @@ -8102,7 +8114,7 @@ mod named_face_lookup_tests { assert!(b.mesh.get().is_none(), "{} was meshed", b.name); } let h = hit.unwrap(); - assert_eq!((h.body, h.split, h.merged), (7, false, false)); + assert_eq!(h.body, 7); assert_eq!(found(hit), found(crate::naming::locate_face(&st, &name, top))); // Looking over every body names (and so meshes) them all. assert!(st.bodies.iter().all(|b| b.mesh.get().is_some())); @@ -8123,12 +8135,12 @@ mod named_face_lookup_tests { } } let moved = crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, top).unwrap(); - assert_eq!((moved.body, moved.split), (2, false)); + assert_eq!(moved.body, 2); } /// A copy of a body has its source's face names. Over every body the name finds the face on - /// both, and the one nearest the point is taken as a piece of a split face. A feature on the - /// copy takes the copy's face, whole. + /// both, and takes the one the point lies on; a point on neither finds no face (it is never + /// told apart by the nearest). A feature on the copy takes the copy's face. #[test] fn the_same_face_on_a_copy_is_not_a_piece_of_the_named_bodys_face() { let mut st = parts(2); @@ -8140,7 +8152,8 @@ mod named_face_lookup_tests { let on_copy = crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, top).unwrap(); let everywhere = crate::naming::locate_face(&st, &name, top).unwrap(); assert_eq!((on_copy.body, on_copy.face, on_copy.point), (everywhere.body, everywhere.face, everywhere.point)); - assert_eq!((on_copy.split, everywhere.split), (false, true)); assert_eq!(on_copy.note(&name), None); + assert!(crate::naming::locate_face(&st, &name, Vec3::new(15.0, 5.0, 30.0)).is_none()); + assert_eq!(crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, Vec3::new(15.0, 5.0, 30.0)).map(|hit| hit.body), Some(1)); } } diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 377bb8443..5cb0e12c5 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -44,17 +44,8 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, { let mut scoped = ModelState::default(); scoped.bodies.push(mb.clone()); - let (picked, split) = crate::naming::point_on_face(&scoped, name, at) - .ok_or_else(|| DocError::Invalid("selected cylinder face no longer exists".into()))?; - if split { - return Err(DocError::Invalid("selected cylinder face was split".into())); - } - let (index, _, _) = crate::project::nearest_face(&mb.mesh(), picked) - .ok_or_else(|| DocError::Invalid("selected cylinder face cannot be resolved".into()))?; - if !crate::naming::face_has_name(&mb, index as usize, name) { - return Err(DocError::Invalid("selected cylinder face is ambiguous".into())); - } - at = kernel::cylinder_emboss_anchor(&mb.body, index as usize, picked)?; + let hit = crate::name_lookup::locate_face(&scoped, name, at).ok_or_else(|| DocError::reselect(name.as_str()))?; + at = kernel::cylinder_emboss_anchor(&mb.body, hit.face, hit.point)?; } let result = kernel::emboss_cylinder_at(&mb.body, at, &plane, ®ions, if *deboss { -d } else { d })?; if let Some(slot) = st.bodies.get_mut(i) { @@ -759,21 +750,19 @@ pub(super) fn sheet_eval( let mb = st.body(body).cloned().ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; let r = doc.sheet_rule(rule.as_deref()); let values = |t: Option| doc.rule_values_at(vals, &r, t); - // The bend edges by name first; a name that is gone keeps its point, with a warning. + // The bend edges by name where they have one: a name that no longer finds its edge + // fails the conversion, asking for the edge to be picked again. let mut picks = Vec::with_capacity(bends.len()); for (i, p) in bends.iter().enumerate() { let name = f.edge_names.get(i).filter(|n| !n.is_empty()); - picks.push(match name.map(|n| (n, crate::naming::locate_edge(&mb, n, p.0))) { - Some((n, Ok(hit))) => { + picks.push(match name { + Some(n) => { + let hit = crate::naming::locate_edge(&mb, n, p.0).map_err(|_| DocError::reselect(n.as_str()))?; if let Some(note) = hit.note(n) { append_warning(warning, note); } hit.point } - Some((n, Err(_))) => { - append_warning(warning, format!("edge `{n}` no longer exists; using the edge at the picked point")); - p.0 - } None => p.0, }); } diff --git a/crates/doc/src/feature_geometry.rs b/crates/doc/src/feature_geometry.rs index 09a0a4881..dcf371050 100644 --- a/crates/doc/src/feature_geometry.rs +++ b/crates/doc/src/feature_geometry.rs @@ -55,7 +55,7 @@ impl FeatureKind { /// The body a feature that works on one body's faces names (shell, draft, split, offset, /// delete and replace face, surface offset, the placed plastic features, sheet metal - /// conversion, ruled surface): its face points pick faces of that body. + /// conversion, ruled surface, untrim): its face points pick faces of that body. pub fn face_body(&self) -> Option<&str> { match self { FeatureKind::Shell { body, .. } @@ -69,6 +69,7 @@ impl FeatureKind { | FeatureKind::SnapFit { body, .. } | FeatureKind::Rest { body, .. } => body.as_deref(), FeatureKind::SheetConvert { body, .. } | FeatureKind::SurfaceRuled { body, .. } => Some(body.as_ref()), + FeatureKind::SurfaceUntrim { face, .. } => Some(face.body.as_ref()), _ => None, } } diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 81e915599..043a5cba7 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -387,8 +387,8 @@ const JSON_STEPS: [JsonStep; HAND_WRITTEN as usize - 1] = [ ]; /// Stored face and edge names were worked out from geometry before format 14; they get the -/// legacy mark (`?`, see `naming::LEGACY_MARK`) so they are found again as those builds found -/// them, and an older design evaluates as it was saved. The step marks the fields that store +/// legacy mark (`?`, see `naming::LEGACY_MARK`), which finds no face or edge: a feature holding +/// one fails, asking for its reference to be picked again. The step marks the fields that store /// such a name, by their place in the schema: /// - each feature's `face_names`, and fillets' and chamfers' `edge_names` (other features' edge /// names are sheet metal's own); diff --git a/crates/doc/src/history_names.rs b/crates/doc/src/history_names.rs index 039ed4fbf..1bd4f8605 100644 --- a/crates/doc/src/history_names.rs +++ b/crates/doc/src/history_names.rs @@ -12,7 +12,10 @@ //! piece of `F2:top` bounded by the block's left wall and the slot's left wall. Pieces nothing //! around them tells apart are numbered (`#1`, `#2`): in the order of what they came from when //! that differs (exact), else in the kernel's order (unverified). A face made of several (a -//! coplanar join) takes one name and answers to the others (aliases). +//! coplanar join) takes one name and keeps the others as aliases: a reference to one of them is +//! to a face that is no longer as it was picked, and finds nothing. A face a feature built from +//! several of its own roles (a side drawn in collinear pieces) has each of them as a name +//! (synonyms): each names that very face. //! //! A piece that is split again keeps the face's stem and the bounds that told the piece it //! came from apart: its name lists the faces around it, not the qualifiers of the pieces @@ -38,8 +41,13 @@ pub struct Names { /// What a face answers to besides its name, and how sure its name is. #[derive(Clone, Debug, Default)] pub(crate) struct FaceInfo { - /// Names of the other faces merged into it (a reference to one of them finds this face). + /// Names of the other faces merged into it. A reference to one of them is to a face that is + /// not this one as it was picked: a feature's reference by one finds nothing (`name_lookup`). pub aliases: Vec, + /// Other names of this very face: the roles besides its first of a face the feature that + /// built it made from several (a side drawn in collinear pieces is one face, made by each). + /// A reference by one of them finds the face as its name does. + pub synonyms: Vec, /// The stems of the faces around it: what tells it apart from other pieces of its face. pub bounds: BTreeSet, /// Whether the name follows exact history (`false`: worked out from geometry, or a piece @@ -54,7 +62,7 @@ impl Names { pub(crate) fn unverified(names: Vec, adjacent: &[(usize, usize)], centres: Option<&dyn Fn() -> Vec>) -> Names { let named = names .into_iter() - .map(|name| Named { name: crate::naming::strip_piece(&name).to_string(), aliases: Vec::new(), verified: false, origins: None }) + .map(|name| Named { name: crate::naming::strip_piece(&name).to_string(), verified: false, ..Named::default() }) .collect(); qualify_at(named, adjacent, centres) } @@ -72,10 +80,11 @@ impl Names { } /// A face's name before pieces are told apart. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] struct Named { name: String, aliases: Vec, + synonyms: Vec, verified: bool, /// What it came from (`None`: not known): faces with one name but different origins (an /// extrude's two caps both above its sketch plane) are numbered in this order. @@ -96,7 +105,7 @@ pub(crate) fn derive(b: &ModelBody, o: &NamingOrigin, lineage: &Lineage) -> Opti let geometric = crate::naming::geometric_names(b, o, named.len()); for (slot, name) in named.iter_mut().zip(geometric) { if slot.is_none() { - *slot = Some(Named { name: crate::naming::strip_piece(&name).to_string(), aliases: Vec::new(), verified: false, origins: None }); + *slot = Some(Named { name: crate::naming::strip_piece(&name).to_string(), verified: false, ..Named::default() }); } } } @@ -161,35 +170,42 @@ impl<'a> OperandNames<'a> { fn face(&self, face: usize, fid: u64) -> Option { let given = |names: &Names| { let info = names.info.get(face)?; - Some(Named { name: names.faces.get(face)?.clone(), aliases: info.aliases.clone(), verified: info.verified, origins: None }) + Some(Named { + name: names.faces.get(face)?.clone(), + aliases: info.aliases.clone(), + synonyms: info.synonyms.clone(), + verified: info.verified, + origins: None, + }) }; match self.operand { Operand::Body(_) | Operand::Stage(_) => given(&self.names), - Operand::Copy { instance, .. } => given(&self.names).map(|n| Named { - name: format!("{}@F{fid}.{instance}", n.name), - aliases: n.aliases.iter().map(|a| format!("{a}@F{fid}.{instance}")).collect(), - verified: n.verified, - origins: None, - }), - Operand::Inner(_) => given(&self.names).map(|n| Named { - name: format!("F{fid}:inner:{}", n.name), - aliases: Vec::new(), - verified: n.verified, - origins: None, + Operand::Copy { instance, .. } => given(&self.names).map(|n| { + let copied = |names: &[String]| names.iter().map(|a| format!("{a}@F{fid}.{instance}")).collect(); + Named { + name: format!("{}@F{fid}.{instance}", n.name), + aliases: copied(&n.aliases), + synonyms: copied(&n.synonyms), + verified: n.verified, + origins: None, + } }), + Operand::Inner(_) => { + given(&self.names).map(|n| Named { name: format!("F{fid}:inner:{}", n.name), verified: n.verified, ..Named::default() }) + } Operand::Made(roles) => { let (first, rest) = roles.get(face)?.split_first()?; Some(Named { name: format!("F{fid}:{first}"), - aliases: rest.iter().map(|r| format!("F{fid}:{r}")).collect(), + synonyms: rest.iter().map(|r| format!("F{fid}:{r}")).collect(), verified: true, - origins: None, + ..Named::default() }) } Operand::CopiedTool { roles, feature, instance } => { let named = |role: &String| format!("F{feature}:{role}@F{fid}.{instance}"); let (first, rest) = roles.get(face)?.split_first()?; - Some(Named { name: named(first), aliases: rest.iter().map(named).collect(), verified: true, origins: None }) + Some(Named { name: named(first), synonyms: rest.iter().map(named).collect(), verified: true, ..Named::default() }) } } } @@ -219,11 +235,11 @@ fn from_origins(face: &FaceProv, operands: &[OperandNames], fid: u64) -> Option< FaceOrigin::Face { operand, face } => operands.get(operand)?.face(face, fid)?, FaceOrigin::Edge { operand, edge } => { let (edge, verified) = operands.get(operand)?.edge(edge)?; - Named { name: format!("F{fid}:blend:{edge}"), aliases: Vec::new(), verified, origins: None } + Named { name: format!("F{fid}:blend:{edge}"), verified, ..Named::default() } } FaceOrigin::Offset { operand, face } => { let source = operands.get(operand)?.face(face, fid)?; - Named { name: format!("F{fid}:inner:{}", source.name), aliases: Vec::new(), verified: source.verified, origins: None } + Named { name: format!("F{fid}:inner:{}", source.name), verified: source.verified, ..Named::default() } } // A profile or cap of a body made from nothing: only a built body's own roles name // these, and those come in as `Made` operands. @@ -237,7 +253,8 @@ fn from_origins(face: &FaceProv, operands: &[OperandNames], fid: u64) -> Option< } /// One name for a face made of faces with these names: the face they are all pieces of, else the -/// first (the target's before a tool's); the others become aliases. +/// first (the target's before a tool's); the others become aliases. The synonyms of the face +/// whose name it takes stay its synonyms. fn merged(names: Vec) -> Option { let verified = names.iter().all(|n| n.verified); let first = names.first()?.name.clone(); @@ -249,15 +266,21 @@ fn merged(names: Vec) -> Option { common = crate::naming::parent_piece(c); } let name = common_piece(&names).or_else(|| common.map(str::to_string)).unwrap_or(first); - let mut aliases: Vec = Vec::new(); + let (mut aliases, mut synonyms): (Vec, Vec) = (Vec::new(), Vec::new()); for n in names { - for alias in std::iter::once(n.name).chain(n.aliases) { + let (kept, merged) = if n.name == name { (n.synonyms, n.aliases) } else { (Vec::new(), [vec![n.name], n.synonyms, n.aliases].concat()) }; + for synonym in kept { + if synonym != name && !synonyms.contains(&synonym) { + synonyms.push(synonym); + } + } + for alias in merged { if alias != name && !aliases.contains(&alias) { aliases.push(alias); } } } - Some(Named { name, aliases, verified, origins: None }) + Some(Named { name, aliases, synonyms, verified, origins: None }) } /// The name the faces have in common: their stem, the faces their qualifiers share and the @@ -441,7 +464,12 @@ fn qualify_at(named: Vec, adjacent: &[(usize, usize)], centres: Option<&d } } } - let info = named.into_iter().zip(bounds).zip(verified).map(|((x, bounds), verified)| FaceInfo { aliases: x.aliases, bounds, verified }).collect(); + let info = named + .into_iter() + .zip(bounds) + .zip(verified) + .map(|((x, bounds), verified)| FaceInfo { aliases: x.aliases, synonyms: x.synonyms, bounds, verified }) + .collect(); Names { faces: Arc::new(names), info } } @@ -526,6 +554,10 @@ pub(crate) fn matches(names: &Names, index: usize, name: &str) -> Option if current == name { return Some(Match::Exact); } + // Another name of this very face; of a piece of it, when the face was split since. + if info.is_some_and(|i| i.synonyms.iter().any(|a| a == name)) { + return Some(if crate::naming::strip_piece(current) == current { Match::Exact } else { Match::Piece }); + } if info.is_some_and(|i| i.aliases.iter().any(|a| a == name)) { return Some(Match::Alias); } diff --git a/crates/doc/src/history_names_tests.rs b/crates/doc/src/history_names_tests.rs index 40972a26f..b9bbaaba0 100644 --- a/crates/doc/src/history_names_tests.rs +++ b/crates/doc/src/history_names_tests.rs @@ -23,7 +23,7 @@ fn piece_names_parse_into_stem_and_bounding_faces() { } fn named(names: &[&str]) -> Vec { - names.iter().map(|n| Named { name: n.to_string(), aliases: Vec::new(), verified: true, origins: None }).collect() + names.iter().map(|n| Named { name: n.to_string(), verified: true, ..Named::default() }).collect() } #[test] @@ -125,6 +125,28 @@ fn a_merged_face_takes_the_shared_stem_or_the_first_name_and_answers_to_the_othe assert_eq!(matches(&names, 0, "F9:top"), Some(Match::Alias)); } +/// A side drawn in two collinear pieces is one face its feature made from both: each piece's role +/// names that very face, a piece of it once it is split. Joined with another feature's face, it +/// keeps them, and the other face's names are aliases only. +#[test] +fn a_face_made_from_several_roles_is_named_by_each_and_keeps_them_when_merged() { + let side = Named { name: "F2:side:c1".into(), synonyms: vec!["F2:side:c2".into()], verified: true, ..Named::default() }; + let names = qualify(vec![side.clone()], &[]); + assert_eq!(names.faces[0], "F2:side:c1"); + assert_eq!(matches(&names, 0, "F2:side:c2"), Some(Match::Exact)); + let other = Named { name: "F9:side:a".into(), synonyms: vec!["F9:side:b".into()], verified: true, ..Named::default() }; + let m = merged(vec![side.clone(), other]).unwrap(); + assert_eq!((m.name.as_str(), m.synonyms.as_slice()), ("F2:side:c1", ["F2:side:c2".to_string()].as_slice())); + assert_eq!(m.aliases, vec!["F9:side:a".to_string(), "F9:side:b".to_string()]); + let names = qualify(vec![m], &[]); + assert_eq!(matches(&names, 0, "F2:side:c2"), Some(Match::Exact)); + assert_eq!(matches(&names, 0, "F9:side:b"), Some(Match::Alias)); + // Split by a cut: each piece is a piece of what either role names. + let names = qualify(vec![side.clone(), side, Named { name: "F4:side:x".into(), ..Named::default() }], &[(0, 2)]); + assert_eq!(names.faces[0], "F2:side:c1#[F4:side:x]"); + assert_eq!(matches(&names, 0, "F2:side:c2"), Some(Match::Piece)); +} + /// #3330: a linked design's faces are named after the names that design gave them, so what the /// name holds must mean nothing else in the assembly, while its pieces stay pieces. #[test] diff --git a/crates/doc/src/hole_reference.rs b/crates/doc/src/hole_reference.rs index 187a1971f..7dc682888 100644 --- a/crates/doc/src/hole_reference.rs +++ b/crates/doc/src/hole_reference.rs @@ -167,12 +167,16 @@ fn to_polyline(p: Vec3, e: &[Vec3]) -> f64 { e.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min) } -/// Reference edge `k` (its ends, and its index in the mesh), found by `name`, else by the edge -/// nearest `p`: one that runs through `p` for a fresh pick, within a quarter of the body for a -/// stored one. It must be straight. +/// Reference edge `k` (its ends, and its index in the mesh), found by `name` (a name that finds +/// no edge fails, asking for the edge to be picked again), else by the edge nearest `p`: one +/// that runs through `p` for a fresh pick, within a quarter of the body for a stored one. It +/// must be straight. fn find_edge(b: &ModelBody, m: &Mesh, k: usize, p: Vec3, name: Option<&str>, exact: bool) -> Result<(Vec3, Vec3, usize)> { let size = b.body.size().max(1e-9); - let by_name = name.filter(|n| !n.is_empty()).and_then(|n| crate::naming::locate_edge(b, n, p).ok()).map(|hit| hit.edge); + let by_name = match name.filter(|n| !n.is_empty()) { + Some(n) => Some(crate::naming::locate_edge(b, n, p).map_err(|_| DocError::reselect(n))?.edge), + None => None, + }; let i = match by_name { Some(i) => i, None => { diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rs index 8b1be1c6d..79c45141e 100644 --- a/crates/doc/src/joints_cam.rs +++ b/crates/doc/src/joints_cam.rs @@ -341,7 +341,7 @@ fn profile_points(doc: &Document, st: &ModelState, p: &CamProfile, cam: &super:: let (body, p) = bodies .iter() .enumerate() - .find_map(|(i, b)| crate::naming::find_edge(b, name, *pick).ok().map(|(p, _)| (i, p))) + .find_map(|(i, b)| crate::naming::find_edge(b, name, *pick).ok().map(|p| (i, p))) .ok_or_else(|| bad(&format!("the edge `{name}` no longer exists (edit the cam to pick again)")))?; (on, at) = (Some(body), p); } diff --git a/crates/doc/src/joints_edge.rs b/crates/doc/src/joints_edge.rs index afa006976..c2fd1ed7a 100644 --- a/crates/doc/src/joints_edge.rs +++ b/crates/doc/src/joints_edge.rs @@ -54,7 +54,7 @@ fn face_of(b: &ModelBody, i: usize, name: Option<&str>, pick: Vec3) -> Result<(u let planar = |f: usize| infos.iter().find(|x| x.index == f).and_then(|x| x.plane_normal.map(|n| (x.index, n, x.centroid, x.area))); let chosen = match name { Some(n) => { - let (f, _, _) = crate::naming::face_on_body(b, n, pick) + let (f, _) = crate::naming::face_on_body(b, n, pick) .ok_or_else(|| DocError::Invalid(format!("joint origin: the face `{n}` no longer exists (edit the joint to pick again)")))?; if !beside.contains(&f) { return Err(DocError::Invalid(format!("joint origin: the face `{n}` no longer meets its edge (edit the joint to pick again)"))); @@ -190,7 +190,7 @@ pub fn edge_snap(doc: &Document, st: &ModelState, comp: u64, pick: Vec3, on: Opt Some(p) => { let f = crate::naming::face_name_at_body(b, p) .and_then(|n| crate::naming::face_on_body(b, &n, p)) - .map(|(f, _, _)| f) + .map(|(f, _)| f) .ok_or_else(|| DocError::Invalid("joint origin: `on` is not on a face of that body".into()))?; if !beside.contains(&f) { return Err(DocError::Invalid("joint origin: `on` picks a face the edge doesn't bound".into())); diff --git a/crates/doc/src/joints_face.rs b/crates/doc/src/joints_face.rs index 18da16b76..91b5b0d1c 100644 --- a/crates/doc/src/joints_face.rs +++ b/crates/doc/src/joints_face.rs @@ -32,17 +32,16 @@ fn gone(name: &str) -> DocError { /// The face called `name` on the bodies of `component` nearest `pick` (an error when it is gone: /// a joint must not quietly attach elsewhere). Each body is looked at in its own coordinates, and -/// a face the name finds exactly comes before a piece of it or a face it was merged into. Only the -/// component's own bodies: the parts of one STEP import share their face names, and another +/// the nearest of the faces the name finds is taken. Only the component's own bodies: the parts of one STEP import share their face names, and another /// part's face of that name can lie nearer the pick than this part's own. pub(super) fn named_face<'a>(doc: &Document, st: &'a ModelState, component: u64, pick: Vec3, name: &str) -> Result> { let own = component_bodies(doc, st, component).into_iter().filter_map(|body| { let offset = doc.model_body_offset(body).copied().unwrap_or(IDENTITY); - let (face, at, inexact) = crate::naming::face_on_body(body, name, apply_point(&mat_inverse(&offset)?, pick))?; + let (face, at) = crate::naming::face_on_body(body, name, apply_point(&mat_inverse(&offset)?, pick))?; let point = apply_point(&offset, at); - Some(((inexact, point.dist(pick)), NamedFace { body, face, point, offset })) + Some((point.dist(pick), NamedFace { body, face, point, offset })) }); - if let Some((_, nf)) = own.min_by(|(a, _), (b, _)| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))) { + if let Some((_, nf)) = own.min_by(|(a, _), (b, _)| a.total_cmp(b)) { return Ok(nf); } // On none of them (the face's body has gone to another component since): wherever the name @@ -53,7 +52,7 @@ pub(super) fn named_face<'a>(doc: &Document, st: &'a ModelState, component: u64, return Ok(NamedFace { body, face: hit.face, point: hit.point, offset: IDENTITY }); }; let inv = mat_inverse(&offset).ok_or_else(|| gone(name))?; - let (face, at, _) = crate::naming::face_on_body(body, name, apply_point(&inv, pick)).ok_or_else(|| gone(name))?; + let (face, at) = crate::naming::face_on_body(body, name, apply_point(&inv, pick)).ok_or_else(|| gone(name))?; Ok(NamedFace { body, face, point: apply_point(&offset, at), offset }) } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index f51058bf1..7e43f91ba 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -103,6 +103,41 @@ pub enum DocError { Sketch(#[from] solidcraft_sketch::SketchError), #[error(transparent)] Kernel(#[from] solidcraft_kernel::KernelError), + /// A stored reference (a face or edge name, a piece of a split face) no longer finds exactly + /// what it named: the feature using it fails, and the user picks it again. `feature` is + /// empty until the evaluation of the feature fills it in ([`DocError::in_feature`]). + #[error("{}", reselect_message(feature, reference))] + Reselect { feature: String, reference: String }, +} + +impl DocError { + /// A feature's `reference` that no longer finds what it named ([`DocError::Reselect`]), for + /// the feature being evaluated. + pub fn reselect(reference: impl Into) -> Self { + DocError::Reselect { feature: String::new(), reference: reference.into() } + } + + /// This error, raised while feature `feature` was evaluated: a [`DocError::Reselect`] names it. + pub fn in_feature(self, feature: &str) -> Self { + match self { + DocError::Reselect { feature: f, reference } if f.is_empty() => DocError::Reselect { feature: feature.into(), reference }, + other => other, + } + } +} + +/// What a feature that lost a reference says ([`DocError::Reselect`]). +fn reselect_message(feature: &str, reference: &str) -> String { + let feature = if feature.is_empty() { "this feature" } else { feature }; + format!("{feature}: the reference `{reference}` no longer exists as it was picked; reselect it") +} + +/// The feature and the reference of a [`DocError::Reselect`] message, read back from its text +/// (a feature's error is kept as text): `None` for any other message. +pub fn reselect_parts(text: &str) -> Option<(&str, &str)> { + let (feature, rest) = text.split_once(": the reference `")?; + let reference = rest.strip_suffix("` no longer exists as it was picked; reselect it")?; + Some((feature, reference)) } pub type Result = std::result::Result; diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs index 35f9b3329..d0bd2014f 100644 --- a/crates/doc/src/model_cache.rs +++ b/crates/doc/src/model_cache.rs @@ -37,9 +37,8 @@ fn bad(what: &str) -> DocError { DocError::Invalid(what.into()) } -/// A design whose stored face or edge names were saved before format 14 (marked -/// [`crate::naming::LEGACY_MARK`]) finds them through names worked out from geometry on demand, -/// which a saved model does not keep. +/// A design holding a face or edge name saved before format 14 (marked +/// [`crate::naming::LEGACY_MARK`]): it saves without a model. fn has_legacy_names(doc: &Document) -> bool { let mark = format!("\"{}", crate::naming::LEGACY_MARK); doc.features.iter().any(|f| match &f.kind { @@ -122,7 +121,7 @@ impl Writer { return *i; } let names = crate::naming::names(b); - let info: Vec = names.info.iter().map(|i| json!([i.aliases, i.bounds, i.verified])).collect(); + let info: Vec = names.info.iter().map(|i| json!([i.aliases, i.bounds, i.verified, i.synonyms])).collect(); self.names.push(json!({"faces": *names.faces, "info": info})); self.names_index.insert(id, self.names.len() - 1); self.names.len() - 1 @@ -233,9 +232,10 @@ impl Model { } features.push(f); } + // The check mode the results were evaluated under: they are another mode's results. let records = json!({ "features": features, "states": w.states, "model_bodies": w.model_bodies, "names": w.names, "sketches": w.sketches, - "sheets": w.sheets, + "sheets": w.sheets, "validation": self.validation().id(), }); Ok(SavedModel { records, bodies: w.bodies }) }) @@ -257,12 +257,12 @@ impl SavedModel { let mut names = Vec::new(); for n in list("names")? { let faces: Vec = serde_json::from_value(parse(n.get("faces"))?).map_err(|_| bad("saved model: names"))?; - let info: Vec<(Vec, std::collections::BTreeSet, bool)> = + let info: Vec<(Vec, std::collections::BTreeSet, bool, Vec)> = serde_json::from_value(parse(n.get("info"))?).map_err(|_| bad("saved model: names"))?; if info.len() != faces.len() { return Err(bad("saved model: names")); } - let info = info.into_iter().map(|(aliases, bounds, verified)| FaceInfo { aliases, bounds, verified }).collect(); + let info = info.into_iter().map(|(aliases, bounds, verified, synonyms)| FaceInfo { aliases, synonyms, bounds, verified }).collect(); names.push(Arc::new(Names { faces: Arc::new(faces), info })); } let mut sketches = Vec::new(); @@ -541,6 +541,7 @@ impl SavedModel { let records = json!({ "features": out_features, "states": out_states, "model_bodies": out_bodies, "names": kept_of(names.as_slice(), &names_used), "sketches": kept_of(sketches.as_slice(), &sketches_used), "sheets": sheets, + "validation": self.records.get("validation").cloned().unwrap_or(Json::Null), }); let kept: Vec = (0..self.bodies.len()).filter(|i| kernel_used.get(*i) == Some(&true)).collect(); let bodies = kept.iter().filter_map(|i| self.bodies.get(*i).cloned()).collect(); @@ -551,8 +552,9 @@ impl SavedModel { impl Model { /// The model a design file kept for `doc` ([`Model::saved`]), taken as `doc`'s evaluation: /// every feature's result as saved, nothing evaluated but the features whose state the file - /// did not keep ([`SavedModel::thinned`]). Refused (an error) unless every feature's - /// fingerprint is the one `doc` gives it now, and every record is well formed. + /// did not keep ([`SavedModel::thinned`]), under the check mode it was evaluated in + /// ([`Model::validation`]). Refused (an error) unless every feature's fingerprint is the one + /// `doc` gives it now, and every record is well formed. pub fn adopt(doc: &Document, saved: &SavedModel) -> Result { let mut states = saved.states()?; let frame_bodies = Arc::new(std::sync::Mutex::new(FrameBodies::default())); @@ -566,13 +568,16 @@ impl Model { let text = |v: Option<&Json>| v.and_then(Json::as_str).filter(|s| s.len() <= 1 << 16).map(str::to_owned).ok_or_else(|| bad("saved model: text")); let features = records.get("features").and_then(Json::as_array).ok_or_else(|| bad("saved model: features"))?; + let validation = + records.get("validation").and_then(Json::as_str).and_then(kernel::Validation::parse).ok_or_else(|| bad("saved model: validation"))?; if features.len() != doc.features.len() { return Err(bad("saved model: features")); } let (vals, param_errors) = evaluation_values(doc); let step_digests = StepDigests::of(doc, &StepDigests::default()); let marker = doc.marker.unwrap_or(usize::MAX); - let ctx = context_digest(doc, &vals); + // As `evaluate` digests the context under the mode, so the next evaluation reuses these. + let ctx = context_digest(doc, &vals) ^ validation_digest(validation); let mut before = Arc::new(ModelState::default()); // Whether `before` is the state before the feature: one the file left out only stands in. let mut exact = true; @@ -614,7 +619,7 @@ impl Model { } results.push(result); } - let mut model = Model { results, param_errors, step_digests, context: ctx, frame_bodies, ..Model::default() }; + let mut model = Model { results, param_errors, step_digests, context: ctx, frame_bodies, validation, ..Model::default() }; let unkept = model.results.iter().filter(|r| r.unkept).count(); if unkept > 0 { // The features whose state the file did not keep, each evaluated again from the state diff --git a/crates/doc/src/name_lookup.rs b/crates/doc/src/name_lookup.rs index 8311c5a0e..ffe025f58 100644 --- a/crates/doc/src/name_lookup.rs +++ b/crates/doc/src/name_lookup.rs @@ -1,25 +1,27 @@ //! Finding a face or edge again by the name a feature stored for it. //! -//! The face with that name is the face; else the one face answering to it (a face merged into -//! it, or the named piece told apart by the faces around it, which still bound it); else, when -//! several faces are pieces of the named one, the piece nearest the reference's point, and the -//! feature says the face was split. Names saved before format 14 ([`LEGACY_MARK`]) are found -//! among the names geometry gives, as the builds that saved them found them. A face whose name -//! was worked out from geometry, found where the reference's point no longer lies, is reported: -//! only geometry decided. +//! The face with that name is the face (a face its feature made from several of its roles, a +//! side drawn in collinear pieces, has each as a name); else the one face answering to it as +//! exactly: the named piece told apart by the faces around it, which still bound it. Nothing +//! else is: when the named face was split into several pieces, when it was merged into another +//! face, when only a face of the same stem is left, when the name is on several bodies, or when +//! the name was saved before format 14 ([`LEGACY_MARK`]), the name finds nothing and the feature +//! that uses it fails, asking for the reference to be picked again +//! ([`crate::DocError::Reselect`]). A face whose name was worked out from geometry, found where +//! the reference's point no longer lies, is reported: only geometry decided. use solidcraft_geom::{Mesh, Vec3}; use crate::history_names::{Match, Names}; -use crate::naming::{self, closest, edge_names, face_names, legacy_edge_names, legacy_face_names, strip_piece}; -use crate::piece_names::{strip_edge_number, strip_edge_piece}; +use crate::naming::{self, closest, edge_names, face_names, strip_piece}; +use crate::piece_names::strip_edge_number; use crate::{ModelBody, ModelState}; /// The mark on a name saved before format 14 (`?F2:top#2`). Those names were worked out from -/// geometry, and a few of them name a face that exact history names differently (a tube's outer -/// wall was named after the nearest sketch curve to its centre, its inner circle): such a name is -/// found again among the names that geometry gives today, as the build that saved it did, so an -/// older design evaluates as it was saved. Picking the face again stores its exact name. +/// geometry, and some of them name a face that exact history names differently (a tube's outer +/// wall was named after the nearest sketch curve to its centre, its inner circle): such a name +/// finds no face, and the feature using it asks for the face to be picked again, which stores +/// its exact name. pub const LEGACY_MARK: char = '?'; /// A name saved before format 14, without its mark (`None`: an exact name). @@ -34,23 +36,19 @@ pub struct EdgeHit { pub edge: usize, /// A point on the edge: the reference's own point when it lies on it, else the edge's middle. pub point: Vec3, - /// The named edge is not one edge any more: the piece nearest the point was taken. - pub split: bool, /// Whether the names of the faces it separates follow exact history (and the edge is not /// one of several between them, numbered by where they lie). pub verified: bool, /// Whether the reference's point still lies on the edge. pub on_point: bool, - /// The name was saved before format 14 and found as that build did ([`LEGACY_MARK`]). - pub legacy: bool, } /// The edge of a body a stored edge name finds: the edge with that name; else the one edge -/// between the faces it names (followed through splits and merges of those faces); else the -/// piece of it nearest `near` (`split`). `Err` explains when there is none. +/// between the faces it names exactly (see [`exactly`]). `Err` explains when there is none: no +/// such edge, the named edge split into several, or a name saved before format 14. pub fn locate_edge(b: &ModelBody, name: &str, near: Vec3) -> Result { - if let Some(old) = legacy_name(name) { - return legacy_locate_edge(b, old, near).map_err(|_| format!("edge `{name}` no longer exists")); + if legacy_name(name).is_some() { + return Err(format!("edge `{name}` was named by a build before format 14")); } let m = b.mesh(); let names = edge_names(b); @@ -63,9 +61,7 @@ pub fn locate_edge(b: &ModelBody, name: &str, near: Vec3) -> Result Result { let on = edge_near(b, &m, i, near); - mid(i) - .map(|p| EdgeHit { edge: i, point: if on { near } else { p }, split: false, verified: verified(i), on_point: on, legacy: false }) - .ok_or_else(|| "edge".into()) + mid(i).map(|p| EdgeHit { edge: i, point: if on { near } else { p }, verified: verified(i), on_point: on }).ok_or_else(|| "edge".into()) }; if let Some(i) = names.iter().position(|n| n == name) { return exact(i); @@ -75,19 +71,22 @@ pub fn locate_edge(b: &ModelBody, name: &str, near: Vec3) -> Result)> = None; for (i, fs) in m.edge_faces.iter().enumerate() { let [fa, fb] = fs.as_slice() else { continue }; - let Some(level) = edge_match(&faces, *fa as usize, *fb as usize, wanted) else { continue }; + let Some(level) = edge_match(&faces, *fa as usize, *fb as usize, wanted).filter(|level| exactly(*level)) else { continue }; keep_best(&mut best, level, i); } - let (level, cands) = best.ok_or_else(|| format!("edge `{name}` no longer exists"))?; - if let ([i], true) = (cands.as_slice(), level >= Match::Piece) { - return exact(*i); + let (_, cands) = best.ok_or_else(|| format!("edge `{name}` no longer exists"))?; + match cands.as_slice() { + [i] => exact(*i), + _ => Err(format!("edge `{name}` is no longer one edge")), } - cands - .iter() - .filter_map(|i| mid(*i).map(|p| (p, *i))) - .min_by(|a, b| a.0.dist(near).total_cmp(&b.0.dist(near))) - .map(|(p, i)| EdgeHit { edge: i, point: p, split: true, verified: verified(i), on_point: false, legacy: false }) - .ok_or_else(|| format!("edge `{name}` no longer exists")) +} + +/// Whether a face found at `level` is exactly the face a name named: the very name (or another +/// name of that very face: a face its feature made from several roles has each), or the named +/// piece told apart by the faces around it. A face the named one was merged into, or a face of +/// the same stem, is not. +fn exactly(level: Match) -> bool { + matches!(level, Match::Exact | Match::Piece) } /// Whether the picked point `near` lies on edge `i` of body `b` (whose mesh is `m`): then a @@ -130,27 +129,6 @@ fn edge_mid(m: &Mesh, i: usize) -> Option { e.first().copied() } -/// [`locate_edge`] for a name saved before format 14 (without its mark), as those builds found -/// it: the edge with that name among the names geometry gives, else the piece of it nearest -/// `near`. -fn legacy_locate_edge(b: &ModelBody, name: &str, near: Vec3) -> Result { - let m = b.mesh(); - let names = legacy_edge_names(b); - if let Some(i) = names.iter().position(|n| n == name) { - let on = edge_near(b, &m, i, near); - return edge_mid(&m, i) - .map(|p| EdgeHit { edge: i, point: if on { near } else { p }, split: false, verified: false, on_point: on, legacy: true }) - .ok_or(()); - } - let stem = strip_edge_piece(name); - (0..names.len()) - .filter(|i| names.get(*i).is_some_and(|n| strip_edge_piece(n) == stem)) - .filter_map(|i| edge_mid(&m, i).map(|p| (p, i))) - .min_by(|a, b| a.0.dist(near).total_cmp(&b.0.dist(near))) - .map(|(p, i)| EdgeHit { edge: i, point: p, split: true, verified: false, on_point: false, legacy: true }) - .ok_or(()) -} - /// How well the stored edge name `wanted` (without its own number) names the edge between faces /// `a` and `b`: the weaker of its two faces' matches, read every way the name splits into two /// face names (a face name may hold `|` itself: a fillet face is named after its edge). @@ -185,32 +163,28 @@ pub struct FaceHit { pub face: usize, /// The point on the face nearest the reference's point. pub point: Vec3, - /// The named face is not one face any more (split, or found on several bodies): the piece - /// nearest the point was taken. - pub split: bool, - /// The named face was merged into this one. - pub merged: bool, /// Whether the face's name follows exact history. pub verified: bool, /// Whether the reference's point still lies on the face (so a name worked out from geometry /// and the pick agree). pub on_point: bool, - /// The name was saved before format 14 and found as that build did ([`LEGACY_MARK`]). - pub legacy: bool, +} + +/// Why a stored face name finds no face. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Miss { + /// No face has the name, or only a face it was merged into or a face of the same stem is + /// left, or the name was saved before format 14. + Gone, + /// Several faces answer to it as well: the pieces of a split face, or the same face on + /// several bodies. + Several, } impl FaceHit { /// What a feature says about how it found a face by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { - if self.split { - Some(format!("face `{name}` was split; using the piece nearest the picked point")) - } else if self.merged { - Some(format!("face `{name}` was merged into another face; using that face")) - } else if !self.verified && !self.on_point && !self.legacy { - Some(format!("face `{name}` was found by geometry, not exact history; check it")) - } else { - None - } + if !self.verified && !self.on_point { Some(format!("face `{name}` was found by geometry, not exact history; check it")) } else { None } } } @@ -316,176 +290,121 @@ fn inside_nearest(m: &Mesh, face: usize, p: Vec3, margin: f64) -> Option { impl EdgeHit { /// What a feature says about how it found an edge by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { - if self.split { - Some(format!("edge `{name}` was split; using the piece nearest the picked point")) - } else if !self.verified && !self.on_point && !self.legacy { - Some(format!("edge `{name}` was found by geometry, not exact history; check it")) - } else { - None - } + if !self.verified && !self.on_point { Some(format!("edge `{name}` was found by geometry, not exact history; check it")) } else { None } } } -/// The face a stored face name finds, on any body: the face with that name, or the one face -/// answering to it (merged into it, or the named piece told apart by the faces around it); else -/// the piece of it nearest `p` (`split`). +/// The face a stored face name finds, on any body: the face with that name, or the named piece +/// told apart by the faces around it. `None` when no face does, or several do. pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option { if crate::sheet::split_sheet_face_name(name).is_some() { - return sheet_locate(st, name, p); + return sheet_locate(st, name, p).ok(); + } + if legacy_name(name).is_some() { + return None; } // Every body's names are read below: work out the ones not known yet on all cores first // (each body's names are its own, whichever thread works them out). - if legacy_name(name).is_none() { - naming::warm_names(st.bodies.iter().filter(|b| !b.body.is_mesh())); - } - locate_in(st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()), name, p) + naming::warm_names(st.bodies.iter().filter(|b| !b.body.is_mesh())); + locate_in(st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()), name, p).ok() } /// [`locate_face`] for a feature that works on the faces of the body called `body` (a shell, a -/// draft…): the one face of that body with the very name, found without working out the names -/// of every other body (a body named from geometry is meshed for it: seconds in a large model). -/// Else as [`locate_face`], over every body: the name moved to another body (a combine took the -/// face), or on this body it names a piece of a split face or a merged one. The same face on -/// another body (a copy of this one) is not a piece of this body's face. +/// draft…): the face of that body the name finds, found without working out the names of every +/// other body (a body named from geometry is meshed for it: seconds in a large model). When +/// that body has no such face, as [`locate_face`] over every body: the name moved to another +/// body (a combine took the face). The same face on another body (a copy of this one) does not +/// make this body's face ambiguous. pub fn locate_face_on_body(st: &ModelState, body: Option<&str>, name: &str, p: Vec3) -> Option { - if crate::sheet::split_sheet_face_name(name).is_some() { - return sheet_locate(st, name, p); + if crate::sheet::split_sheet_face_name(name).is_some() || legacy_name(name).is_some() { + return locate_face(st, name, p); } - if legacy_name(name).is_none() - && let Some(i) = body.and_then(|n| st.bodies.iter().position(|b| b.name == n)) + if let Some(i) = body.and_then(|n| st.bodies.iter().position(|b| b.name == n)) && let Some(b) = st.bodies.get(i).filter(|b| !b.body.is_mesh()) - && let Some(hit) = locate_in(std::iter::once((i, b)), name, p) - && !hit.split - && naming::names(b).faces.get(hit.face).is_some_and(|n| n == name) { - return Some(hit); + match locate_in(std::iter::once((i, b)), name, p) { + Ok(hit) => return Some(hit), + Err(Miss::Several) => return None, + Err(Miss::Gone) => {} + } } locate_face(st, name, p) } /// [`locate_face`] for a sheet face's readable name (`sheet:::`, see -/// [`crate::sheet::body_sheet_face_names`]): the face of that body the sheet names so, else the -/// piece of it nearest `p` (`split`). The sheet itself says which face it is, so the name holds -/// however the faces of the body are numbered. -fn sheet_locate(st: &ModelState, name: &str, p: Vec3) -> Option { - let (body, _) = crate::sheet::split_sheet_face_name(name)?; - let (bi, b) = st.bodies.iter().enumerate().find(|(_, b)| b.name == body && !b.body.is_mesh())?; +/// [`crate::sheet::body_sheet_face_names`]): the face of that body the sheet names so. The sheet +/// itself says which face it is, so the name holds however the faces of the body are numbered. +fn sheet_locate(st: &ModelState, name: &str, p: Vec3) -> Result { + let (body, _) = crate::sheet::split_sheet_face_name(name).ok_or(Miss::Gone)?; + let (bi, b) = st.bodies.iter().enumerate().find(|(_, b)| b.name == body && !b.body.is_mesh()).ok_or(Miss::Gone)?; let names = crate::sheet::body_sheet_face_names(st, b); let faces: Vec = names.iter().enumerate().filter(|(_, n)| n.as_deref() == Some(name)).map(|(i, _)| i).collect(); - let m = b.mesh(); - let (distance, face, point) = - faces.iter().filter_map(|f| nearest_on_face(&m, *f, p).map(|(d, q)| (d, *f, q))).min_by(|a, c| a.0.total_cmp(&c.0))?; - Some(FaceHit { - body: bi, - face, - point, - split: faces.len() > 1, - merged: false, - verified: true, - on_point: distance <= (b.body.size() * 1e-3).max(1e-3), - legacy: false, - }) + let face = match faces.as_slice() { + [face] => *face, + [] => return Err(Miss::Gone), + _ => return Err(Miss::Several), + }; + let (distance, point) = nearest_on_face(&b.mesh(), face, p).ok_or(Miss::Gone)?; + Ok(FaceHit { body: bi, face, point, verified: true, on_point: distance <= (b.body.size() * 1e-3).max(1e-3) }) } -/// [`locate_face`] among `bodies` (with their indices). -fn locate_in<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Option { - if let Some(old) = legacy_name(name) { - return legacy_locate(bodies, old, p); +/// [`locate_face`] among `bodies` (with their indices): the one face the name finds there. +fn locate_in<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Result { + if legacy_name(name).is_some() { + return Err(Miss::Gone); } let mut best: Option<(Match, Vec<(usize, &ModelBody, usize)>)> = None; for (bi, b) in bodies { let names = naming::names(b); for face in 0..names.faces.len() { - if let Some(level) = crate::history_names::matches(&names, face, name) { + if let Some(level) = crate::history_names::matches(&names, face, name).filter(|level| exactly(*level)) { keep_best(&mut best, level, (bi, b, face)); } } } - let (level, faces) = best?; - let unique = faces.len() == 1 && level >= Match::Piece; - let mut nearest: Option<(f64, usize, &ModelBody, usize, Vec3)> = None; - for (bi, b, face) in faces { - if let Some((d, q)) = nearest_on_face(&b.mesh(), face, p) - && nearest.as_ref().is_none_or(|n| d < n.0) - { - nearest = Some((d, bi, b, face, q)); - } - } - let (distance, body, b, face, point) = nearest?; - let on_point = distance <= (b.body.size() * 1e-3).max(1e-3); - Some(FaceHit { - body, - face, - point, - split: !unique, - merged: level == Match::Alias, - verified: naming::names(b).verified(face), - on_point, - legacy: false, - }) -} - -/// [`locate_face`] for a name saved before format 14 (without its mark), as those builds found -/// it: among the names geometry gives, the face with that name (or a piece of the same face, if -/// nearer `p`), the nearest point on it. -fn legacy_locate<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Option { - let stem = strip_piece(name); - let mut best: Option<(f64, usize, usize, Vec3, bool, f64)> = None; - for (bi, b) in bodies { - let names = legacy_face_names(b); - let tol = (b.body.size() * 1e-3).max(1e-3); - let m = b.mesh(); - for (t, f) in m.triangles.iter().zip(&m.tri_face) { - let Some(n) = names.get(*f as usize) else { continue }; - let exact = n == name; - if !exact && strip_piece(n) != stem { - continue; - } - let Some([a, bb, c]) = m.tri(t) else { continue }; - let q = closest(p, a, bb, c); - let d = q.dist(p) - if exact { 1e-9 } else { 0.0 }; - if d.is_finite() && best.is_none_or(|x| d < x.0) { - best = Some((d, bi, *f as usize, q, !exact, tol)); - } - } - } - best.map(|(d, body, face, point, split, tol)| FaceHit { - body, - face, - point, - split, - merged: false, - verified: false, - on_point: d <= tol, - legacy: true, - }) -} - -/// Whether face `index` of a body is the face a stored name names: that name (or one merged into -/// it); for a name saved before format 14, that name among the names those builds gave. -pub fn face_has_name(b: &ModelBody, index: usize, name: &str) -> bool { - match legacy_name(name) { - Some(old) => legacy_face_names(b).get(index).is_some_and(|n| n == old), - None => crate::history_names::matches(&naming::names(b), index, name).is_some_and(|m| m >= Match::Alias), - } -} - -/// The faces of a body that are the stored name's face or pieces of it (by stem), as the name's -/// own era names them. -pub fn faces_with_stem(b: &ModelBody, name: &str) -> Vec { - let (names, wanted) = match legacy_name(name) { - Some(old) => (legacy_face_names(b), old), - None => (face_names(b), name), + let (level, faces) = best.ok_or(Miss::Gone)?; + let found = |(body, b, face): (usize, &ModelBody, usize)| { + let (distance, point) = nearest_on_face(&b.mesh(), face, p)?; + Some(FaceHit { body, face, point, verified: naming::names(b).verified(face), on_point: distance <= (b.body.size() * 1e-3).max(1e-3) }) }; - let stem = strip_piece(wanted); - let aliases = - |i: usize| legacy_name(name).is_none() && naming::names(b).info.get(i).is_some_and(|x| x.aliases.iter().any(|a| strip_piece(a) == stem)); + if let [one] = faces.as_slice() { + return found(*one).ok_or(Miss::Gone); + } + // The very face on several bodies (a body and its copies, whose faces keep their names): the + // one the reference's point lies on. Pieces of one face are never told apart by a point. + let mut bodies: Vec = faces.iter().map(|(bi, _, _)| *bi).collect(); + bodies.dedup(); + if level != Match::Exact || bodies.len() < faces.len() { + return Err(Miss::Several); + } + let mut on = faces.into_iter().filter_map(found).filter(|hit| hit.on_point); + match (on.next(), on.next()) { + (Some(hit), None) => Ok(hit), + _ => Err(Miss::Several), + } +} + +/// Whether face `index` of a body is exactly the face a stored name names (see [`exactly`]). A +/// name saved before format 14 names no face. +pub fn face_has_name(b: &ModelBody, index: usize, name: &str) -> bool { + legacy_name(name).is_none() && crate::history_names::matches(&naming::names(b), index, name).is_some_and(exactly) +} + +/// The faces of a body that are the stored name's face or pieces of it (by stem). A name saved +/// before format 14 has none. +pub fn faces_with_stem(b: &ModelBody, name: &str) -> Vec { + if legacy_name(name).is_some() { + return Vec::new(); + } + let names = face_names(b); + let stem = strip_piece(name); + let aliases = |i: usize| naming::names(b).info.get(i).is_some_and(|x| x.synonyms.iter().chain(&x.aliases).any(|a| strip_piece(a) == stem)); (0..names.len()).filter(|i| names.get(*i).is_some_and(|n| strip_piece(n) == stem) || aliases(*i)).collect() } /// [`locate_face`] on one body. pub(crate) fn locate_on(body: &ModelBody, name: &str, p: Vec3) -> Option { - locate_in(std::iter::once((0, body)), name, p) + locate_in(std::iter::once((0, body)), name, p).ok() } /// The one face a name `model.faces` lists finds, on the body called `body` or, without one, on @@ -502,11 +421,10 @@ pub fn locate_one(st: &ModelState, body: Option<&str>, name: &str) -> Result format!("no face is named `{name}` (`model.faces` lists the names)"), + Miss::Several => format!("`{name}` names more than one face (pieces of a split face): give the name of one piece"), + }); } let bodies: Vec<(usize, &ModelBody)> = st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh() && body.is_none_or(|n| b.name == n)).collect(); @@ -514,11 +432,10 @@ pub fn locate_one(st: &ModelState, body: Option<&str>, name: &str) -> Result 1 && legacy_name(name).is_none() { naming::warm_names(bodies.iter().map(|(_, b)| *b)); } - let hit = locate_in(bodies.into_iter(), name, Vec3::ZERO).ok_or_else(|| format!("no face is named `{name}` (`model.faces` lists the names)"))?; - if hit.split { - return Err(format!( - "`{name}` names more than one face (pieces of a split face, or faces of several bodies): give `body`, or the name of one piece" - )); - } - Ok(hit) + locate_in(bodies.into_iter(), name, Vec3::ZERO).map_err(|miss| match miss { + Miss::Gone => format!("no face is named `{name}` (`model.faces` lists the names)"), + Miss::Several => { + format!("`{name}` names more than one face (pieces of a split face, or faces of several bodies): give `body`, or the name of one piece") + } + }) } diff --git a/crates/doc/src/named_projection_tests.rs b/crates/doc/src/named_projection_tests.rs index 4adae985d..f2de76196 100644 --- a/crates/doc/src/named_projection_tests.rs +++ b/crates/doc/src/named_projection_tests.rs @@ -28,7 +28,7 @@ fn named_manual_projection_keeps_its_body_and_face_at_shared_boundaries() { sketch.links[0].source = LinkSource::Face { body: "Source".into(), at: Vec3::new(0., 0., 10.) }; let mut current = ModelState::default(); current.bodies.extend([named_box("Source", 20., 20.), named_box("Control", 5., 10.)]); - assert!(crate::project::refresh_links(&doc, &BTreeMap::new(), ¤t, &plane, &mut sketch).is_empty()); + assert!(crate::project::refresh_links(&doc, &BTreeMap::new(), ¤t, &plane, &mut sketch).unwrap().is_empty()); assert!(!sketch.links[0].lost); assert!(sketch.points.iter().any(|point| point.pos.x > 19.)); assert!(sketch.points.iter().any(|point| point.pos.y > 19.)); @@ -40,9 +40,9 @@ fn named_manual_projection_keeps_its_body_and_face_at_shared_boundaries() { let saved = sketch.clone(); let mut missing = ModelState::default(); missing.bodies.push(named_box("Control", 5., 10.)); - let warnings = crate::project::refresh_links(&doc, &BTreeMap::new(), &missing, &plane, &mut sketch); - assert!(sketch.links[0].lost); - assert!(!warnings.is_empty()); + // Its body gone, the named face finds nothing: the sketch fails, asking for it again. + let error = crate::project::refresh_links(&doc, &BTreeMap::new(), &missing, &plane, &mut sketch).unwrap_err(); + assert!(matches!(&error, crate::DocError::Reselect { reference, .. } if reference == "shared:top"), "{error}"); assert_eq!(sketch.curves, saved.curves); assert_eq!(sketch.points, saved.points); assert_eq!(sketch.links[0].id, link); diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 445e22dad..96a59e0e2 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -42,9 +42,7 @@ pub struct NameCell { /// What the body's faces came from, when the feature that made it reports it. lineage: Option>, names: Arc>>, - /// The names designs saved before format 14 gave its faces (see [`LEGACY_MARK`]). - legacy: Arc>>>, - /// The body this one is a moved copy of (its legacy names are that body's). + /// The body this one is a moved copy of (its names are that body's). copy_of: Option>, /// How deep the chain of features that named it is, for names taken from a saved model /// (which has no origin): see [`NameCell::depth`]. @@ -57,15 +55,11 @@ impl NameCell { } /// Names of a body made by `origin`'s feature, following `lineage` where it is known. pub(crate) fn traced(origin: Option>, lineage: Option>) -> Self { - NameCell { origin, lineage, names: Arc::new(OnceLock::new()), legacy: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None } + NameCell { origin, lineage, names: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None } } /// Names already known, taken as they are. pub fn known(names: Arc>) -> Self { - let legacy = OnceLock::new(); - let _ = legacy.set(names.clone()); - let mut cell = Self::shared(Arc::new(Names::given(names))); - cell.legacy = Arc::new(legacy); - cell + Self::shared(Arc::new(Names::given(names))) } /// The names of `body` (a moved copy of a body keeps its faces' names, and how sure they are). /// @@ -102,7 +96,7 @@ impl NameCell { fn shared(names: Arc) -> Self { let cell = OnceLock::new(); let _ = cell.set(names); - NameCell { origin: None, lineage: None, names: Arc::new(cell), legacy: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None } + NameCell { origin: None, lineage: None, names: Arc::new(cell), copy_of: None, saved_depth: None } } } @@ -166,7 +160,7 @@ const MAX_DEPTH: usize = 400; const SAMPLES: usize = 9; /// Up to this many sample points per face where a sheet's panel kept in place names the face it is -/// part of (see [`geometric_from`]). +/// part of (see [`geometric_names`]). const PANEL_SAMPLES: usize = 256; /// Unit normals of each face's triangles. @@ -323,8 +317,8 @@ pub fn blend_seams(b: &ModelBody) -> Vec { // Per face: the names it answers to, and the edges a blend face replaced (each as // `|`, without qualifiers or numbers). let all = |i: usize| -> Vec<&str> { - let aliases = n.info.get(i).map(|f| f.aliases.as_slice()).unwrap_or_default(); - n.faces.get(i).map(String::as_str).into_iter().chain(aliases.iter().map(String::as_str)).collect() + let (aliases, synonyms) = n.info.get(i).map(|f| (f.aliases.as_slice(), f.synonyms.as_slice())).unwrap_or_default(); + n.faces.get(i).map(String::as_str).into_iter().chain(synonyms.iter().chain(aliases).map(String::as_str)).collect() }; let replaced: Vec> = (0..n.faces.len()) .map(|i| { @@ -420,35 +414,6 @@ pub(crate) fn names(b: &ModelBody) -> Arc { .clone() } -/// The names builds before format 14 gave a body's faces: from geometry, over the inputs' names -/// as those builds gave them, pieces of a split face numbered along the longest axis of their -/// spread (`#1`, `#2`, …). -pub(crate) fn legacy_face_names(b: &ModelBody) -> Arc> { - if let Some(source) = &b.names.copy_of { - return legacy_face_names(source); - } - b.names - .legacy - .get_or_init(|| { - let nf = face_count(b); - let names = match b.names.origin.as_ref() { - Some(o) if o.depth < MAX_DEPTH => { - let mut names = geometric_from(b, o, nf, legacy_face_names); - number_pieces(&mut names, &samples(&b.mesh(), nf), '#'); - names - } - _ => (0..nf).map(|k| format!("{}:face:{k}", b.name)).collect(), - }; - Arc::new(names) - }) - .clone() -} - -/// The names builds before format 14 gave a body's edges. -pub(crate) fn legacy_edge_names(b: &ModelBody) -> Vec { - edge_names_from(b, &legacy_face_names(b)) -} - /// Pairs of faces of a body that share an edge (from its mesh's edges). pub(crate) fn mesh_adjacency(b: &ModelBody) -> Vec<(usize, usize)> { crate::history_names::face_pairs(b.mesh().edge_faces.iter().map(|fs| fs.iter().map(|f| *f as usize))) @@ -458,17 +423,12 @@ pub(crate) fn mesh_adjacency(b: &ModelBody) -> Vec<(usize, usize)> { /// geometry: where each face's sample points lie on the input's faces. Faces sharing a name are /// pieces of one, told apart afterwards. pub(crate) fn geometric_names(b: &ModelBody, o: &NamingOrigin, nf: usize) -> Vec { - geometric_from(b, o, nf, face_names) -} - -/// [`geometric_names`], the input bodies' faces named by `names_of`. -fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&ModelBody) -> Arc>) -> Vec { // A rigid Move changes coordinates, not topology or face ownership. Geometric // overlap with the unmoved input cannot recover the names at the new position. if matches!(o.feature.kind, FeatureKind::Move { .. }) && let Some(input) = o.before.body(&b.name) { - return names_of(input).as_ref().clone(); + return face_names(input).as_ref().clone(); } let m = b.mesh(); let size = b.body.size().max(1e-6); @@ -505,7 +465,7 @@ fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&Mode .take(64) .map(|x| { let n = face_count(x); - (x, FaceIndex::new(&x.mesh(), n), names_of(x)) + (x, FaceIndex::new(&x.mesh(), n), face_names(x)) }) .collect(); let fid = o.feature.id; @@ -520,7 +480,7 @@ fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&Mode .iter() .filter(|x| !x.body.is_mesh()) .take(64) - .map(|x| (x, FaceIndex::new(&x.mesh(), face_count(x)), names_of(x))) + .map(|x| (x, FaceIndex::new(&x.mesh(), face_count(x)), face_names(x))) .collect(); let mut best: Option<(usize, usize, Vec>)> = None; for (k, mat) in o.mats.iter().enumerate() { @@ -939,10 +899,10 @@ fn edge_names_from(b: &ModelBody, faces: &[String]) -> Vec { names } -/// The edge of a body with this name: exact, else the pieces of the same edge nearest `near` -/// (`Err` explains when there is none). -pub fn find_edge(b: &ModelBody, name: &str, near: Vec3) -> Result<(Vec3, bool), String> { - locate_edge(b, name, near).map(|hit| (hit.point, hit.split)) +/// A point on the edge of a body this name finds (see [`locate_edge`]; `Err` explains when there +/// is none). +pub fn find_edge(b: &ModelBody, name: &str, near: Vec3) -> Result { + locate_edge(b, name, near).map(|hit| hit.point) } /// Names of the edges nearest each point on a body (for storing references). @@ -1100,21 +1060,20 @@ pub fn named_face_point(st: &ModelState, body: Option<&str>, name: &str) -> Resu face_spot(b, hit.face).map(|spot| spot.point).ok_or_else(|| format!("face `{name}` has no surface to pick")) } -/// The point on the face with this name nearest `p` (a split face: its nearest piece, with -/// `true` for "not exactly that face": split, or merged into another); `None` when no face has -/// the name. -pub fn point_on_face(st: &ModelState, name: &str, p: Vec3) -> Option<(Vec3, bool)> { - locate_face(st, name, p).map(|hit| (hit.point, hit.split || hit.merged)) +/// The point on the face this name finds nearest `p`; `None` when the name finds no face (see +/// [`locate_face`]). +pub fn point_on_face(st: &ModelState, name: &str, p: Vec3) -> Option { + locate_face(st, name, p).map(|hit| hit.point) } /// Resolve a legacy named face only on its recorded source body. Return the /// selected face index as well as the closest point, which may lie on a shared /// edge and therefore must not be used to pick the face a second time. -pub fn face_on_body(body: &ModelBody, name: &str, p: Vec3) -> Option<(usize, Vec3, bool)> { +pub fn face_on_body(body: &ModelBody, name: &str, p: Vec3) -> Option<(usize, Vec3)> { if body.body.is_mesh() { return None; } - crate::name_lookup::locate_on(body, name, p).map(|hit| (hit.face, hit.point, hit.split || hit.merged)) + crate::name_lookup::locate_on(body, name, p).map(|hit| (hit.face, hit.point)) } #[cfg(test)] @@ -1140,7 +1099,7 @@ mod tests { fn same_hit(a: &FaceHit, b: &FaceHit) { assert_eq!((a.body, a.face, a.point), (b.body, b.face, b.point)); - assert_eq!((a.split, a.merged, a.verified, a.on_point, a.legacy), (b.split, b.merged, b.verified, b.on_point, b.legacy)); + assert_eq!((a.verified, a.on_point), (b.verified, b.on_point)); } #[test] diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index a50ff5622..e629aa024 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -600,20 +600,24 @@ pub fn resolved_edge_name(st: &ModelState, r: &Resolved) -> Option { crate::naming::edge_names(body).get(index).filter(|name| !name.is_empty()).cloned() } -/// Re-resolve every link of a sketch (in place). Returns warnings for lost, moved or rebuilt -/// links; lost links keep their last geometry. fn lost(reference: &str) -> DocError { DocError::Unknown(format!("{reference} no longer exists")) } /// The edge a link's stored name finds, and the body it is on: the link's body, or, when no -/// body has that name any more (it was joined into another), the body on which the name finds -/// the edge nearest the link's point. +/// body has that name any more (it was joined into another), the one body on which the name +/// finds an edge. fn locate_named_edge(st: &ModelState, body: &str, name: &str, at: Vec3) -> Option<(String, crate::naming::EdgeHit)> { let hit = |b: &crate::ModelBody| crate::naming::locate_edge(b, name, at).ok().map(|hit| (b.name.clone(), hit)); match st.body(body) { Some(b) => hit(b), - None => st.bodies.iter().filter(|b| !b.body.is_mesh()).filter_map(hit).min_by(|a, b| a.1.point.dist(at).total_cmp(&b.1.point.dist(at))), + None => { + let mut found = st.bodies.iter().filter(|b| !b.body.is_mesh()).filter_map(hit); + match (found.next(), found.next()) { + (Some(one), None) => Some(one), + _ => None, + } + } } } @@ -752,6 +756,7 @@ pub fn resolve_face_indices(st: &ModelState, plane: &Plane, kind: LinkKind, body }) } +/// [`refresh_links`] for a sketch attached to a face by `anchor`. pub fn refresh_face_anchor_links( doc: &Document, vals: &BTreeMap, @@ -759,7 +764,7 @@ pub fn refresh_face_anchor_links( plane: &Plane, sk: &mut Sketch, anchor: &crate::FaceAnchor, -) -> Vec { +) -> Result> { refresh_links_in(doc, vals, st, plane, sk, Some(anchor)) } @@ -832,7 +837,11 @@ fn merge_family_lines(geom: Vec) -> Result> { Ok(result) } -pub fn refresh_links(doc: &Document, vals: &BTreeMap, st: &ModelState, plane: &Plane, sk: &mut Sketch) -> Vec { +/// Re-resolve every link of a sketch (in place). Returns warnings for lost, moved or rebuilt +/// links; lost links keep their last geometry. A link kept by the name of a face or edge that no +/// longer finds exactly that face or edge is not lost: the sketch fails, asking for the +/// reference to be picked again ([`DocError::Reselect`]). +pub fn refresh_links(doc: &Document, vals: &BTreeMap, st: &ModelState, plane: &Plane, sk: &mut Sketch) -> Result> { refresh_links_in(doc, vals, st, plane, sk, None) } @@ -869,7 +878,7 @@ fn refresh_links_in( plane: &Plane, sk: &mut Sketch, anchor: Option<&crate::FaceAnchor>, -) -> Vec { +) -> Result> { let mut warn = Vec::new(); let links = sk.links.clone(); for l in &links { @@ -878,45 +887,18 @@ fn refresh_links_in( if !l.auto_face && let (Some(name), LinkSource::Face { body, at }) = (&l.face_name, &mut source) { - if let Some((index, p, split)) = st.body(body).and_then(|target| crate::naming::face_on_body(target, name, *at)) { - let stem = crate::naming::strip_piece(name); - let removed_piece = split - && name != stem - && st.body(body).is_some_and(|target| { - (certified_planar_construction(target, index) || target.body.face_was_coalesced(index)) - && crate::naming::face_has_name(target, index, stem) - }); - if removed_piece { - sk.set_link_lost(&l.id, true); - warn.push(format!("projected face piece `{name}` no longer exists; last geometry retained")); - continue; - } - *at = p; - named_face = Some((body.clone(), index, p)); - if split { - warn.push(format!("projected face `{name}` was split; using the nearest piece")); - } - } else { - sk.set_link_lost(&l.id, true); - warn.push(format!("projected face `{name}` no longer exists")); - continue; - } + let (index, p) = + st.body(body).and_then(|target| crate::naming::face_on_body(target, name, *at)).ok_or_else(|| DocError::reselect(name.as_str()))?; + *at = p; + named_face = Some((body.clone(), index, p)); } // An edge the link keeps by name is that edge of its body, wherever it went. When no - // edge has the name any more the link is lost: no other edge is taken for it. + // edge has the name any more no other edge is taken for it: the sketch fails. let mut named_edge = None; if let (Some(name), LinkSource::Edge { body, at }) = (&l.edge_name, &source) { - match locate_named_edge(st, body, name, *at) { - Some((body, hit)) => { - warn.extend(hit.note(name).map(|note| format!("projected {note}"))); - named_edge = Some((body, hit.edge, *at)); - } - None => { - sk.set_link_lost(&l.id, true); - warn.push(format!("projected reference lost: edge `{name}` no longer exists; last geometry retained")); - continue; - } - } + let (body, hit) = locate_named_edge(st, body, name, *at).ok_or_else(|| DocError::reselect(name.as_str()))?; + warn.extend(hit.note(name).map(|note| format!("projected {note}"))); + named_edge = Some((body, hit.edge, *at)); } let resolved = if matches!(source, LinkSource::Text { .. }) { // A text needs nothing outside its sketch; one on a path follows a curve of it. @@ -974,7 +956,7 @@ fn refresh_links_in( } } } - warn + Ok(warn) } // --------------------------------------------------------------------------------------------- diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 8731e71cb..02f542019 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -1168,12 +1168,17 @@ fn prism_edge_in_a_round_cornered_slab_end_face_joins() { /// of the bodies as they lie left the hole closed by a skin of no thickness (the plate's top face /// whole over the hole, the tool's end face under it), which no volume shows and which was kept. /// The hole is open, and the cut takes the whole tool: the circle of radius 3.04 the two -/// profiles make, from the barrel cut's floor at z 1.6 up to the plate's top at z 2.8. +/// profiles make, from the barrel cut's floor at z 1.6 up to the plate's top at z 2.8. The design +/// was saved by an older build: Extrude13 starts from a piece of a face that is no longer that +/// piece, so it fails, asking for its face again; the rest builds. #[test] fn cut_up_to_the_plate_top_face_opens_the_hole() { let mut script: Value = serde_json::from_str(include_str!("../../../examples/regressions/cut_up_to_face_leaves_skin.json")).unwrap(); let s = replay_value(&script); - assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let failed = + |r: &solidcraft_doc::FeatureResult| r.error.as_deref().and_then(solidcraft_doc::reselect_parts).map(|(feature, _)| feature.to_string()); + assert!(s.model.results.iter().all(|r| r.error.is_none() || failed(r).as_deref() == Some("Extrude13")), "{:?}", s.model.results); + assert!(s.model.results.iter().any(|r| failed(r).as_deref() == Some("Extrude13"))); let state = s.model.state(); let body = &state.body("Body7").unwrap().body; assert!(body.validity().is_empty(), "{:?}", body.validity()); diff --git a/crates/engine/src/cmd/component_clone.rs b/crates/engine/src/cmd/component_clone.rs index 5e0b9e5dc..55c84e18c 100644 --- a/crates/engine/src/cmd/component_clone.rs +++ b/crates/engine/src/cmd/component_clone.rs @@ -498,7 +498,6 @@ pub(super) fn paste( } if let Some(name) = &face.name { face.point = solidcraft_doc::naming::point_on_face(&state, name, face.point) - .map(|(point, _)| point) .ok_or_else(|| bad(CMD, "source frozen face appearance lost its identity"))?; } let source_body = state.body(&face.body).ok_or_else(|| bad(CMD, "source frozen face appearance lost its body"))?; diff --git a/crates/engine/src/cmd/component_clone_tests.rs b/crates/engine/src/cmd/component_clone_tests.rs index b817a4e7c..b879f2d3f 100644 --- a/crates/engine/src/cmd/component_clone_tests.rs +++ b/crates/engine/src/cmd/component_clone_tests.rs @@ -479,7 +479,7 @@ fn transferred_frozen_face_paint_ignores_consumed_legacy_offset() { let part = component(&mut s, "Part"); run(&mut s, "component.move_bodies", json!({"component":part,"bodies":["Foreign"]})); let original = s.doc.appearances.faces.iter().find(|face| face.body == "Foreign").unwrap(); - let expected = solidcraft_doc::naming::point_on_face(&s.model.state(), original.name.as_ref().unwrap(), original.point).unwrap().0; + let expected = solidcraft_doc::naming::point_on_face(&s.model.state(), original.name.as_ref().unwrap(), original.point).unwrap(); copy(&mut s, part); let paint = s.doc.appearances.faces.iter().find(|face| face.body == "Foreign (2)").unwrap(); assert!(paint.point.dist(expected) < 1e-6, "{:?} versus {expected:?}", paint.point); diff --git a/crates/engine/src/cmd/component_extract.rs b/crates/engine/src/cmd/component_extract.rs index ea72a2bd3..cabb6785a 100644 --- a/crates/engine/src/cmd/component_extract.rs +++ b/crates/engine/src/cmd/component_extract.rs @@ -131,10 +131,10 @@ fn keep_component_looks(doc: &mut Document, owners: &BTreeMap, comp /// What the bodies `new` call the face or edge that `old` calls `name`, found where it is. fn renamed(old: &ModelState, new: &[&ModelBody], name: &str, near: Vec3) -> Option { use solidcraft_doc::{appearance::face_index_at, naming}; - if let Some((p, _)) = naming::point_on_face(old, name, near) { + if let Some(p) = naming::point_on_face(old, name, near) { return new.iter().find_map(|b| face_index_at(b, p).and_then(|i| naming::face_names(b).get(i).cloned())); } - let p = old.bodies.iter().find_map(|b| naming::find_edge(b, name, near).ok())?.0; + let p = old.bodies.iter().find_map(|b| naming::find_edge(b, name, near).ok())?; new.iter().find(|b| face_index_at(b, p).is_some()).and_then(|b| naming::edge_names_at(b, &[p]).pop()) } @@ -376,7 +376,7 @@ fn part_design(s: &Session, sc: &Scope, stem: &str, cmd: &str) -> Result<(Sessio if !source.configs.is_empty() { notices.push(format!("the configurations stay in this design; {stem} has none")); } - let part = Session::new(part); + let part = Session::opened_validating(part, None, s.validation()); let failing: Vec = part.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| format!("{} ({e})", r.name))).take(5).collect(); if !failing.is_empty() { return Err(bad(cmd, format!("{name} does not build on its own: {}", failing.join("; ")))); diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index 391d976e6..e90f2957a 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -88,8 +88,8 @@ pub fn resolve_design_links(doc: &mut Document, from: Option<&str>) { /// the design gives their faces (`Feature::link_faces`), with the source's design properties. type Linked = (String, solidcraft_io::StepFeature, Vec>, solidcraft_doc::Metadata); -/// The solid bodies of the design at `file`, evaluated, as an Import feature. -fn linked_bodies(file: &Path, own: Option<&str>) -> Result { +/// The solid bodies of the design at `file`, evaluated under `validation`, as an Import feature. +fn linked_bodies(file: &Path, own: Option<&str>, validation: solidcraft_kernel::Validation) -> Result { let shown = file.display().to_string(); if own.is_some_and(|o| absolute(Path::new(o)) == absolute(file)) { return Err(EngineError::Other(format!("{shown}: a design can't be linked into itself"))); @@ -101,7 +101,7 @@ fn linked_bodies(file: &Path, own: Option<&str>) -> Result { EngineError::Other(if e.starts_with(&shown) { e } else { format!("{shown}: {e}") }) })?; let doc = solidcraft_io::read_design(&bytes).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?; - session_bodies(&Session::opened_at(doc, None, Some(&shown)), &shown) + session_bodies(&Session::opened_at_validating(doc, None, Some(&shown), validation), &shown) } /// The solid bodies of `part`, the design saved as `shown`, as an Import feature. @@ -156,7 +156,7 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate})); } } - let (design_name, sf, faces, metadata) = linked_bodies(&file, s.path.as_deref())?; + let (design_name, sf, faces, metadata) = linked_bodies(&file, s.path.as_deref(), s.validation())?; let name = str_(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string).unwrap_or(design_name); let mut create = json!({"name": name, "activate": false}); // Clipboard insertion uses reuse even for the first paste, which must stay movable. @@ -224,7 +224,7 @@ fn update_links(s: &mut Session, p: &Value) -> Result { let old = old.clone(); link_refused(s.path.as_deref(), &link.path).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; let file = resolve(s.path.as_deref(), &link.path); - let (_, sf, faces, _) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; + let (_, sf, faces, _) = linked_bodies(&file, s.path.as_deref(), s.validation()).map_err(|e| bad(cmd, format!("{cname}: {e}")))?; warnings.extend(sf.warnings.iter().cloned()); let same = matches!(&sf.kind, FeatureKind::Import { step, .. } if *step == old); let kept = s.doc.feature(link.feature).map(|f| &f.link_faces); @@ -305,7 +305,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { } // Read/evaluate the candidate before changing anything. Session::execute owns the single // undo step and restores both the document and evaluated state on any later failure. - let (_, sf, faces, _) = linked_bodies(&file, s.path.as_deref()).map_err(|e| bad(cmd, e.to_string()))?; + let (_, sf, faces, _) = linked_bodies(&file, s.path.as_deref(), s.validation()).map_err(|e| bad(cmd, e.to_string()))?; let geometry_changed = match (s.doc.feature(link.feature).map(|f| &f.kind), &sf.kind) { (Some(FeatureKind::Import { step: old, .. }), FeatureKind::Import { step, .. }) => old != step, _ => true, diff --git a/crates/engine/src/cmd/config_certificate_tests.rs b/crates/engine/src/cmd/config_certificate_tests.rs index e39c32134..e82e64c67 100644 --- a/crates/engine/src/cmd/config_certificate_tests.rs +++ b/crates/engine/src/cmd/config_certificate_tests.rs @@ -120,8 +120,8 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam 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. + // Names saved before format 14 open with the legacy mark; the sketch is held by its anchor, + // not by its name. let mark = |name: &Option| name.as_ref().map(|n| format!("{}{n}", solidcraft_doc::naming::LEGACY_MARK)); let mut saved_plane = saved_plane; if let solidcraft_doc::PlaneRef::Face { name, .. } = &mut saved_plane { @@ -175,7 +175,7 @@ fn certified_side_refuses_reused_body_name_from_a_new_producer() { } #[test] -fn legacy_v9_annulus_outer_side_emboss_keeps_its_original_heuristic_anchor() { +fn legacy_v9_annulus_outer_side_emboss_asks_for_its_face_again() { let mut s = Session::default(); run(&mut s, "sketch.create", json!({"plane":"XY"})); run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":10,"id":"outer"})); @@ -200,19 +200,20 @@ fn legacy_v9_annulus_outer_side_emboss_keeps_its_original_heuristic_anchor() { let mut legacy: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); legacy["format"] = json!("solidcraft/9"); // What a version 9 design stored for that pick: the centroid-family name of the outer wall - // piece holding the point. It keeps finding that piece, as it did when saved. + // piece holding the point, worked out from geometry. It names no face today (the outer wall + // is one face, named after its own curve): the emboss fails and asks for its face again, + // and the sleeve is built without it. for feature in legacy["features"].as_array_mut().unwrap() { if feature["id"] == json!(feature_id) { feature["face_names"] = json!(["F2:side:inner#4"]); } } let reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap()); - assert!(reopened.model.result(feature_id).unwrap().error.is_none()); - assert!( - (reopened.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume - volume) - .abs() - < 1e-8 - ); + let error = reopened.model.result(feature_id).unwrap().error.clone().unwrap(); + assert_eq!(solidcraft_doc::reselect_parts(&error), Some(("Raised Badge", "?F2:side:inner#4")), "{error}"); + let sleeve = reopened.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; + assert!((sleeve - std::f64::consts::PI * 380.).abs() < 0.2, "volume {sleeve}"); + assert!(reopened.model.results.iter().filter(|r| r.id != feature_id).all(|r| r.error.is_none()), "{:?}", reopened.model.results); } #[test] diff --git a/crates/engine/src/cmd/diagnostics.rs b/crates/engine/src/cmd/diagnostics.rs index 5837ca9ee..4faa96b2a 100644 --- a/crates/engine/src/cmd/diagnostics.rs +++ b/crates/engine/src/cmd/diagnostics.rs @@ -45,6 +45,18 @@ pub static COMMANDS: &[CommandSpec] = &[ moves single operations on top of both. Returns {choice, environment, overrides: {op: backend}, routes: [{op, \ route, backend}]}: route is the table's kernel for the operation, backend the one it runs on now", ), + CommandSpec::new("diagnostics.validation", "Validation", crate::checked!("diagnostics.validation", validation)) + .icon("bug_report") + .noundo() + .contract(&VALIDATION_CONTRACT) + .output(crate::schema::output_schema_for::) + .params( + "mode?: each_step | each_feature | off (default: leave it). When the kernel's full check runs on the features computed \ + from now on: after every sweep, boolean and blend (each_step), once on the bodies each feature makes or changes \ + (each_feature, the default; a body it refuses still fails its feature, with the check's reason), or never (off, \ + experimental). Results already there stand until their features are computed again (timeline.compute_all). \ + The app's preference of the same name sets it. Returns {mode, previous}", + ), CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).icon("bug_report").noundo().enabled(crash_test_enabled).params( "mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \ the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \ @@ -112,6 +124,26 @@ fn crash_test(_: &mut Session, p: &Value) -> Result { const PROFILE_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const VALIDATION_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +fn validation(s: &mut Session, p: &Value) -> Result { + let cmd = "diagnostics.validation"; + let mode = match p.get("mode") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_str() + .and_then(solidcraft_kernel::Validation::parse) + .ok_or_else(|| bad(cmd, format!("`mode` {}", crate::schema::diagnostics::VALIDATION_MODES)))?, + ), + }; + let previous = s.validation(); + if let Some(mode) = mode { + s.set_validation(mode); + } + let out = crate::schema::diagnostics::ValidationReply { mode: s.validation().into(), previous: previous.into() }; + serde_json::to_value(out).map_err(|e| EngineError::Other(format!("{cmd}: {e}"))) +} + /// Rows `diagnostics.profile` returns at most. const MAX_PROFILE_ROWS: u64 = 10_000; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 31655f997..143358069 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -134,7 +134,9 @@ fn restore_checkpoint(s: &mut Session, p: &Value) -> Result { } fn compute_all(s: &mut Session, _p: &Value) -> Result { + let validation = s.validation(); s.model = solidcraft_doc::Model::new(); + s.set_validation(validation); s.refresh(); let errors = s.model.results.iter().filter(|r| r.error.is_some()).count(); Ok(json!({"features": s.model.results.len(), "errors": errors})) diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 21c7d8189..2d74db520 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -1829,26 +1829,31 @@ fn a_line_of_text_cuts_into_a_block_at_any_depth() { /// A design saved before tapered sides were built through `taper_loop` (#1014), by the build /// before it: two tapered bosses apart from each other (now joined in one boolean), a fillet on -/// a sloping side edge of one and on the top edge of the other, both saved by edge name. They -/// still find their edges, and the part comes out the same. +/// a sloping side edge of one and on the top edge of the other, both saved by edge name. The +/// sloping edge is still the edge its name names. The top edge was saved as an edge of piece `#1` +/// of the cone's side, which is one face now: no edge is that edge any more, so that fillet fails +/// and asks for its edge to be picked again (never the nearest edge of the whole face), and the +/// rest of the part comes out as before. #[test] -fn fillets_on_tapered_bosses_saved_before_still_find_their_edges() { +fn a_fillet_saved_on_a_piece_of_a_tapered_side_that_is_whole_now_asks_for_its_edge_again() { let text = include_str!("../../../../tests/taper/before-1014/two_tapered_bosses_filleted.json"); let mut s = Session::new(solidcraft_doc::Document::from_json(text).unwrap()); let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); - for name in ["Extrude2", "Fillet1", "Fillet2"] { + for name in ["Extrude2", "Fillet1"] { let id = s.doc.find_feature(name).unwrap().id; let r = s.model.result(id).unwrap(); assert!(r.error.is_none() && r.warning.is_none(), "{name}: {:?} {:?}", r.error, r.warning); } + let fillet = s.doc.find_feature("Fillet2").unwrap().id; + let error = s.model.result(fillet).unwrap().error.clone().unwrap(); + assert_eq!(solidcraft_doc::reselect_parts(&error), Some(("Fillet2", "F4:side:c1#1|F4:top#[F4:side:c1]")), "{error}"); // In closed form: the 80 × 40 × 20 block, the 20 × 20 boss 10 high tapered 5° in (a frustum, // top 20 − 20 tan 5° square: 3660.251034), the Ø16 boss tapered alike (a cone frustum, top // radius 8 − 10 tan 5°: 1798.751833); less the R1 round along a sloping corner (the corner's // section, r²(cot φ/2 − (π − φ)/2) at its dihedral angle φ = 90.435°, times its length - // between z = 20 and 30: 2.124401) and the R0.5 round all round the cone's top (the section - // at the rim's 95°, turned about the axis by Pappus: 1.928463). The build that saved it, - // with truck, measured 69454.885209. - assert!((volume - 69454.950004).abs() < 1e-3, "{volume}"); + // between z = 20 and 30: 2.124401). The R0.5 round all round the cone's top (1.928463) is + // the failed fillet's. + assert!((volume - 69456.878467).abs() < 1e-3, "{volume}"); assert_eq!(s.world_state().unwrap().bodies.len(), 1); } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 69d6149a0..b698cb8fa 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -294,6 +294,7 @@ fn open(s: &mut Session, p: &Value) -> Result { if let Some(command) = super::drawing_import_command(path) { let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into()); let mut fresh = Session::new(Document::new(&stem)); + fresh.set_validation(s.validation()); let mut out = fresh.execute(command, &json!({"path": path}))?; fresh.undo.clear(); s.replace_design(fresh); @@ -307,6 +308,7 @@ fn open(s: &mut Session, p: &Value) -> Result { // A new, unsaved design holding the file's bodies. let stem = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "Untitled".into()); let mut fresh = Session::new(Document::new(&stem)); + fresh.set_validation(s.validation()); let r = if solidcraft_io::is_step_path(path) { add_step(&mut fresh, path, None, &step_options(p, "doc.open")?)? } else { @@ -335,7 +337,7 @@ fn open(s: &mut Session, p: &Value) -> Result { if let Some(stem) = default_name_for(&doc.name, path) { doc.name = stem; } - s.replace_design(Session::opened_at(doc, saved.as_ref(), Some(path))); + s.replace_design(Session::opened_at_validating(doc, saved.as_ref(), Some(path), s.validation())); s.disk = disk; s.read_only = read_only; let errors = s.model.results.iter().filter(|r| r.error.is_some()).count(); @@ -460,9 +462,19 @@ fn write_bytes( impl Session { /// Open a design with its file location, resolving component links before history keeps /// them. Absolute in-memory targets survive Save As, undo, redo and recovery unchanged. - pub fn opened_at(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>, path: Option<&str>) -> Self { + pub fn opened_at(doc: Document, saved: Option<&solidcraft_doc::SavedModel>, path: Option<&str>) -> Self { + Self::opened_at_validating(doc, saved, path, solidcraft_kernel::Validation::default()) + } + + /// [`Self::opened_at`], its features evaluated under `validation` ([`Session::set_validation`]). + pub fn opened_at_validating( + mut doc: Document, + saved: Option<&solidcraft_doc::SavedModel>, + path: Option<&str>, + validation: solidcraft_kernel::Validation, + ) -> Self { super::component_link::resolve_design_links(&mut doc, path); - let mut session = Self::opened(doc, saved); + let mut session = Self::opened_validating(doc, saved, validation); session.path = path.map(str::to_owned); session } @@ -815,7 +827,7 @@ fn recover(s: &mut Session, p: &Value) -> Result { if let Some(stem) = entry.path.as_deref().and_then(|path| default_name_for(&doc.name, path)) { doc.name = stem; } - s.replace_design(Session::opened_at(doc, None, entry.path.as_deref())); + s.replace_design(Session::opened_at_validating(doc, None, entry.path.as_deref(), s.validation())); s.mark_unsaved(); if bool_(p, "discard").unwrap_or(false) { crate::recovery::remove(&dir, id)?; diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rs index 38de1be77..32e5ed765 100644 --- a/crates/engine/src/cmd/plastic.rs +++ b/crates/engine/src/cmd/plastic.rs @@ -509,8 +509,7 @@ mod tests { let before = s.model.state_before(feature.id); let name = feature.face_names.first().unwrap(); let point = solidcraft_doc::naming::point_on_face(&before, name, Vec3::new(0., -28., 20.)) - .expect("the original wall identity survives merged pieces") - .0; + .expect("the original wall identity survives merged pieces"); assert!((point - Vec3::new(0., -33., 20.)).len() < 1e-8, "{point:?}"); assert!(s.model.results.iter().all(|result| result.error.is_none())); let check = |session: &Session| { diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index feaebfecc..347148838 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -194,10 +194,16 @@ pub(super) fn refresh(s: &Session, doc: &Document, id: u64, sk: &mut Sketch) -> return vec!["lost face attachment; reattach explicitly".into()]; }; let Ok(plane) = sketch_plane(&doc, id, &st) else { return Vec::new() }; - let warnings = match attachment { + let refreshed = match attachment { Some(anchor) => solidcraft_doc::project::refresh_face_anchor_links(&doc, &vals, &st, &plane, sk, anchor), None => solidcraft_doc::project::refresh_links(&doc, &vals, &st, &plane, sk), }; + // A link whose named face or edge is gone fails the sketch when it is evaluated; while it is + // edited, that is what the refresh says. + let warnings = match refreshed { + Ok(warnings) => warnings, + Err(e) => return vec![e.in_feature(&doc.feature(id).map(|f| f.name.clone()).unwrap_or_default()).to_string()], + }; if let Ok(stored) = doc.sketch(id) && sk.positions_in(stored).is_some() { diff --git a/crates/engine/src/cmd/sketch_project_edge_tests.rs b/crates/engine/src/cmd/sketch_project_edge_tests.rs index db3528ae1..97472f680 100644 --- a/crates/engine/src/cmd/sketch_project_edge_tests.rs +++ b/crates/engine/src/cmd/sketch_project_edge_tests.rs @@ -1,6 +1,6 @@ //! A projected edge stays the edge that was picked: its link keeps the edge's persistent name, //! so the edge is found by that name wherever a change of the body takes it, and no other edge -//! is taken for it when it is split or gone. +//! is taken for it when it is split or gone: the sketch fails, asking for the edge again. use serde_json::{Value, json}; use solidcraft_geom::{Vec2, Vec3}; @@ -119,11 +119,17 @@ fn a_projected_edge_stays_that_edge_when_the_body_changes_size() { assert!(matches!(&stored(&s).source, LinkSource::Edge { body, at } if body == "Body1" && at.dist(Vec3::new(400.0, 25.0, 20.0)) < 1e-6)); } +/// What sketch `Top` asks to be picked again, when it fails for a reference it lost. +fn reselect(s: &Session) -> Option { + let r = s.model.result(s.doc.find_feature("Top").unwrap().id).unwrap(); + r.error.as_deref().and_then(solidcraft_doc::reselect_parts).filter(|(feature, _)| *feature == "Top").map(|(_, reference)| reference.to_string()) +} + /// A slot cut through the plate from x = 80 to 120, y = 20 to 30 leaves the picked edge in two -/// pieces, y = 0..20 and y = 30..50. The link, picked at y = 10, gives the piece it was picked -/// on and says the edge was split; without the slot it is the whole edge again. +/// pieces, y = 0..20 and y = 30..50. Neither is the edge: the sketch fails, asking for it again +/// (never the piece nearest the pick); without the slot it is the whole edge again. #[test] -fn a_projected_edge_that_was_split_gives_its_nearest_piece_and_says_so() { +fn a_projected_edge_that_was_split_fails_its_sketch_asking_for_the_edge_again() { let mut s = Session::default(); plate(&mut s); run(&mut s, "sketch.create", json!({"plane": "XY", "name": "SlotSketch"})); @@ -133,31 +139,28 @@ fn a_projected_edge_that_was_split_gives_its_nearest_piece_and_says_so() { run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": true})); project_right_edge(&mut s, 10.0); assert_line(&s, 100.0, (0.0, 50.0), "drawn"); + let name = stored(&s).edge_name.unwrap(); run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": false})); - assert_line(&s, 100.0, (0.0, 20.0), "split"); - assert!(trouble(&s).contains("was split"), "{}", trouble(&s)); - assert!(!link(&s).lost); + assert_eq!(reselect(&s), Some(name), "{}", trouble(&s)); run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": true})); assert_line(&s, 100.0, (0.0, 50.0), "whole again"); assert_eq!(trouble(&s), ""); } /// A fillet of radius 4 takes the picked edge away. Its two tangent edges are 4 from the picked -/// point, the nearest edges there are now: the link is lost and keeps its line, it takes -/// neither of them. Without the fillet the link has its edge again. +/// point, the nearest edges there are now: the sketch takes neither of them, it fails, asking for +/// its edge again. Without the fillet the link has its edge again. #[test] -fn a_projected_edge_that_is_gone_is_lost_not_replaced() { +fn a_projected_edge_that_is_gone_fails_its_sketch_not_replaced() { let mut s = Session::default(); plate(&mut s); run(&mut s, "solid.fillet", json!({"edges": [[100, 25, 20]], "radius": "4 mm", "name": "Round"})); run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": true})); project_right_edge(&mut s, 25.0); assert_line(&s, 100.0, (0.0, 50.0), "drawn"); + let name = stored(&s).edge_name.unwrap(); run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": false})); - let said = trouble(&s); - assert!(said.contains("projected reference lost: edge") && said.contains("no longer exists"), "{said}"); - assert!(link(&s).lost); - assert_line(&s, 100.0, (0.0, 50.0), "the last geometry is kept"); + assert_eq!(reselect(&s), Some(name), "{}", trouble(&s)); run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": true})); assert_eq!(trouble(&s), ""); assert!(!link(&s).lost); diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index 6c32703a2..543112cff 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -304,21 +304,20 @@ fn deleting_one_edge_of_a_projected_face_keeps_the_others_as_they_were() { assert!(s.doc.sketch(id).unwrap().links.is_empty()); } +/// The edge a projection was made from goes with its body: the sketch fails, asking for the edge +/// again, instead of keeping a lost link. #[test] -fn lost_reference_keeps_geometry_with_a_warning() { +fn a_reference_whose_body_is_gone_fails_its_sketch_asking_for_it_again() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); let boxf = s.doc.features.last().unwrap().id; run(&mut s, "sketch.create", json!({"plane": "XY"})); run(&mut s, "sketch.project", json!({"refs": [{"edge": [5, 0, 10]}]})); run(&mut s, "sketch.finish", json!({})); + let name = s.doc.sketch(s.doc.features.last().unwrap().id).unwrap().links[0].edge_name.clone().unwrap(); run(&mut s, "timeline.suppress", json!({"feature": boxf, "suppressed": true})); - let st = s.model.state(); - let ss = st.sketches.last().unwrap(); - assert_eq!(ss.sketch.curves.len(), 1, "geometry kept"); - assert!(ss.sketch.links[0].lost); - let w = s.model.results.last().unwrap().warning.clone().unwrap_or_default(); - assert!(w.contains("lost"), "{w}"); + let r = s.model.results.last().unwrap(); + assert_eq!(r.error.as_deref().and_then(solidcraft_doc::reselect_parts), Some((r.name.as_str(), name.as_str())), "{r:?}"); } #[test] @@ -558,8 +557,8 @@ fn sweeps_and_pipes_follow_3d_sketch_curves() { } /// #47: references to other bodies: an edge, a face's loops and a silhouette of a second body -/// project into a sketch on the first; they follow an edit of that body (a parameter) and -/// are reported lost, not crashed on, when it goes away. +/// project into a sketch on the first; they follow an edit of that body (a parameter), and when +/// it goes away the sketch fails, asking for the named edge again, not crashed on. #[test] fn project_and_include_from_other_bodies() { let mut s = Session::default(); @@ -589,13 +588,17 @@ fn project_and_include_from_other_bodies() { let id = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap().id; let si = run(&mut s, "sketch.inspect", json!({"sketch": id})); assert!(xs(&si).iter().any(|x| (x - 70.0).abs() < 1e-6), "{:?}", xs(&si)); - // Remove the cylinder: its silhouette and edge are lost, with a warning and no error. + // Remove the cylinder: the edge included from it is gone, and the sketch asks for it again. let cyl = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Cylinder { .. })).unwrap().id; run(&mut s, "timeline.delete", json!({"feature": cyl})); let t = run(&mut s, "document.inspect", json!({})); let row = t["timeline"].as_array().unwrap().iter().find(|r| r["id"] == json!(id)).cloned().unwrap(); - assert!(row["error"].is_null(), "{row}"); - assert!(row["warning"].as_str().is_some_and(|w| w.contains("lost")), "{row}"); + let error = row["error"].as_str().unwrap_or_default(); + assert!( + solidcraft_doc::reselect_parts(error) + .is_some_and(|(feature, reference)| feature == row["name"] && reference.starts_with(&format!("F{cyl}:"))), + "{row}" + ); } /// A cylinder's wall and the torus of a rounded rim are drawn as one face but stored in halves diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4084cf4b4..fc5977046 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -606,20 +606,31 @@ impl Session { /// `doc`'s evaluation ([`Model::adopt`]); otherwise the timeline is evaluated. /// Use [`Self::opened_at`] when the document's file location is known. /// `SOLIDCRAFT_NO_MODEL_CACHE` set always evaluates. - pub fn opened(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>) -> Self { + pub fn opened(doc: Document, saved: Option<&solidcraft_doc::SavedModel>) -> Self { + Self::opened_validating(doc, saved, solidcraft_kernel::Validation::default()) + } + + /// [`Self::opened`], its features evaluated under `validation` ([`Session::set_validation`]). + pub fn opened_validating(mut doc: Document, saved: Option<&solidcraft_doc::SavedModel>, validation: solidcraft_kernel::Validation) -> Self { // A design's font files are checked like its other paths before it is evaluated. solidcraft_io::vfs::install_checks(); // The session keeps what is hidden (an undo step of its own); the design file carries it. let visibility = std::mem::take(&mut doc.visibility); let doc = Arc::new(doc); + // A model saved under another check mode holds that mode's results: evaluated again. let adopted = saved .filter(|_| solidcraft_geom::env::var_os("NO_MODEL_CACHE").is_none()) - .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()); - let model = adopted.unwrap_or_else(|| { - let mut model = Model::new(); - model.evaluate(&doc); - model - }); + .and_then(|saved| Model::adopt(&doc, saved).map_err(|e| log::info!("the saved model is not used: {e}")).ok()) + .filter(|model| model.validation() == validation); + let model = match adopted { + Some(model) => model, + None => { + let mut model = Model::new(); + model.set_validation(validation); + model.evaluate(&doc); + model + } + }; Session { saved: doc.clone(), doc, @@ -690,6 +701,7 @@ impl Session { /// checkpoint keeps, not the replaced session's file path (docs/mcp.md). pub fn replace_design(&mut self, fresh: Session) { let auto_project = self.auto_project; + let validation = self.validation(); let metric_tap_drill_major_less_pitch = self.metric_tap_drill_major_less_pitch; let surface_extrude_symmetric_per_side = self.surface_extrude_symmetric_per_side; let param_check = self.param_check; @@ -707,6 +719,9 @@ impl Session { self.crash_journal = crash_journal; self.command_check = command_check; self.auto_project = auto_project; + // The user's, like `auto_project`: the commands that open a design evaluate it under it + // already (`Session::opened_validating`). + self.set_validation(validation); self.metric_tap_drill_major_less_pitch = metric_tap_drill_major_less_pitch; self.surface_extrude_symmetric_per_side = surface_extrude_symmetric_per_side; self.param_check = param_check; @@ -942,6 +957,20 @@ impl Session { } } + /// When SMLib's check runs on the features evaluated: after every sweep, boolean and blend, + /// once on the bodies each feature keeps (the default), or not at all. A user's setting, + /// kept when another design is opened (`diagnostics.validation`, the app's preference). + pub fn validation(&self) -> solidcraft_kernel::Validation { + self.model.validation() + } + + /// Evaluate the features computed from now on under `validation` ([`Session::validation`]); + /// the results already there stand until their features are computed again + /// (`timeline.compute_all` computes every one). + pub fn set_validation(&mut self, validation: solidcraft_kernel::Validation) { + self.model.set_validation(validation); + } + pub fn refresh(&mut self) { self.model.evaluate(&self.doc); #[cfg(test)] diff --git a/crates/engine/src/naming_history_tests.rs b/crates/engine/src/naming_history_tests.rs index e78604914..fe6c3d132 100644 --- a/crates/engine/src/naming_history_tests.rs +++ b/crates/engine/src/naming_history_tests.rs @@ -27,6 +27,12 @@ fn error(s: &Session, name: &str) -> Option { s.model.result(id(s, name)).and_then(|r| r.error.clone()) } +/// The reference feature `name` failed on, asking for it to be picked again. +fn reselect(s: &Session, name: &str) -> Option { + let error = error(s, name)?; + solidcraft_doc::reselect_parts(&error).filter(|(feature, _)| *feature == name).map(|(_, reference)| reference.to_string()) +} + /// Whether any body holds `p`. fn solid_at(s: &Session, p: [f64; 3]) -> bool { s.model.state().bodies.iter().any(|b| b.body.contains(Vec3::new(p[0], p[1], p[2]))) @@ -171,14 +177,16 @@ fn a_piece_keeps_its_identity_when_the_cut_that_made_it_moves_or_shrinks() { change(&mut s, "slot_w", "0.05 mm"); assert_eq!(warning(&s, "Raise"), None); assert!(solid_at(&s, [39.0, 15.0, 11.0]) && !solid_at(&s, [27.0, 15.0, 11.0])); - // Gone altogether (suppressed), the piece is the whole top again: said, not guessed. + // Gone altogether (suppressed), the top is whole again, which is not the piece: the raise + // fails, asking for its face again, never guessed. run(&mut s, "timeline.suppress", json!({"feature": "Slot", "suppressed": true})); - let w = warning(&s, "Raise").unwrap_or_default(); - assert!(w.contains("split") || w.contains("no longer exists"), "{w}"); + assert_eq!(reselect(&s, "Raise").as_ref(), raise.face_names.first()); } +/// A face merged into another is not the face that was picked: the feature on it fails, asking +/// for its face again; when the faces part again, the reference finds its face. #[test] -fn a_face_merged_into_another_answers_to_its_name_and_says_so() { +fn a_face_merged_into_another_asks_for_its_face_again() { let mut s = Session::default(); block(&mut s); run(&mut s, "parameters.add", json!({"name": "boss_h", "expression": "5 mm"})); @@ -191,13 +199,13 @@ fn a_face_merged_into_another_answers_to_its_name_and_says_so() { let raise = s.doc.find_feature("Raise").cloned().unwrap(); assert_eq!(raise.face_names, vec![format!("F{boss}:top")]); assert!(solid_at(&s, [50.0, 15.0, 5.5]) && !solid_at(&s, [50.0, 15.0, 6.5])); - // As tall as the block, the boss's top and the block's are one face: the reference finds - // it and says it was merged. + // As tall as the block, the boss's top and the block's are one face: not the boss's top. change(&mut s, "boss_h", "10 mm"); + assert_eq!(reselect(&s, "Raise").as_ref(), raise.face_names.first()); + assert!(!solid_at(&s, [50.0, 15.0, 10.5]) && !solid_at(&s, [20.0, 15.0, 10.5]), "nothing is raised"); + change(&mut s, "boss_h", "5 mm"); assert_eq!(error(&s, "Raise"), None); - let w = warning(&s, "Raise").unwrap_or_default(); - assert!(w.contains("merged"), "{w}"); - assert!(solid_at(&s, [50.0, 15.0, 10.5]) && solid_at(&s, [20.0, 15.0, 10.5]), "the merged top is raised as one"); + assert!(solid_at(&s, [50.0, 15.0, 5.5]) && !solid_at(&s, [20.0, 15.0, 10.5])); } #[test] @@ -498,11 +506,11 @@ fn split_pieces_keep_their_numbers_across_evaluations() { } } -/// #3902: a design saved before the pieces of a face were numbered by place opens with the -/// numbers it was saved with, so a reference to `…#1` stays on the piece it was made on. The -/// grooved disc's top is split in two, numbered the other way round by place. +/// #3902: a design saved before the pieces of a face were numbered by place opens with its +/// features marked `kernel_piece_order`, and evaluates: its pieces are named alike every time it +/// is evaluated. (Which numbers they get is not promised to be the ones it was saved with.) #[test] -fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { +fn a_design_saved_before_pieces_were_numbered_by_place_opens_marked_and_names_alike() { let mut s = Session::default(); s.run_script(&grooved_disc()).unwrap(); let by_place = listed(&mut s, "Disc"); @@ -521,11 +529,9 @@ fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { assert!(old.features.iter().all(|f| f.kernel_piece_order), "the features of an older design keep the old numbering"); let mut reopened = Session::new(old); reopened.refresh(); + assert!(reopened.model.results.iter().all(|r| r.error.is_none()), "{:?}", reopened.model.results); let kept = listed(&mut reopened, "Disc"); - let at = |faces: &[(String, bool, [f64; 3])], name: &str| faces.iter().find(|(n, _, _)| n == name).map(|(_, _, c)| *c); - // The pieces are numbered differently by place, and the older design keeps its own numbers. - let (old1, new1) = (at(&kept, "F1:top#1").unwrap(), at(&by_place, "F1:top#1").unwrap()); - assert!((0..3).any(|k| (old1[k] - new1[k]).abs() > 1.0), "{kept:?} {by_place:?}"); + assert_eq!(kept.len(), by_place.len()); let mut legacy = solidcraft_doc::Document::clone(&s.doc); legacy.features.iter_mut().for_each(|f| f.kernel_piece_order = true); let mut saved_with = Session::new(legacy); @@ -630,9 +636,9 @@ fn one_fillet_over_two_bodies_of_one_extrude_rounds_each_body_s_own_edges() { /// One fillet over a vertical edge of each of two stacked boxes. A build before blends were split /// by body named the upper box's edge after the lower box's nearest edge (its top front edge), /// which was rounded instead. The pick (outside the box the name was recorded on) shows that name -/// is not the upper box's: the edge is found at its point, on the upper box. +/// is not the upper box's edge: the fillet fails, asking for that edge again, and rounds nothing. #[test] -fn one_fillet_over_stacked_boxes_rounds_the_upper_box_s_edge_even_when_saved_named_on_the_lower() { +fn one_fillet_over_stacked_boxes_saved_named_on_the_lower_asks_for_the_upper_edge_again() { let mut s = Session::default(); stacked_boxes(&mut s); run(&mut s, "solid.fillet", json!({"edges": [[25, -25, 20], [-25, -25, 45]], "radius": 2, "name": "Rounds"})); @@ -655,10 +661,11 @@ fn one_fillet_over_stacked_boxes_rounds_the_upper_box_s_edge_even_when_saved_nam let old_refs = solidcraft_doc::edge_refs(&before, &Some(lower.name.clone().into()), &[Vec3::new(25.0, -25.0, 20.0), Vec3::new(-25.0, -25.0, 45.0)]); let feature = s.doc_mut().feature_mut(f).unwrap(); - feature.edge_names = old_names; + feature.edge_names = old_names.clone(); feature.edge_refs = old_refs; s.refresh(); - check(&s, "saved by an older build"); + assert_eq!(reselect(&s, "Rounds").as_ref(), old_names.get(1)); + assert!(solid_at(&s, [24.8, -24.8, 20.0]) && solid_at(&s, [-24.8, -24.8, 45.0]), "nothing is rounded"); } /// A shell opened by a point pick on a bar's end face keeps opening that face when a parameter diff --git a/crates/engine/src/schema/diagnostics.rs b/crates/engine/src/schema/diagnostics.rs index dd7cb1bb0..1f28686de 100644 --- a/crates/engine/src/schema/diagnostics.rs +++ b/crates/engine/src/schema/diagnostics.rs @@ -142,6 +142,67 @@ impl ProfileReport { } } +/// A validation mode by name, with the handler's message for anything else. +fn validation_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::String(s) => ValidationMode::parse(&s).map(Some).ok_or_else(|| serde::de::Error::custom(VALIDATION_MODES)), + _ => Err(serde::de::Error::custom(VALIDATION_MODES)), + } +} + +/// What a `mode` that names no validation mode is told. +pub(crate) const VALIDATION_MODES: &str = "must be each_step, each_feature or off"; + +/// When SMLib's full check runs while features are computed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ValidationMode { + /// After every sweep, boolean and blend inside a feature: a step whose result fails the + /// check fails the feature there. + EachStep, + /// Once per feature (the default): each body the feature makes or changes is checked before + /// it is kept, and a body the check refuses fails the feature with the check's reason. + EachFeature, + /// Never (experimental): a body the check would refuse is kept. + Off, +} + +impl ValidationMode { + fn parse(id: &str) -> Option { + solidcraft_kernel::Validation::parse(id).map(ValidationMode::from) + } +} + +impl From for ValidationMode { + fn from(v: solidcraft_kernel::Validation) -> Self { + match v { + solidcraft_kernel::Validation::EachStep => ValidationMode::EachStep, + solidcraft_kernel::Validation::EachFeature => ValidationMode::EachFeature, + solidcraft_kernel::Validation::Off => ValidationMode::Off, + } + } +} + +/// Read, or set, when SMLib's full check runs on the features computed from now on. +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ValidationParams { + /// The mode to compute features under from now on. Default: leave it as it is. The results + /// already there stand until their features are computed again (`timeline.compute_all`). + #[serde(default, deserialize_with = "validation_mode")] + pub mode: Option, +} + +/// The reply of `diagnostics.validation`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ValidationReply { + /// The mode features are computed under now. + pub mode: ValidationMode, + /// The mode before this call. + pub previous: ValidationMode, +} + /// Tests that switch the process-wide profiler on, off or reset it run one at a time. #[cfg(test)] pub(crate) static PROFILE_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); diff --git a/crates/engine/src/schema/diagnostics_tests.rs b/crates/engine/src/schema/diagnostics_tests.rs index 51aade0b8..f568cc59a 100644 --- a/crates/engine/src/schema/diagnostics_tests.rs +++ b/crates/engine/src/schema/diagnostics_tests.rs @@ -1,6 +1,6 @@ use serde_json::json; -use super::ProfileParams; +use super::{ProfileParams, ValidationParams}; use crate::Session; use crate::schema::input_schema_for; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; @@ -8,6 +8,7 @@ use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["enabled", "reset", "top", "trace"]); + assert_keys(input_schema_for::(), &["mode"]); } #[test] @@ -18,6 +19,8 @@ fn strict_keeps_todays_errors() { ("diagnostics.profile", json!({"top": -1})), ("diagnostics.profile", json!({"top": 2.5})), ("diagnostics.profile", json!({"trace": 5})), + ("diagnostics.validation", json!({"mode": "each step"})), + ("diagnostics.validation", json!({"mode": true})), ]); } @@ -162,3 +165,59 @@ fn diagnostics_kernel_refuses_unknown_choices() { } assert_eq!(s.execute("diagnostics.kernel", &json!({})).unwrap()["choice"], before); } + +/// Features are checked once each by default; the command reads and sets the mode, and the mode +/// is the user's: it stays when another design is started and when everything is computed again. +#[test] +fn validation_defaults_to_each_feature_and_round_trips_through_the_command() { + use solidcraft_kernel::Validation; + let mut s = Session::default(); + assert_eq!(s.validation(), Validation::EachFeature); + assert_eq!(s.execute("diagnostics.validation", &json!({})).unwrap(), json!({"mode": "each_feature", "previous": "each_feature"})); + let r = s.execute("diagnostics.validation", &json!({"mode": "each_step"})).unwrap(); + assert_eq!(r, json!({"mode": "each_step", "previous": "each_feature"})); + assert_eq!(s.validation(), Validation::EachStep); + s.execute("file.new", &json!({})).unwrap(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); + s.execute("timeline.compute_all", &json!({})).unwrap(); + assert_eq!(s.execute("diagnostics.validation", &json!({"mode": "off"})).unwrap()["previous"], json!("each_step")); + assert_eq!(s.validation(), Validation::Off); + // A refused mode changes nothing. + assert!(s.execute("diagnostics.validation", &json!({"mode": "never"})).is_err()); + assert_eq!(s.validation(), Validation::Off); +} + +/// A feature whose body SMLib's check refuses fails under each_feature as under each_step (once +/// at its end instead of at the step), with the check's reason; off keeps the body. The bar's +/// top edge rounded into the boss's round (kernel case +/// fillets/1207-fillet-bar-top-edge-after-boss-arc-round-r0-5, refused by the check on this +/// SMLib); the same features without the last round build under every mode, to the same volume. +#[test] +fn a_body_the_check_refuses_still_fails_its_feature_once_per_feature() { + use solidcraft_kernel::Validation; + let build = |mode: Validation, last: bool| { + let mut s = Session::default(); + s.set_validation(mode); + s.execute("solid.box", &json!({"length": 100, "width": 30, "height": 10, "corner": [0, -15, 0], "body_name": "Arm"})).unwrap(); + s.execute("solid.cylinder", &json!({"diameter": 40, "height": 20, "base": [0, 0, 0], "operation": "join", "targets": ["Arm"]})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[16, 12, 10]], "radius": 2})).unwrap(); + let r = if last { s.execute("solid.fillet", &json!({"edges": [[60, -15, 10]], "radius": 0.5})).map(|_| ()) } else { Ok(()) }; + let volume = s.execute("inspect.measure", &json!({})).ok().and_then(|m| m["total"]["volume_mm3"].as_f64()); + (r.map_err(|e| e.to_string()), volume) + }; + let each_step = build(Validation::EachStep, false); + for mode in [Validation::EachFeature, Validation::Off] { + let (r, volume) = build(mode, false); + assert!(r.is_ok() && each_step.0.is_ok(), "{mode:?}: {r:?}"); + assert!(volume.zip(each_step.1).is_some_and(|(v, w)| (v - w).abs() <= 1e-9 * w), "{mode:?}: {volume:?} vs {:?}", each_step.1); + } + let (step, _) = build(Validation::EachStep, true); + let (feature, _) = build(Validation::EachFeature, true); + assert_eq!(step.is_err(), feature.is_err(), "each_step {step:?}, each_feature {feature:?}"); + if let Err(e) = &feature { + assert!(e.contains("SMLib's check refuses the result"), "{e}"); + assert!(step.as_ref().err().is_some_and(|e| e.contains("SMLib's check refuses the result")), "{step:?}"); + let (off, _) = build(Validation::Off, true); + assert!(off.is_ok(), "off keeps the body the check refuses: {off:?}"); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6bf71333b..c2e5467cc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2635,6 +2635,13 @@ mod naming { s.model.result(id).and_then(|r| r.warning.clone()) } + /// The reference feature `name` failed on, asking for it to be picked again. + fn reselect(s: &Session, name: &str) -> Option { + let id = s.doc.find_feature(name).map(|f| f.id)?; + let error = s.model.result(id).and_then(|r| r.error.clone())?; + solidcraft_doc::reselect_parts(&error).filter(|(feature, _)| *feature == name).map(|(_, reference)| reference.to_string()) + } + /// A 40 x 30 x 10 block (sketch S: l1…l4 counter-clockwise from the origin), a hole H, a /// fillet on the right top edge. fn block() -> Session { @@ -2692,8 +2699,10 @@ mod naming { assert_eq!(warning(&s, "Round"), None); } + /// The notch leaves the filleted edge in two pieces: neither is the edge, so the fillet fails, + /// asking for its edge again, and never rounds the piece nearest the pick. #[test] - fn a_split_edge_warns_and_takes_the_nearest_piece() { + fn a_split_edge_fails_the_fillet_asking_for_the_edge_again() { let mut s = block(); // Upstream of the fillet, a notch through the middle of the filleted edge. run(&mut s, "timeline.roll_to", json!({"feature": "Hole"})); @@ -2702,12 +2711,13 @@ mod naming { run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch": "N", "distance": 10, "operation": "cut", "name": "Notch"})); run(&mut s, "timeline.roll_to", json!({})); - let w = warning(&s, "Round").unwrap_or_default(); - assert!(w.contains("split"), "{w}"); + assert_eq!(reselect(&s, "Round").as_deref(), Some("F2:side:l2|F2:top")); } + /// The face the filleted edge bounded is gone with its sketch line: the fillet fails, asking + /// for its edge again. #[test] - fn a_removed_segment_warns() { + fn a_removed_segment_fails_the_fillet_asking_for_the_edge_again() { let mut s = block(); // Replace the right side (l2) of the rectangle with a new line: the face it made is gone. let sk = s.doc.find_feature("S").map(|f| f.id).unwrap(); @@ -2716,8 +2726,7 @@ mod naming { run(&mut s, "sketch.line", json!({"points": [[40, 0], [40, 30]], "ids": ["right"]})); let r: Result = s.execute("sketch.finish", &json!({})); assert!(r.is_ok() || r.is_err()); - let w = warning(&s, "Round").unwrap_or_default(); - assert!(w.contains("no longer exists"), "{w}"); + assert_eq!(reselect(&s, "Round").as_deref(), Some("F2:side:l2|F2:top")); } fn face_names(s: &mut Session, body: &str) -> Vec { @@ -2776,7 +2785,9 @@ mod naming { model.evaluate(&reopened); assert_eq!(model.state().sketch(reopened.find_feature("Top").unwrap().id).unwrap().plane.origin.z, 10.); assert!((model.state().bodies[0].mesh().bounds().max.z - 15.).abs() < 1e-6); - // A historical format-10 attachment uses its saved generic face name and no strong anchor. + // A format-10 attachment has only the face name that build worked out from geometry, and + // no strong anchor: that name finds no face today. The sketch fails, asking for its face + // again, and so does the peg on it; the block builds. let mut old = (*s.doc).clone(); let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, name, .. }, sketch } = &mut old.features.iter_mut().find(|f| f.name == "Top").unwrap().kind @@ -2784,6 +2795,7 @@ mod naming { panic!("fixture must contain a face sketch"); }; *anchor = None; + let saved = name.clone().unwrap(); for link in &mut sketch.links { if link.auto_face { link.auto_face = false; @@ -2791,30 +2803,20 @@ mod naming { } } old.format = "solidcraft/10".into(); - let mut legacy = Session::new(solidcraft_doc::Document::from_json(&old.to_json()).unwrap()); - assert_eq!(attached(&legacy), Some(10.)); - assert!((top(&mut legacy) - 15.).abs() < 1e-6); + let legacy = Session::new(solidcraft_doc::Document::from_json(&old.to_json()).unwrap()); + let error = |s: &Session, name: &str| s.model.results.iter().find(|r| r.id == s.doc.find_feature(name).unwrap().id).unwrap().error.clone(); + let reference = format!("{}{saved}", solidcraft_doc::naming::LEGACY_MARK); + assert_eq!(error(&legacy, "Top").as_deref().and_then(solidcraft_doc::reselect_parts), Some(("Top", reference.as_str()))); + assert!(error(&legacy, "Peg").is_some()); + assert!(error(&legacy, "Block").is_none()); // An upstream join that trims the certified face: the attachment stays on what is left // of it and never follows the substitute roof (see face_tests for a face covered whole). - for target in [&mut s, &mut legacy] { - run(target, "timeline.roll_to", json!({"feature": "Block"})); - run(target, "sketch.create", json!({"plane": "XY", "name": "B"})); - run(target, "sketch.rectangle.two_point", json!({"p0": [8, -5], "p1": [45, 35]})); - run(target, "sketch.finish", json!({})); - run(target, "solid.extrude", json!({"sketch": "B", "distance": 20, "operation": "join", "name": "Boss"})); - run(target, "timeline.roll_to", json!({})); - } - assert_eq!(attached(&legacy), Some(10.), "historical weak naming retains its saved geometry behavior"); - assert!((top(&mut legacy) - 20.).abs() < 1e-6); - let legacy_reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.doc.to_json()).unwrap()); - assert_eq!(attached(&legacy_reopened), Some(10.)); - assert!((legacy_reopened.model.state().bodies[0].mesh().bounds().max.z - 20.).abs() < 1e-6); - let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, .. }, .. } = - &legacy_reopened.doc.find_feature("Top").unwrap().kind - else { - panic!("saved historical face reference must remain present"); - }; - assert!(anchor.is_none(), "opening old face references must not infer a strict attachment"); + run(&mut s, "timeline.roll_to", json!({"feature": "Block"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "B"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [8, -5], "p1": [45, 35]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "B", "distance": 20, "operation": "join", "name": "Boss"})); + run(&mut s, "timeline.roll_to", json!({})); let failed = |s: &Session, name: &str| s.model.results.iter().find(|r| r.id == s.doc.find_feature(name).unwrap().id).unwrap().error.is_some(); assert!(!failed(&s, "Top")); assert!(!failed(&s, "Peg")); @@ -4088,10 +4090,11 @@ fn extrude_reply_lists_the_bodies_it_created() { assert_eq!(r["created_bodies"], json!(["Ribs", "Ribs (2)", "Ribs (3)"]), "{r}"); } -/// A design saved before format 14 names the bodies past its stored names `BodyN`, as it did when -/// it was saved, so later features that name them still find them (#373). +/// A design saved before format 14 with fewer stored body names than bodies (#373) opens and +/// evaluates: the first body takes its stored name, and every body has a name of its own. (The +/// names the others had when it was saved are not promised.) #[test] -fn a_design_saved_before_format_14_keeps_generic_names_past_body_name() { +fn a_design_saved_before_format_14_with_fewer_body_names_opens_and_names_every_body() { let mut s = Session::default(); run(&mut s, "sketch.create", json!({"plane": "XY", "name": "R"})); for x in [0, 10, 20] { @@ -4109,8 +4112,10 @@ fn a_design_saved_before_format_14_keeps_generic_names_past_body_name() { std::fs::write(&design, legacy.to_string()).unwrap(); let mut old = Session::default(); run(&mut old, "doc.open", json!({"path": design.to_string_lossy()})); + assert!(old.model.results.iter().all(|r| r.error.is_none()), "{:?}", old.model.results); let names: Vec = old.model.state().bodies.iter().map(|b| b.name.clone()).collect(); - assert_eq!(names, ["Ribs", "Body1", "Body2"]); + assert_eq!((names.len(), names.first().map(String::as_str)), (3, Some("Ribs")), "{names:?}"); + assert_eq!(names.iter().collect::>().len(), 3, "{names:?}"); let _ = std::fs::remove_dir_all(&dir); } @@ -4449,12 +4454,12 @@ fn a_side_drawn_in_two_collinear_pieces_extrudes_into_one_face() { assert_eq!(run(&mut s, "inspect.measure", json!({}))["bodies"][0]["kernel"]["faces"], 6); let names: Vec<&str> = f.iter().filter_map(|x| x["name"].as_str()).collect(); assert!(names.contains(&format!("F2:side:{}", pieces[0]).as_str()), "{names:?}"); - // The second piece's name answers for the same face, so a reference made when the side was - // two faces (an edge of the second piece) still finds its edge. + // The extrude made the side from both pieces: the second piece's role names that very face + // too, so an edge named after it is that edge. let st = s.model.state(); let body = st.body("Body1").unwrap(); let edge = format!("F2:side:{}|F2:top", pieces[1]); - let (at, _) = solidcraft_doc::naming::find_edge(body, &edge, geom::Vec3::new(15.0, 0.0, 5.0)).unwrap(); + let at = solidcraft_doc::naming::find_edge(body, &edge, geom::Vec3::new(15.0, 0.0, 5.0)).unwrap(); assert!(at.y.abs() < 1e-9 && (at.z - 5.0).abs() < 1e-9, "{edge} at {at:?}"); // A sketch attaches to the joined side as to any side. assert_eq!(run(&mut s, "sketch.create", json!({"plane": {"face": [15, 0, 2.5]}}))["attachment"], "exact_face"); diff --git a/crates/engine/src/tests/blend_fit.rs b/crates/engine/src/tests/blend_fit.rs index e0af9c813..a4790a13b 100644 --- a/crates/engine/src/tests/blend_fit.rs +++ b/crates/engine/src/tests/blend_fit.rs @@ -24,7 +24,7 @@ fn chamfer_error(s: &Session) -> Option { /// then a 9 mm chamfer on the top edge over one side opening. The openings are 5 mm from the /// edge, so the chamfer runs over their rims: it is cut by them. Of its section, the triangle /// y + (20 − z) <= 9 (area 40.5, along 20: 810), the two openings crossing it hold 80 each -/// (the rig's fillets/1080-chamfer-runs-into-openings-refused): 4000 − (810 − 160) = 3350. +/// (the rig's fillets/1080-chamfer-runs-into-openings-cut-by-them): 4000 − (810 − 160) = 3350. #[test] fn chamfer_through_the_openings_is_cut_by_them() { let mut s = open_fixture(); diff --git a/crates/engine/src/tests/robustness.rs b/crates/engine/src/tests/robustness.rs index 589a44844..4f126969e 100644 --- a/crates/engine/src/tests/robustness.rs +++ b/crates/engine/src/tests/robustness.rs @@ -304,10 +304,15 @@ fn fillet_into_an_earlier_round() { assert!((v - want).abs() < 2.0, "the upright's tangent chain: {v} vs {want}"); } -/// Clean seeds (seed 16: a partial face contact, fused), and the original seed 5 edge contact, -/// kept as two bodies without distortion. +/// Fixed seeds run without a panic and leave valid bodies (seed 16: a partial face contact, +/// fused), and the original seed 5 edge contact is kept as two bodies without distortion. What a +/// seed's steps come to is not compared with what the builds that chose the seeds made (truck's): +/// the kernel's reference is the ladder (`tests/kernel-cases/ladder`). #[test] fn fixed_seeds_run_clean() { + // A panic, a body that is not valid or a step that moved the volume the wrong way; a step the + // kernel refuses is not one. + let clean = |r: &fuzz::Run| !matches!(r.outcome.kind.as_str(), "panic" | "invalid" | "volume"); for seed in FIXED_SEEDS { if *seed == 5 { // Seed 5 originally joined these boxes along only an edge. Accepting it once required @@ -351,11 +356,11 @@ fn fixed_seeds_run_clean() { assert!((total_volume(&s) - want).abs() < 0.2, "{} vs {want}", total_volume(&s)); assert!(s.model.state().bodies.iter().all(|b| b.body.validity().is_empty())); let r = fuzz::run(*seed, 8); - assert!(!r.outcome.is_bug(), "seed {seed}: {:?}\n{}", r.outcome, r.script()); + assert!(clean(&r), "seed {seed}: {:?}\n{}", r.outcome, r.script()); continue; } let r = fuzz::run(*seed, 8); - assert!(!r.outcome.is_bug(), "seed {seed}: {:?}\n{}", r.outcome, r.script()); + assert!(clean(&r), "seed {seed}: {:?}\n{}", r.outcome, r.script()); } } diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs index 780c2b2c8..d886263b9 100644 --- a/crates/io/src/design/native_cache.rs +++ b/crates/io/src/design/native_cache.rs @@ -5,7 +5,7 @@ use super::*; use solidcraft_doc::{ModelState, SavedModel}; -const FORMAT: &str = "solidcraft-model-cache/4"; +const FORMAT: &str = "solidcraft-model-cache/6"; const PRODUCER: &str = "solidcraft-truck-adapter/4"; const MANIFEST: &str = "cache/model.json"; const PAYLOAD: &str = "cache/bodies.bin"; diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 46cdeaf9d..ac134b452 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -502,7 +502,9 @@ fn largest_that_fits(size: f64, blend: impl Fn(f64) -> Result) -> Result { lo = mid; best = Some(b); diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs index 9b8e6ac13..79b3512a0 100644 --- a/crates/kernel/src/blend_corner.rs +++ b/crates/kernel/src/blend_corner.rs @@ -298,12 +298,19 @@ mod tests { } } - /// A chamfer of a basin's rim loop whose leg would run off the 1 mm rim over the slab's front - /// edge is refused as too large, the kind a fit can reduce. (The largest size that fits is - /// the doc layer's to name; it and the loop's blends that fit, with their exact mitred - /// volumes, are graded by the rig's fillets/1080-*-equal-slope-basin-* cases.) + /// A chamfer 2 of a basin's rim loop (walls all sloping 10 over 20, the front rim 1 mm wide) + /// whose front leg runs off the rim over the slab's front edge builds, cut by the front face + /// (the owner's ruling of 2026-10-30, d7: a chamfer that reaches or runs past a rim builds). + /// Sliced at depth t below the top, each chamfer's strip beside its wall is + /// w(t) = d (1 − t/δ) wide, δ = d / √(1 + k²) with k = 1/2 the walls' run over drop; the four + /// meet in mitres at the rim's corners, so the section removed is the pocket's rectangle at t, + /// [20 + t/2, 80 − t/2] × [1 + t/2, 50 − t/2], grown by w(t) on every side and clipped to the + /// slab's front face y >= 0, less that rectangle. Its area is quadratic in t between δ and + /// where the front strip's edge 1 + t/2 − w(t) crosses y = 0, so Simpson's rule is exact on + /// each piece: 375.673069 taken from V0 = 140333.333333 (the prismatoid), 139957.660264. #[test] - fn a_rim_loop_chamfer_running_off_its_rim_is_refused() { + #[ignore = "fails until SMLib builds the cliff overflow of a blended loop: CloseRemovalRegion refuses it (SM_FILERR_NO_ROOM, its fillet boundary closes on one face)"] + fn a_rim_loop_chamfer_running_off_its_rim_builds() { use solidcraft_geom::{Loop2, Plane, Vec2}; let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); @@ -312,10 +319,23 @@ mod tests { .unwrap(); let basin = crate::boolean(&slab, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); let picks = [Vec3::new(50.0, 1.0, 30.0), Vec3::new(80.0, 27.0, 30.0), Vec3::new(50.0, 50.0, 30.0), Vec3::new(20.0, 27.0, 30.0)]; - match crate::chamfer(&basin, &picks, 2.0) { - Err(KernelError::TooLarge(_)) => {} - Err(e) => panic!("refused, but not as too large: {e}"), - Ok(_) => panic!("a chamfer whose leg runs off the rim was built"), - } + let (d, k) = (2.0_f64, 0.5_f64); + let delta = d / (1.0 + k * k).sqrt(); + let area = |t: f64| { + let w = d * (1.0 - t / delta); + let (x0, x1, y0, y1) = (20.0 + k * t, 80.0 - k * t, 1.0 + k * t, 50.0 - k * t); + (x1 - x0 + 2.0 * w) * (y1 + w - (y0 - w).max(0.0)) - (x1 - x0) * (y1 - y0) + }; + // 1 + k t − d (1 − t/δ) = 0. + let crossing = (d - 1.0) / (k + d / delta); + let removed: f64 = + [(0.0, crossing), (crossing, delta)].iter().map(|&(a, b)| (b - a) / 6.0 * (area(a) + 4.0 * area(0.5 * (a + b)) + area(b))).sum(); + assert!((removed - 375.673069).abs() < 1e-6, "{removed}"); + let before = crate::measure(&basin).unwrap().volume; + assert!((before - 140333.333333).abs() < 1e-5, "{before}"); + let result = crate::chamfer(&basin, &picks, d).unwrap_or_else(|e| panic!("{e}")); + assert!(result.validity().is_empty(), "{:?}", result.validity()); + let v = crate::measure(&result).unwrap().volume; + assert!((v - (before - removed)).abs() < 1e-6 * before, "{v} vs {}", before - removed); } } diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs index 757b6ff81..39229c613 100644 --- a/crates/kernel/src/blend_smlib.rs +++ b/crates/kernel/src/blend_smlib.rs @@ -357,12 +357,20 @@ mod imp { SmError::NoRoom => KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow")), e => failed(what, "operation", e), })?; - let check = r.check(CheckLevel::All).map_err(|e| failed(what, "check", e))?; - if !check.is_valid() { - let input_fails = sb.check(CheckLevel::All).is_ok_and(|c| !c.is_valid()); - let step = - if input_fails { "SMLib's check refuses the result (the input already fails it)" } else { "SMLib's check refuses the result" }; - return Err(failed(what, step, check)); + // Checked here unless the evaluation's validation mode leaves it to the feature's end + // (`crate::validation`). + let step = crate::validation::step(); + if step == crate::validation::Step::Check { + let check = r.check(CheckLevel::All).map_err(|e| failed(what, "check", e))?; + if !check.is_valid() { + let input_fails = sb.check(CheckLevel::All).is_ok_and(|c| !c.is_valid()); + let step = if input_fails { + "SMLib's check refuses the result (the input already fails it)" + } else { + "SMLib's check refuses the result" + }; + return Err(failed(what, step, check)); + } } let (out, result_order) = body_from_smlib_ordered(&r)?; let history = match (order, &result_order) { @@ -380,7 +388,13 @@ mod imp { }, _ => None, }; - Ok((out.with_checked_history(history, &record::counts(&[body])).inherit_regularization_protection(body), extra, result_order)) + let out = out.with_checked_history(history, &record::counts(&[body])).inherit_regularization_protection(body); + let out = if step == crate::validation::Step::Defer { + out.left_unchecked(&format!("SMLib {what}"), crate::validation::Checked::AsIs, r) + } else { + out + }; + Ok((out, extra, result_order)) }) } diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index f781ab85a..74bfcbd73 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -55,6 +55,10 @@ pub struct Body { /// Meshes of this record kept for reuse, set by [`Body::keeping_meshes`]: a check that /// intersects one large body with many small ones meshes it at the same tolerance each time. pub(crate) meshes: Option>, + /// The SMLib result this body was decoded from, when the step that made it left SMLib's + /// check to the end of its feature ([`crate::validation`]): checked there as the step's own + /// check would have, then let go. Answers only for this record. + pub(crate) unchecked: Option>, } /// The meshes made of one record (see [`Body::keeping_meshes`]), by tolerance and angle. They @@ -473,9 +477,17 @@ impl Body { history: None, display_of: None, meshes: None, + unchecked: None, } } + /// This body with `result`, the SMLib result of the step `what` it was decoded from, whose + /// check that step left to the end of its feature ([`crate::validation::check_kept`]). + pub(crate) fn left_unchecked(self, what: &str, how: crate::validation::Checked, result: solidcraft_smlib::Brep) -> Body { + let unchecked = crate::validation::Unchecked::new(&self.record, what, how, result); + Body { unchecked: Some(std::sync::Arc::new(unchecked)), ..self } + } + /// The body of a schema 4 record (a solid, or a surface body of open shells): checked for /// structure (references, loops, regions, canonical order; a record from a file is checked /// against the file budgets where it is read). Its faces face as the diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 6295c4fdd..10f0c529a 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -151,6 +151,7 @@ mod topo; mod tspline; #[cfg(test)] mod untouched_faces_tests; +mod validation; mod validity; pub mod watch; @@ -234,6 +235,7 @@ pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_ pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at, material_in_ring}; pub use topo::{TopoCounts, merged_topology, seam_flags}; pub use tspline::tspline_sheet; +pub use validation::{Validation, check_kept, validating}; pub use validity::{SmlibCheck, Validity, smlib_built, smlib_dump_dir, validity}; #[derive(Debug, Clone, PartialEq, thiserror::Error)] diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index f7d06860d..d491d19eb 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -156,9 +156,22 @@ pub(crate) fn smlib_record_ordered( /// Where SMLib's faces and edges of `brep` (imported from `record`) are in the record's order: /// `None` where SMLib's export does not number them as the record does. +/// +/// SMLib's export is in canonical order, and `order` says where SMLib's own face and edge `i` +/// went in it. Where the canonical record numbers them as `record` does, `order` maps SMLib's +/// to the record's. Otherwise SMLib may still keep the record's own order (an import lists +/// SMLib's faces and edges in the record's order, and canonical order can list them otherwise, +/// a tube's seam edges among them): the export put back in SMLib's order then numbers them as +/// `record` does, and SMLib's face and edge `i` are the record's `i`. fn numbering(record: &solidcraft_geom::brep::Brep, brep: &solidcraft_smlib::Brep) -> Option { match brep.to_native_ordered() { - Ok((back, order)) => same_numbering(record, &back).then_some(order), + Ok((back, order)) => { + if same_numbering(record, &back) { + return Some(order); + } + let in_smlib_order = in_smlib_order(&back, &order)?; + same_numbering(record, &in_smlib_order).then(solidcraft_smlib::history::Order::default) + } Err(e) => { log::debug!(target: "smlib", "no order for an operand: {e}"); None @@ -166,6 +179,50 @@ fn numbering(record: &solidcraft_geom::brep::Brep, brep: &solidcraft_smlib::Brep } } +/// The canonical record `back` with its faces and edges in SMLib's own order (`order`: where +/// SMLib's face and edge `i` are in `back`), each loop naming its edges by SMLib's numbers. +/// `None` where `order` is not a renumbering of `back`'s faces and edges (an edge split into +/// pieces where solids touch along it is more than one record edge). +fn in_smlib_order(back: &solidcraft_geom::brep::Brep, order: &solidcraft_smlib::history::Order) -> Option { + use solidcraft_geom::brep::Loop; + let permutation = |to: &[usize], n: usize| -> Option> { + if to.is_empty() { + return Some((0..n).collect()); + } + let mut from = vec![usize::MAX; n]; + for (i, &k) in to.iter().enumerate() { + let slot = from.get_mut(k)?; + if *slot != usize::MAX { + return None; + } + *slot = i; + } + (to.len() == n).then_some(from) + }; + if !order.pieces.is_empty() { + return None; + } + // `faces_from[k]`: SMLib's number of `back`'s face k; likewise for edges. + let faces_from = permutation(&order.faces, back.faces.len())?; + let edges_from = permutation(&order.edges, back.edges.len())?; + let mut out = back.clone(); + for (k, face) in back.faces.iter().enumerate() { + let mut face = face.clone(); + for l in &mut face.loops { + if let Loop::Edges { edges } = l { + for e in edges.iter_mut() { + e.edge = u32::try_from(*edges_from.get(usize::try_from(e.edge).ok()?)?).ok()?; + } + } + } + *out.faces.get_mut(*faces_from.get(k)?)? = face; + } + for (k, edge) in back.edges.iter().enumerate() { + *out.edges.get_mut(*edges_from.get(k)?)? = edge.clone(); + } + Some(out) +} + /// Whether two records of one body number its faces, edges and vertices alike: the same loops of /// the same edges, the same edge ends, and each vertex where the other's is. fn same_numbering(a: &solidcraft_geom::brep::Brep, b: &solidcraft_geom::brep::Brep) -> bool { diff --git a/crates/kernel/src/par.rs b/crates/kernel/src/par.rs index b18ea88bb..00aa24a6e 100644 --- a/crates/kernel/src/par.rs +++ b/crates/kernel/src/par.rs @@ -8,7 +8,9 @@ use crate::{Result, guard}; /// thread. Waking the pool's workers costs tens of microseconds, so callers ask for it only /// when the items carry more work than that (decided from the work, not the item count). pub(crate) fn map(what: &'static str, items: &[T], parallel: bool, f: impl Fn(&T) -> Result + Sync) -> Vec> { - let one = |item: &T| guard(what, || f(item)); + // The workers run under the caller's validation mode (`crate::validation`). + let scope = crate::validation::current(); + let one = |item: &T| crate::validation::within(scope.clone(), || guard(what, || f(item))); // The browser build has no worker pool: everything runs on the calling thread. #[cfg(target_arch = "wasm32")] let _ = parallel; @@ -53,7 +55,8 @@ pub fn map_with_local_pools(items: &[T], max_threads: usize, f let _ = cell.set(pool); } let pool = cell.get().ok_or_else(|| crate::KernelError::Failed("missing mesh worker".into()))?; - pool.install(|| guard("mesh worker", || f(item))) + let scope = crate::validation::current(); + pool.install(|| crate::validation::within(scope, || guard("mesh worker", || f(item)))) }) }; #[cfg(target_arch = "wasm32")] @@ -67,7 +70,9 @@ pub fn map_with_local_pools(items: &[T], max_threads: usize, f /// `f` over `items` as [`for_each_on_threads`] runs it, results in item order (`None` where an /// item panicked). pub fn map_on_threads(items: &[T], max_threads: usize, f: impl Fn(&T) -> R + Sync) -> Vec> { - let one = |item: &T| guard("parallel item", || Ok(f(item))).ok(); + // The threads run under the caller's validation mode (`crate::validation`). + let scope = crate::validation::current(); + let one = |item: &T| crate::validation::within(scope.clone(), || guard("parallel item", || Ok(f(item))).ok()); #[cfg(not(target_arch = "wasm32"))] { use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/crates/kernel/src/smlib_boolean.rs b/crates/kernel/src/smlib_boolean.rs index 87f41d0d3..df079532e 100644 --- a/crates/kernel/src/smlib_boolean.rs +++ b/crates/kernel/src/smlib_boolean.rs @@ -13,6 +13,7 @@ mod smlib { use crate::history::History; use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; use crate::ops::BoolOp; + use crate::validation::{Checked, Step}; use crate::{KernelError, Result, record}; fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { @@ -34,7 +35,7 @@ mod smlib { BoolOp::Intersect => BooleanOp::Intersect, }; let Some(r) = ta.boolean(&tb, kind).map_err(|e| failed("operation", e))? else { return Ok(None) }; - checked(&r, &[&sa, &sb])?; + let step = checked(&r, &[&sa, &sb])?; let (body, or) = body_from_smlib_ordered(&r)?; let history = match (oa, ob, or) { (Some(oa), Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[oa, ob], &or).map(Some).unwrap_or_else(|e| { @@ -43,7 +44,7 @@ mod smlib { }), _ => None, }; - Ok(Some(with_history(body, history, a, b))) + Ok(Some(left(with_history(body, history, a, b), step, r))) } /// The union of `bodies` in one SMLib call, each tagged as its own operand, checked once: @@ -68,7 +69,7 @@ mod smlib { let refs: Vec<&solidcraft_smlib::Brep> = tagged.iter().collect(); let r = solidcraft_smlib::Brep::union_all(&refs).map_err(|e| failed("operation", e))?; let operand_refs: Vec<&solidcraft_smlib::Brep> = operands.iter().collect(); - checked(&r, &operand_refs)?; + let step = checked(&r, &operand_refs)?; let (body, or) = body_from_smlib_ordered(&r)?; let history = match (orders, or) { (Some(orders), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&orders, &or).map(Some).unwrap_or_else(|e| { @@ -77,25 +78,30 @@ mod smlib { }), _ => None, }; - Ok(body.with_checked_history(history, &record::counts(bodies))) + Ok(left(body.with_checked_history(history, &record::counts(bodies)), step, r)) } - /// An error unless SMLib's check accepts `r`, the result of combining `operands`. - fn checked(r: &solidcraft_smlib::Brep, operands: &[&solidcraft_smlib::Brep]) -> Result<()> { + /// `body`, decoded from `r`, keeping `r` for the check at the end of its feature when the + /// step left it there. + fn left(body: Body, step: Step, r: solidcraft_smlib::Brep) -> Body { + if step == Step::Defer { body.left_unchecked("SMLib boolean", Checked::Combined, r) } else { body } + } + + /// An error unless SMLib's check accepts `r`, the result of combining `operands` (checked + /// here unless the evaluation's validation mode leaves it to the feature's end, + /// `crate::validation`): what was done with the check. + fn checked(r: &solidcraft_smlib::Brep, operands: &[&solidcraft_smlib::Brep]) -> Result { + let step = crate::validation::step(); + if step != Step::Check { + return Ok(step); + } // Solids touching each other along an edge or at a vertex come back as one non-manifold // body, which the export splits into separate solids: SMLib's check is of those, imported // as given (its check of the touching arrangement itself refuses the radial order of // faces round an edge they share). - let manifold = r.is_manifold_solid().map_err(|e| failed("check", e))?; - let check = if manifold { - r.check(CheckLevel::All).map_err(|e| failed("check", e))? - } else { - let record = r.to_native().map_err(|e| failed("export", e))?; - let split = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| failed("the separate solids", e))?; - split.check(CheckLevel::All).map_err(|e| failed("check", e))? - }; + let check = crate::validation::check_result(r, Checked::Combined).map_err(|e| KernelError::Failed(format!("SMLib boolean: {e}")))?; if check.is_valid() { - return Ok(()); + return Ok(step); } // Whether an operand failed it already says whose the fault is. let failing: Vec = operands diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rs index cbaf1e922..bf27ffd44 100644 --- a/crates/kernel/src/smlib_sweeps.rs +++ b/crates/kernel/src/smlib_sweeps.rs @@ -155,20 +155,26 @@ mod imp { segs.iter().map(|s| curve(plane, s)).collect() } - /// The kernel body of an SMLib result SMLib's own check finds valid. - fn body_of(brep: &Brep, what: &str) -> Result { - let check = brep.check(CheckLevel::All).map_err(|e| failed(what, e))?; - if !check.is_valid() { - return Err(failed(what, format!("SMLib's check refuses the result: {check}"))); + /// The kernel body of an SMLib result SMLib's own check finds valid (checked here unless the + /// evaluation's validation mode leaves it to the feature's end, `crate::validation`). + fn body_of(brep: Brep, what: &str) -> Result { + use crate::validation::{Checked, Step}; + let step = crate::validation::step(); + if step == Step::Check { + let check = brep.check(CheckLevel::All).map_err(|e| failed(what, e))?; + if !check.is_valid() { + return Err(failed(what, format!("SMLib's check refuses the result: {check}"))); + } } - crate::native::body_from_smlib(brep) + let body = crate::native::body_from_smlib(&brep)?; + Ok(if step == Step::Defer { body.left_unchecked(&format!("SMLib {what}"), Checked::AsIs, brep) } else { body }) } /// The body (a solid or a sheet) a schema 4 record describes, taken by SMLib as a /// modeller's own record (no healing) and checked there. pub(crate) fn body_from_record(record: &solidcraft_geom::brep::Brep, what: &str) -> Result { let brep = Brep::from_record(record, true).map_err(|e| failed(what, e))?; - body_of(&brep, what) + body_of(brep, what) } /// The sketch segments `segs` on `plane` projected along `direction` onto the face of @@ -236,7 +242,7 @@ mod imp { /// a sphere revolves. pub(crate) fn sphere(center: Vec3, radius: f64) -> Result { let brep = Brep::make_sphere(p(center), radius).map_err(|e| failed("sphere", e))?; - let body = body_of(&brep, "sphere")?; + let body = body_of(brep, "sphere")?; let faces = body.face_count(); Ok(record::attach(body, &[], Some(vec![record::profile(&[0usize]); faces]), &[])) } @@ -415,7 +421,7 @@ mod imp { Brep::extrude(&curves(&knee, pieces)?, p(dir), distance - foot, lean, corner(d.corner), true).map_err(|e| failed("extrude", e))?; let brep = prism.boolean(&slope, solidcraft_smlib::BooleanOp::Union).map_err(|e| failed("extrude", e))?; let brep = brep.ok_or_else(|| failed("extrude", "nothing is left"))?; - let body = body_of(&brep, "extrude")?; + let body = body_of(brep, "extrude")?; // The caps and the foot's walls from the base; the sloping walls (and the foot's again) // from the edges at the knee, which both stand on. let low = roles(&body, &base, Some(&top), &edges, &[], false)?; @@ -438,7 +444,7 @@ mod imp { let lean = draft.map_or(0.0, |d| -d.taper); let rule = draft.map_or(DraftCorner::default(), |d| corner(d.corner)); let brep = Brep::extrude(&c, p(dir), distance, lean, rule, true).map_err(|e| failed("extrude", e))?; - let body = body_of(&brep, "extrude")?; + let body = body_of(brep, "extrude")?; // Half-way along a straight wall lies over its segment; a drafted one has moved. let inside = if draft.is_none() { seeds(&base, pieces, |q| q + dir * (distance * 0.5)) } else { Vec::new() }; let roles = roles(&body, &base, Some(&top), &edges, &inside, false)?; @@ -495,7 +501,7 @@ mod imp { .map_err(|e| failed("extrude", e))? .ok_or_else(|| KernelError::Invalid("the draft leaves nothing of the profile".into()))?; } - let body = body_of(&brep, "extrude")?; + let body = body_of(brep, "extrude")?; let base = plane.offset(from); let top = plane.offset(from + sign.signum() * distance); let low = roles(&body, &base, Some(&top), &seeds(&base, all, |q| q), &[], false)?; @@ -574,7 +580,7 @@ mod imp { let turn = turn.min(std::f64::consts::TAU); let c = curves(plane, pieces)?; let brep = Brep::revolve(&c, p(origin), p(k), turn, true).map_err(|e| failed("revolve", e))?; - let body = body_of(&brep, "revolve")?; + let body = body_of(brep, "revolve")?; let size = body.size().max(1e-9); let off_axis = |q: Vec3| { let w = q - origin; @@ -639,7 +645,7 @@ mod imp { return cornered(plane, pieces, path, &runs, translate); } let (brep, [_, middle, last]) = swept(plane, pieces, path, translate)?; - let body = body_of(&brep, "sweep")?; + let body = body_of(brep, "sweep")?; // The walls known by the profile carried half way (past the start's edges: a wall the // start touches by no edge, as round a closed path, and walls along later path segments). let inside = seeds(plane, pieces, |q| apply(&middle, q)); @@ -852,7 +858,7 @@ mod imp { } } let brep = body.ok_or_else(|| KernelError::Invalid("empty path".into()))?; - let body = body_of(&brep, "sweep")?; + let body = body_of(brep, "sweep")?; let roles = roles(&body, plane, (!closed).then_some(&pose), &seeds(plane, pieces, |q| q), &inside, false)?; with_history(body, &roles, pieces) } @@ -1015,7 +1021,7 @@ mod imp { }) .collect(); let brep = Brep::sweep_stations(&c, &maps, if closed { Ends::Joined } else { Ends::Capped }).map_err(|e| failed("sweep", e))?; - let body = body_of(&brep, "sweep")?; + let body = body_of(brep, "sweep")?; let mid = st.get(st.len() / 2).copied().unwrap_or(*last); let inside = seeds(plane, &pieces, |q| mid.at + mid.apply(q - s0)); let roles = if closed { @@ -1227,7 +1233,7 @@ mod imp { crate::sweep_path::closing_offset(plane, l, &[to_station(&IDENTITY), to_station(&at_start)])?; } } - let body = body_of(&brep, "sweep")?; + let body = body_of(brep, "sweep")?; let roles = if closed { roles(&body, &plane.offset(size * 10.0), None, &[], &inside, false)? } else { @@ -1382,7 +1388,7 @@ mod imp { /// across them; `sections` and `first` as [`loft`] takes them name the faces. fn loft_through(sections: &[(Plane, Vec)], first: usize, curves: &[Vec], degree: u32) -> Result { let brep = Brep::loft(curves, degree, true).map_err(|e| failed("loft", e))?; - let body = body_of(&brep, "loft")?; + let body = body_of(brep, "loft")?; let (Some((start, lead)), Some(last)) = (sections.get(first), sections.get(if first == 0 { sections.len().saturating_sub(1) } else { 0 })) else { return Err(KernelError::Invalid("loft sections".into())); @@ -1442,7 +1448,7 @@ mod imp { pub(crate) fn loft_to_point(plane: &Plane, pieces: &[Piece], apex: Vec3) -> Result { let c = curves(plane, pieces)?; let brep = Brep::loft_to_point(&c, p(apex)).map_err(|e| failed("loft to a point", e))?; - let body = body_of(&brep, "loft to a point")?; + let body = body_of(brep, "loft to a point")?; let roles = roles(&body, plane, None, &seeds(plane, pieces, |q| q), &[], false)?; with_history(body, &roles, pieces) } @@ -1454,7 +1460,7 @@ mod imp { // Walls within a ten-thousandth of the pitch of the true screw surfaces. let tolerance = (pitch.abs() * 1e-4).clamp(1e-6, 1e-2); let brep = Brep::screw_sweep(&c, p(origin), p(axis), pitch, turns, tolerance).map_err(|e| failed("screw sweep", e))?; - let body = body_of(&brep, "screw sweep")?; + let body = body_of(brep, "screw sweep")?; let roles = roles(&body, plane, None, &seeds(plane, pieces, |q| q), &[], true)?; with_history(body, &roles, pieces) } @@ -1474,7 +1480,7 @@ mod imp { let tolerance = (pitch.abs() * 1e-4).clamp(1e-6, 1e-2); let brep = Brep::screw_sweep_radial(&c, p(origin), p(axis), pitch, turns, law, tolerance).map_err(|e| failed("screw sweep with a radial law", e))?; - let body = body_of(&brep, "screw sweep")?; + let body = body_of(brep, "screw sweep")?; let roles = roles(&body, plane, None, &seeds(plane, pieces, |q| q), &[], true)?; with_history(body, &roles, pieces) } diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index 8b03229ed..1a4c79961 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -57,7 +57,7 @@ pub struct ImportedBody { pub file_faces: usize, /// No B-rep could be made of the whole solid, and this is why (the import's warnings say so /// too, naming each face left out): `body` is an open surface body of the solid's exact faces - /// but those, or a mesh body of them where no surface body could be made of them. + /// but those. pub refused: Option, } @@ -99,10 +99,11 @@ pub struct StepImport { #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum IssueKind { - /// No body could be made of the part: it is not in the design. + /// The part could not be read from the file: it is not in the design. NotImported, - /// No solid could be made of the part: it is shown as a mesh of its faces. - ShownAsMesh, + /// The kernel refuses the part's B-rep, its faces' too: it is not in the design, and the + /// warning gives the kernel's reason. + Refused, /// No solid could be made of the part: it came in as surfaces of its faces. ImportedAsSurfaces, /// A face of the part could not be read or made, and is left out. @@ -365,6 +366,12 @@ impl Reader { false } + /// `item`'s part is not in the design: the kernel refuses its B-rep, for `why`. + fn refused(&mut self, item: u64, why: &str) { + let label = self.label(item); + self.note(IssueKind::Refused, Some(item), 0, format!("{label}: not imported: {why}")); + } + /// A warning about the file as a whole. fn warn(&mut self, msg: impl Into) { self.note(IssueKind::File, None, 0, msg); @@ -788,8 +795,7 @@ impl Reader { } if let Some(again) = self.unreadable.get(&item) { if let Some(msg) = again.clone() { - let label = self.label(item); - self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}")); + self.refused(item, &msg); } continue; } @@ -816,8 +822,7 @@ impl Reader { None => { if let Some(again) = self.unreadable.get(&item) { if let Some(msg) = again.clone() { - let label = self.label(item); - self.warn(format!("{label}: not imported: {msg}")); + self.refused(item, &msg); } continue; } @@ -840,9 +845,7 @@ impl Reader { if let Some(failed) = read { let label = self.label(item); if let Some(why) = &part.refused { - let kind = if part.body.is_mesh() { IssueKind::ShownAsMesh } else { IssueKind::ImportedAsSurfaces }; - let words = if part.body.is_mesh() { "shown as a mesh" } else { "imported as surfaces" }; - self.note(kind, Some(item), 0, format!("{label}: {words}: {why}")); + self.note(IssueKind::ImportedAsSurfaces, Some(item), 0, format!("{label}: imported as surfaces: {why}")); } for f in &failed { let (kind, faces, f) = match f { @@ -924,8 +927,12 @@ impl Reader { }); } Err(parallel::Failure { read, msg }) => { - let label = self.label(item); - self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}")); + if read { + let label = self.label(item); + self.note(IssueKind::NotImported, Some(item), 0, format!("{label}: not imported: {msg}")); + } else { + self.refused(item, &msg); + } // Later instances don't read the item again. if !self.oriented.contains_key(&item) { self.unreadable.insert(item, (!read).then_some(msg)); diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rs index 0761251a1..e2b32c13d 100644 --- a/crates/kernel/src/step_in/parallel.rs +++ b/crates/kernel/src/step_in/parallel.rs @@ -27,8 +27,7 @@ pub(super) struct Part { /// The file face of each kernel face. pub face_origin: Vec, /// No B-rep could be made of the whole solid, and this is why: the body is a surface body of - /// the faces that read ([`surface_part`]), or, where none could be made of them, a mesh of - /// them ([`mesh_part`]). + /// the faces that read ([`surface_part`]). pub refused: Option, } @@ -204,9 +203,9 @@ const MAX_LEFT_OUT_ROUNDS: usize = 8; /// [`MAX_LEFT_OUT_ROUNDS`] reads). A face is only ever left out where a refusal names it. /// 2. Where a refusal names no face of the solid: the faces that read alone, stitched by SMLib /// into one surface body (their edges sewn at ten times their tolerance). -/// 3. Where SMLib cannot stitch them either: a mesh of them ([`mesh_part`]). /// -/// With no face to import, the solid stays refused. +/// Where SMLib cannot stitch them either, or there is no face to import, the solid stays refused +/// with the reason it was: a B-rep SMLib refuses is never kept as a mesh of its faces. fn surface_part(ex: &Exchange, item: u64, units: Units, refused: Failure) -> std::result::Result<(Part, Vec), Failure> { let _span = solidcraft_profile::span("import", "step.refused_surfaces"); let trims = &solidcraft_smlib::pcurves::SmlibTrims; @@ -256,13 +255,12 @@ fn surface_part(ex: &Exchange, item: u64, units: Units, refused: Failure) -> std Err(e) => notes.push(Note::LeftOut(format!("left out: {}", e.to_string().trim_start_matches("the operation failed: ")))), } } - match stitched_part(&pieces, faces.len(), &refused.msg) { - Ok(part) => Ok((part, notes)), - Err(e) => { - log::debug!(target: "step", "item #{item}: its faces not stitched ({e}); meshed instead"); - mesh_part(&pieces, faces.len(), notes, refused) - } - } + // Where SMLib cannot stitch them either, the solid is refused with the reason it was. + let part = stitched_part(&pieces, faces.len(), &refused.msg).map_err(|e| { + log::debug!(target: "step", "item #{item}: its faces not stitched ({e})"); + refused + })?; + Ok((part, notes)) } /// The one-face surface bodies `pieces` (each with its file face) stitched by SMLib into one @@ -290,37 +288,6 @@ fn stitched_part(pieces: &[(u64, Body)], file_faces: usize, refused: &str) -> cr Ok(Part { body, closed, file_faces, face_origin, refused: Some(refused.to_string()) }) } -/// The one-face surface bodies `pieces` meshed by the planner, their triangles together a mesh -/// body: no B-rep (modelling operations refuse it), for a solid whose faces SMLib could not -/// stitch either. Faces that cannot be meshed are left out, each named in the notes; with no -/// face to show, the solid stays refused. -fn mesh_part(pieces: &[(u64, Body)], file_faces: usize, mut notes: Vec, refused: Failure) -> std::result::Result<(Part, Vec), Failure> { - let _span = solidcraft_profile::span("import", "step.refused_mesh"); - // Every face at the display tolerance of the whole solid. - let bounds: solidcraft_geom::Aabb3 = pieces.iter().flat_map(|(_, b)| b.record().vertices.iter().map(|v| crate::body::v3(v.point))).collect(); - let size = if bounds.is_empty() { 0.0 } else { bounds.diagonal() }; - let tol = crate::MeshTolerance::display_of(if size.is_finite() { size } else { 0.0 }); - let (mut positions, mut triangles) = (Vec::new(), Vec::new()); - for (face, b) in pieces { - match b.mesh(&tol) { - Ok(m) if !m.triangles.is_empty() => { - let Ok(base) = u32::try_from(positions.len()) else { break }; - positions.extend_from_slice(&m.positions); - triangles.extend(m.triangles.iter().map(|t| t.map(|i| i.saturating_add(base)))); - } - Ok(_) => notes.push(Note::LeftOut(format!("left out: face #{face}: no triangles"))), - Err(e) => notes.push(Note::LeftOut(format!("left out: face #{face}: {}", e.to_string().trim_start_matches("the operation failed: ")))), - } - } - if triangles.is_empty() { - return Err(Failure { msg: format!("{} (no face could be shown as a mesh either)", refused.msg), ..refused }); - } - let body = crate::meshbody::mesh_body(&positions, &triangles) - .map_err(|e| Failure { msg: format!("{} (its mesh: {e})", refused.msg), read: refused.read })?; - let closed = body.is_closed_mesh(); - Ok((Part { body, closed, file_faces, face_origin: Vec::new(), refused: Some(refused.msg) }, notes)) -} - /// Prepare `jobs`, the results in the jobs' order. Solids still to read and orient (the slow /// part) are shared out between up to `workers` threads, each taking the next job when it is /// done with one, so one large part does not hold up the rest. diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 606f55609..99049a2c4 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -490,6 +490,17 @@ fn offset_surface_cube_import_is_closed_and_editable() { assert!(rel(measure(&result).unwrap().volume, 1000.0 - 40.0 * std::f64::consts::PI) < 1e-3); } +/// A solid whose B-rep SMLib refuses, its faces too (here every SMLib call: the build has no +/// SMLib), is refused with the kernel's reason, naming the solid. It once came in as a mesh of +/// its faces, which the planner could still triangulate. +#[cfg(not(feature = "smlib"))] +#[test] +fn a_solid_smlib_refuses_with_its_faces_is_refused_not_meshed() { + let text = format!("{HEAD}{}#60=SHAPE_REPRESENTATION('',(#101),$);\n{TAIL}", cube_entities()); + let why = step_import(&text).map(|imp| imp.warnings).unwrap_err().to_string(); + assert!(why.contains("solid 'Cube': not imported: ") && why.contains("SMLib"), "{why}"); +} + /// A hand-written unit cube brep (`#100`…) in a representation with the given unit and items. fn cube_entities() -> String { let mut s = String::new(); @@ -1748,7 +1759,9 @@ fn periodic_knot_tube(first: u64, x: f64, r: f64, h: f64) -> (String, u64) { /// Two such tubes far apart in one body: the body's size sets a chord tolerance coarse beside /// the tubes, and meshing a face at it divided the surface's whole parameter box, whose /// corners lay outside the domain. The division never converged there (#1374's recursion), -/// and the import grew by gigabytes without end. +/// and the import grew by gigabytes without end. The sheet comes in as SMLib's B-rep of its two +/// faces, each the file's face (SMLib lists the seam edges in another canonical order than the +/// file, and keeps the file's own order), each a cylinder's side. #[test] fn periodic_knot_tube_faces_import_and_mesh() { let t0 = std::time::Instant::now(); @@ -1760,9 +1773,16 @@ fn periodic_knot_tube_faces_import_and_mesh() { ); let imp = step_import(&text).unwrap(); assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); - let m = measure(&imp.bodies[0].body).unwrap(); + let tubes = &imp.bodies[0]; + assert!(tubes.refused.is_none() && !tubes.body.is_mesh() && tubes.body.is_surface(), "{:?} {:?}", tubes.refused, imp.warnings); + assert_eq!(tubes.face_origin, vec![fa, fb], "{:?}", imp.warnings); + // Each face is the file's quadratic circle of radius r (corner weights √2/2 to 12 digits, + // a radius off by under 1e-12 of r) moved straight along its axis by h: a cylinder's side, + // 2π r h. SMLib integrates to 1e-8. + let m = measure(&tubes.body).unwrap(); let area = 2.0 * std::f64::consts::TAU * r * h; - assert!(rel(m.area, area) < 0.02, "area {} (expected {area})", m.area); + assert!(rel(m.area, area) < 1e-6, "area {} (expected {area})", m.area); + assert_eq!(tubes.body.unmeshed_faces(), 0); assert!(t0.elapsed().as_secs_f64() < 60.0, "took {:?}", t0.elapsed()); } diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index ab81cc996..b0a1cf739 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -1104,31 +1104,78 @@ fn chamfer_sloped_basin_rim() { assert!(mesh.contains(Vec3::new(50.0, 3.5, 28.0))); } -/// A chamfer wider than a basin's thin rim (`chamfer_sloped_basin_rim`'s basin with the rim -/// `margin` wide at the top) would run its leg off the rim's top, over the slab's front edge; as -/// wide as the rim it would use the rim's top up. Both are refused as too large, the kind a fit -/// can reduce, the body unchanged (the owner's blend-overflow ruling, 2026-10-30). The largest -/// size that fits is named by the doc layer (`with_largest_fit`) and graded, with the chamfers -/// that fit, by the rig's fillets/1080-chamfer-sloped-basin-* cases. -#[test] -fn chamfer_wider_than_sloped_basin_rim_is_refused() { +/// `chamfer_sloped_basin_rim`'s basin with its front rim `margin` wide at the top. +fn sloped_basin(margin: f64) -> Body { let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]); - let basin = |margin: f64| { - let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); - let pocket = - loft(&[(Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)), (Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0))]) - .unwrap(); - boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap() + let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap(); + let pocket = + loft(&[(Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)), (Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0))]).unwrap(); + boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap() +} + +/// What an equal-distance chamfer `d` of [`sloped_basin`]'s rim edge at y = `margin` takes, built +/// as if the top went on past the slab's front face y = 0 and then cut by it (the owner's ruling +/// of 2026-10-30, d7: a chamfer that reaches or runs past a rim builds). Its section in (y, z) is +/// the triangle of the edge (margin, 30), the top's contact (margin − d, 30) and the wall's +/// contact d down the wall towards (20, 10) (run 20 − margin over the drop 20), clipped to +/// y >= 0. At height z it runs between the sloped end walls x = 20 + (30 − z)/2 and +/// 80 − (30 − z)/2 (planar, x by z alone), which cut it, so its length there is 30 + z: it takes +/// ∬ (30 + z) dy dz over the clipped section, area · 30 + ∬ z, both exact by the shoelace sums +/// over the polygon (the first moment Σ (z₀ + z₁)(y₀ z₁ − y₁ z₀) / 6). +fn sloped_basin_rim_chamfer_removed(margin: f64, d: f64) -> f64 { + let len = ((20.0 - margin).powi(2) + 400.0).sqrt(); + let (e, t) = ((margin, 30.0), (margin - d, 30.0)); + let w = (margin + d * (20.0 - margin) / len, 30.0 - d * 20.0 / len); + let poly = if t.0 >= 0.0 { + vec![e, t, w] + } else { + let s = -t.0 / (w.0 - t.0); + vec![e, (0.0, 30.0), (0.0, t.1 + s * (w.1 - t.1)), w] }; - for (margin, distance) in [(1.0, 2.0), (1.0, 3.0), (0.5, 4.0), (0.5, 0.5), (1.0, 1.0)] { - let b = basin(margin); - let before = measure(&b).unwrap().volume; - match chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], distance) { - Err(KernelError::TooLarge(_)) => {} - Err(e) => panic!("{margin}, {distance}: refused, but not as too large: {e}"), - Ok(_) => panic!("{margin}, {distance}: a chamfer whose leg runs off the rim was built"), - } - assert_eq!(measure(&b).unwrap().volume, before); + let (mut area, mut moment) = (0.0, 0.0); + for i in 0..poly.len() { + let ((y0, z0), (y1, z1)) = (poly[i], poly[(i + 1) % poly.len()]); + let c = y0 * z1 - y1 * z0; + area += c / 2.0; + moment += (z0 + z1) * c / 6.0; + } + area.abs() * 30.0 + moment.abs() +} + +/// A chamfer as wide as a basin's thin rim (`chamfer_sloped_basin_rim`'s basin with the rim +/// `margin` wide at the top) uses the rim's top up, its leg ending on the slab's front edge: +/// it builds (the owner's ruling of 2026-10-30, d7), taking the whole triangle +/// ([`sloped_basin_rim_chamfer_removed`]: unclipped, d · drop / 2 · (60 − drop / 3) with +/// drop = 20 d / √((20 − margin)² + 400)): 21.662379 at 1 on the 1 mm rim, 5.359321 at 0.5 on +/// the 0.5 mm one. +#[test] +fn chamfer_as_wide_as_sloped_basin_rim_builds() { + // The formula reads the fitting chamfer of `chamfer_sloped_basin_rim` as that test does. + let drop = 2.0 / (1.0 + 0.8f64.powi(2)).sqrt(); + assert!(rel(sloped_basin_rim_chamfer_removed(4.0, 2.0), drop * (60.0 - drop / 3.0)) < 1e-12); + for margin in [0.5, 1.0] { + let b = sloped_basin(margin); + let made = chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], margin).unwrap_or_else(|e| panic!("{margin}: {e}")); + assert!(made.validity().is_empty(), "{margin}: {:?}", made.validity()); + let want = measure(&b).unwrap().volume - sloped_basin_rim_chamfer_removed(margin, margin); + assert!(rel(measure(&made).unwrap().volume, want) < 1e-8, "{margin}: {} vs {want}", measure(&made).unwrap().volume); + } +} + +/// A chamfer wider than a basin's thin rim runs its leg off the rim's top, over the slab's front +/// edge (a cliff): it builds as if the top went on and is cut by the front face (the owner's +/// ruling of 2026-10-30, d7), lowering the front face where it crosses it +/// ([`sloped_basin_rim_chamfer_removed`], clipped to y >= 0): 73.450475 for 2 and 142.112912 for +/// 3 on the 1 mm rim, 184.526613 for 4 on the 0.5 mm one. +#[test] +#[ignore = "fails until SMLib builds the cliff overflow: CloseRemovalRegion refuses it (SM_FILERR_NO_ROOM, its fillet boundary along the side edge's line lies on the surfaces of two faces)"] +fn chamfer_wider_than_sloped_basin_rim_builds() { + for (margin, distance) in [(1.0, 2.0), (1.0, 3.0), (0.5, 4.0)] { + let b = sloped_basin(margin); + let made = chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], distance).unwrap_or_else(|e| panic!("{margin}, {distance}: {e}")); + assert!(made.validity().is_empty(), "{margin}, {distance}: {:?}", made.validity()); + let want = measure(&b).unwrap().volume - sloped_basin_rim_chamfer_removed(margin, distance); + assert!(rel(measure(&made).unwrap().volume, want) < 1e-8, "{margin}, {distance}: {} vs {want}", measure(&made).unwrap().volume); } } diff --git a/crates/kernel/src/validation.rs b/crates/kernel/src/validation.rs new file mode 100644 index 000000000..4ebfbf108 --- /dev/null +++ b/crates/kernel/src/validation.rs @@ -0,0 +1,261 @@ +//! How often SMLib's full check runs while a model is evaluated. Every sweep, boolean and blend +//! checks its result in SMLib before it is decoded ([`Validation::EachStep`]); an evaluation can +//! instead leave those checks to one check of the bodies each feature keeps +//! ([`Validation::EachFeature`]), or skip them ([`Validation::Off`]). A body kept straight from +//! a step is checked at the end as that step would have checked it, on the step's own result +//! (kept with the body until then): the record a result is decoded to can pass SMLib's check +//! where the result itself fails it (a surface of revolution's polar curve, rebuilt on import). +//! +//! The evaluation installs its mode around a feature with [`validating`], as [`crate::watch`] +//! installs a watch: the operations a feature runs are reached through hundreds of public kernel +//! functions, and the mode is the evaluation's, not each operation's. Outside [`validating`] +//! (the kernel called directly, a preview, a test) every step is checked, as it always was. The +//! worker threads the kernel starts for a step run under the same mode ([`crate::par`]). + +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde::{Deserialize, Serialize}; + +use crate::body::Body; +use crate::{KernelError, Result}; + +/// When SMLib's full check of a result runs during a model evaluation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Validation { + /// After every sweep, boolean and blend: a step whose result fails the check fails the + /// feature there (how every evaluation checked before the mode existed). + EachStep, + /// Once per feature: the steps inside a feature are not checked, and each body the feature + /// makes or changes is checked before it is kept, so a feature that makes a body the check + /// refuses still fails, with the check's reason. + #[default] + EachFeature, + /// Never (experimental): a body the check would refuse is kept. + Off, +} + +impl Validation { + pub const ALL: [Validation; 3] = [Validation::EachStep, Validation::EachFeature, Validation::Off]; + + /// The mode's name: `each_step`, `each_feature` or `off` (as it is saved and sent). + pub fn id(self) -> &'static str { + match self { + Validation::EachStep => "each_step", + Validation::EachFeature => "each_feature", + Validation::Off => "off", + } + } + + /// The mode named `id` ([`Validation::id`]), `None` for anything else. + pub fn parse(id: &str) -> Option { + Validation::ALL.into_iter().find(|v| v.id() == id) + } +} + +/// One feature's work under a mode, shared with the worker threads it starts. +#[derive(Debug)] +pub(crate) struct Scope { + mode: Validation, + /// A step's check was left for the end of the feature ([`Validation::EachFeature`]). + deferred: AtomicBool, +} + +thread_local! { + static CURRENT: RefCell>> = const { RefCell::new(None) }; +} + +/// Run `f` with `mode` deciding which checks the kernel work it does on this thread runs. Also +/// gives whether a step's check was left for later under [`Validation::EachFeature`]: the +/// caller then checks the bodies it keeps ([`check_kept`]). +pub fn validating(mode: Validation, f: impl FnOnce() -> R) -> (R, bool) { + let scope = Arc::new(Scope { mode, deferred: AtomicBool::new(false) }); + let r = within(Some(scope.clone()), f); + (r, scope.deferred.load(Ordering::Relaxed)) +} + +/// The scope this thread's work runs in, to hand to the worker threads it starts. +pub(crate) fn current() -> Option> { + CURRENT.with(|c| c.borrow().clone()) +} + +/// Run `f` in `scope` (one [`current`] gave on another thread), restoring this thread's own +/// afterwards, also when `f` panics. +pub(crate) fn within(scope: Option>, f: impl FnOnce() -> R) -> R { + struct Restore(Option>>); + impl Drop for Restore { + fn drop(&mut self) { + if let Some(previous) = self.0.take() { + CURRENT.with(|c| *c.borrow_mut() = previous); + } + } + } + let previous = CURRENT.with(|c| c.replace(scope)); + let _restore = Restore(Some(previous)); + f() +} + +/// What a step does with SMLib's check of its result ([`step`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Step { + /// Check it now (outside [`validating`], and under [`Validation::EachStep`]). + Check, + /// Leave it to the end of the feature (under [`Validation::EachFeature`]): the body decoded + /// from the result keeps it ([`Body::left_unchecked`]) for [`check_kept`]. + Defer, + /// Never check it (under [`Validation::Off`]). + Skip, +} + +/// What the step about to check its result does. [`Step::Defer`] also tells the feature a check +/// was left for its end. +pub(crate) fn step() -> Step { + CURRENT.with(|c| match c.borrow().as_deref() { + None | Some(Scope { mode: Validation::EachStep, .. }) => Step::Check, + Some(s @ Scope { mode: Validation::EachFeature, .. }) => { + s.deferred.store(true, Ordering::Relaxed); + Step::Defer + } + Some(Scope { mode: Validation::Off, .. }) => Step::Skip, + }) +} + +/// How a step's own check takes its result. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Checked { + /// As it is. + AsIs, + /// A boolean's: solids touching each other along an edge or at a vertex come back as one + /// non-manifold body, checked as the separate solids its export holds (the boolean's rule). + Combined, +} + +/// A step's SMLib result whose check was left to the end of its feature: kept with the body +/// decoded from it (and only for that body's record) until [`check_kept`] takes it, so the check +/// at the end is the step's own, of the result the step made. +#[derive(Debug)] +pub(crate) struct Unchecked { + record: std::sync::Weak, + /// The step, as its own refusal names it (`SMLib fillet`). + what: String, + how: Checked, + result: std::sync::Mutex>, +} + +impl Unchecked { + pub(crate) fn new(record: &Arc, what: &str, how: Checked, result: solidcraft_smlib::Brep) -> Unchecked { + Unchecked { record: Arc::downgrade(record), what: what.to_string(), how, result: std::sync::Mutex::new(Some(result)) } + } + + /// The step's result, taken (once), when this is `record`'s. + fn take(&self, record: &Arc) -> Option { + if !std::ptr::eq(self.record.as_ptr(), Arc::as_ptr(record)) { + return None; + } + self.result.lock().ok().and_then(|mut r| r.take()) + } +} + +/// SMLib's full check of `r` as a step takes it (`how`): the check's report. +pub(crate) fn check_result(r: &solidcraft_smlib::Brep, how: Checked) -> std::result::Result { + fn failed(what: &'static str) -> impl Fn(&dyn std::fmt::Display) -> String { + move |e| format!("{what}: {e}") + } + match how { + Checked::Combined if !r.is_manifold_solid().map_err(|e| failed("check")(&e))? => { + let record = r.to_native().map_err(|e| failed("export")(&e))?; + let split = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| failed("the separate solids")(&e))?; + split.check(solidcraft_smlib::CheckLevel::All).map_err(|e| failed("check")(&e)) + } + _ => r.check(solidcraft_smlib::CheckLevel::All).map_err(|e| failed("check")(&e)), + } +} + +/// SMLib's full check of a body a feature keeps, once a step of the feature left its check to +/// the end: an error with the check's reason unless it passes. A body decoded from a step's +/// result is checked as that step would have checked it, on its result; any other (a copy moved +/// into place, pieces joined without an operation) as SMLib takes it for the operations after it. +/// A mesh body has nothing to check. +pub fn check_kept(body: &Body) -> Result<()> { + if body.is_mesh() { + return Ok(()); + } + let step = body.unchecked.as_deref().and_then(|u| u.take(&body.record).map(|r| (u, r))); + let (what, check) = match &step { + Some((u, r)) => (u.what.as_str(), check_result(r, u.how)), + None => ("SMLib", body.smlib()?.check(solidcraft_smlib::CheckLevel::All).map_err(|e| format!("check: {e}"))), + }; + match check { + Ok(c) if c.is_valid() => Ok(()), + Ok(c) => Err(KernelError::Failed(format!("{what}: SMLib's check refuses the result: {c}"))), + Err(e) => Err(KernelError::Failed(format!("{what}: {e}"))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_step_is_checked_outside_an_evaluation_and_under_each_step() { + assert_eq!(step(), Step::Check); + assert_eq!(validating(Validation::EachStep, step), (Step::Check, false)); + assert_eq!(validating(Validation::EachFeature, step), (Step::Defer, true)); + assert_eq!(validating(Validation::Off, step), (Step::Skip, false)); + // The thread's own mode comes back, also after a nested scope. + let ((inner, outer), deferred) = validating(Validation::Off, || (validating(Validation::EachStep, step).0, step())); + assert!(inner == Step::Check && outer == Step::Skip && !deferred); + assert_eq!(step(), Step::Check); + } + + #[test] + fn the_mode_reaches_the_kernels_worker_threads() { + let items = [0, 1, 2, 3]; + let (checked, deferred) = validating(Validation::EachFeature, || { + crate::par::map("validation", &items, true, |_| Ok(step())).into_iter().collect::>>() + }); + assert_eq!(checked.ok(), Some(vec![Step::Defer; 4])); + assert!(deferred); + let (on_threads, deferred) = validating(Validation::EachFeature, || crate::par::map_on_threads(&items, 4, |_| step())); + assert_eq!(on_threads, vec![Some(Step::Defer); 4]); + assert!(deferred); + } + + /// A box with one corner moved off its three edges: SMLib's check refuses it. Under each_step + /// the boolean that takes it refuses its result there; under each_feature it is not checked, + /// says the check was left for later, and the check of the body kept refuses it. + #[cfg(feature = "smlib")] + #[test] + fn a_body_the_check_refuses_is_refused_at_the_step_or_at_the_end() { + use solidcraft_geom::Vec3; + let good = crate::box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 10.0)).unwrap(); + assert!(check_kept(&good).is_ok()); + let mut record = good.record().clone(); + record.vertices[0].point[2] += 0.5; + let bad = Body::from_record(record).unwrap(); + let e = check_kept(&bad).unwrap_err().to_string(); + assert!(e.contains("SMLib's check refuses the result"), "{e}"); + let tool = crate::box_solid(Vec3::new(5.0, 5.0, 5.0), Vec3::new(20.0, 20.0, 20.0)).unwrap(); + let (step, deferred) = validating(Validation::EachStep, || crate::boolean(&bad, &tool, crate::BoolOp::Union)); + let e = step.unwrap_err().to_string(); + assert!(e.contains("SMLib's check refuses the result (the first operand already fails it)") && !deferred, "{e}"); + let (joined, deferred) = validating(Validation::EachFeature, || crate::boolean(&bad, &tool, crate::BoolOp::Union)); + assert!(deferred); + let joined = joined.unwrap().unwrap(); + assert!(check_kept(&joined).unwrap_err().to_string().contains("SMLib's check refuses the result")); + let (off, deferred) = validating(Validation::Off, || crate::boolean(&bad, &tool, crate::BoolOp::Union)); + assert!(off.is_ok_and(|b| b.is_some()) && !deferred); + } + + #[test] + fn modes_are_named_as_they_are_saved() { + for v in Validation::ALL { + assert_eq!(Validation::parse(v.id()), Some(v)); + assert_eq!(serde_json::to_value(v).ok(), Some(serde_json::json!(v.id()))); + } + assert_eq!(Validation::parse("each step"), None); + assert_eq!(Validation::default(), Validation::EachFeature); + } +} diff --git a/crates/smlib/SMLIB_PREBUILT b/crates/smlib/SMLIB_PREBUILT index 8f2d58094..8949f9e14 100644 --- a/crates/smlib/SMLIB_PREBUILT +++ b/crates/smlib/SMLIB_PREBUILT @@ -1,10 +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 a0fe19504aee96d2e5de3ac9e4ef7215d649ebb420373a7cc93d62eca3761e2f -aarch64-pc-windows-msvc ad359c3996e4255086b193722a987286c1d094556eb053df80fd1538c5f9340d -aarch64-unknown-linux-gnu 4d0ac76e060de13a67ab60de6b207598bfc79d68b649875caaedbab4cac63d5a -i686-pc-windows-msvc 1218c4f9fa94f769fe8c45ee29d166d1aecd27cb57486de8883c7fba699f6812 -wasm32-unknown-unknown d61597525a3e1c6910890f9848cb85bb5934b2bcdfd8e6551246d90f8b5f94b8 -x86_64-apple-darwin 395f629a4e88132ae69874ff55898f493df75b4d8627a6a663f92ca6b633eb58 -x86_64-pc-windows-msvc 89876ff51ced8dd0513f3837ea1c12965ff957fec3d10051321da31014d24619 -x86_64-unknown-linux-gnu b4bd2990bd100f9a00a24b77f743208f4395adb8725924bcf939fd04a873ef10 +aarch64-apple-darwin 40e2e07835f7622f7b376e7586f2fd76406e6c8ae4d7d9db0047db9cba26a69d +aarch64-pc-windows-msvc dd406f2d33186b83f2e0134d1c71fb32e67c36a3dddbceb834161a9a2f5bdb17 +aarch64-unknown-linux-gnu ae66dca5c3687c298997299bbd54ce932ef6ea5223538a23f79784e625751a83 +i686-pc-windows-msvc a03b6d407a5ddc7ec07a94064fde8ae2962f3397da1b4ad2465cef4c8f2720ea +wasm32-unknown-unknown b62905369f173728f12f252a7d3bd49827e39e2d9bdedfcd54555359508acb5a +x86_64-apple-darwin 482da759ea62ffc0fbfaaa33eb90496852b5431bd06661465f3ebf2387ee23fa +x86_64-pc-windows-msvc 12c285085d7fceecd3dd18712ed4cabc717ea3b4db32712ece5958c9a40492ad +x86_64-unknown-linux-gnu 1ba8094a1a2632c1cc46064e68dfadada2f9ce1c988b80155950de901114b68f diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV index 504115e8a..24991edf9 100644 --- a/crates/smlib/SMLIB_REV +++ b/crates/smlib/SMLIB_REV @@ -1 +1 @@ -f8fd83e2fd5a70cf036fffbfaff0e7bc88e0563a +68fb91627edfea2c5d9251b949c6f2ef8eb23c56 diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 707723bde..533ae07b3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -5117,8 +5117,7 @@ fn named_refill(s: &Session, body: Option<&str>, name: &str, point: Vec3, edge: .filter_map(|b| naming::locate_edge(b, name, point).ok().map(|hit| (b, hit))) .min_by(|(_, a), (_, b)| a.point.dist(point).total_cmp(&b.point.dist(point)))?; (b, hit.edge, hit.point) - } else if let Some((b, (index, point, _))) = body.and_then(|n| st.body(n)).and_then(|b| naming::face_on_body(b, name, point).map(|hit| (b, hit))) - { + } else if let Some((b, (index, point))) = body.and_then(|n| st.body(n)).and_then(|b| naming::face_on_body(b, name, point).map(|hit| (b, hit))) { (b, index, point) } else { let hit = naming::locate_face(&st, name, point)?; diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index 107dd2c98..c9bcd090a 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -742,7 +742,7 @@ fn draft_uses_the_picked_solid_beside_a_hidden_overlapping_mesh() { let target = body.name.clone(); let point = Vec3::new(20.0, 10.0, 5.0); let name = naming::face_name_at_body(body, point).unwrap(); - let (index, _, _) = naming::face_on_body(body, &name, point).unwrap(); + let (index, _) = naming::face_on_body(body, &name, point).unwrap(); h.app.session.selection = vec![Sel::Face { body: target.clone(), index, point }]; let mut d = Dialog::for_command(&h.app, "solid.draft").unwrap(); d.inputs[1].items = vec![Sel::Plane { name: "XY".into() }]; diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 8e859fb55..8b9c351b5 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -160,6 +160,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { app.session.auto_project = out.session.auto_project; app.session.metric_tap_drill_major_less_pitch = out.session.metric_tap_drill_major_less_pitch; app.session.surface_extrude_symmetric_per_side = out.session.surface_extrude_symmetric_per_side; + app.session.set_validation(out.session.validation()); // So does the host's pre-command check: every tab is held to it. app.session.set_command_check(out.session.command_check()); // Views cache by revision: the incoming design must not look unchanged. diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 8bb48e18e..bcf5fa58f 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -408,8 +408,10 @@ fn start(app: &mut SolveApp) { let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() }; let update = request.kind == Kind::UpdateLinks; let mut scratch = if insert || update || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() }; - // A design opened or recovered here is run through the host's pre-command check too. + // A design opened or recovered here is run through the host's pre-command check too, and + // evaluated under the user's validation mode. scratch.set_command_check(app.session.command_check()); + scratch.set_validation(app.preferences.validation); if insert { scratch.selection = app.session.selection.clone(); } @@ -537,6 +539,7 @@ fn start_staged(app: &mut SolveApp) { let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() }; let mut session = if insert { app.session.scratch() } else { Session::default() }; session.set_command_check(app.session.command_check()); + session.set_validation(app.preferences.validation); if insert { session.selection = app.session.selection.clone(); } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 166c9ca62..a3ef0e637 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -202,8 +202,12 @@ impl Locale { } /// Evaluation errors stay English for scripts; the empty Cut/Intersect hint that names - /// another component is translated where it is shown. Other text is returned unchanged. + /// another component, and a feature's request to reselect a reference it lost, are translated + /// where they are shown. Other text is returned unchanged. pub fn diagnostic(self, text: &str) -> String { + if let Some((feature, reference)) = solidcraft_engine::doc::reselect_parts(text) { + return self.format("diagnostic.reselect_reference", &[("feature", &self.given_name(feature)), ("reference", reference)]); + } const PREFIX: &str = "there is no body to cut or intersect in component '"; if let Some((before, detail)) = text.split_once(PREFIX) && let Some((component, detail)) = detail.split_once("'; the tool may overlap '") @@ -379,6 +383,18 @@ mod tests { assert_eq!(Locale::for_language("ja").diagnostic(plain), plain); } + #[test] + fn reselect_reference_diagnostic_translates_with_the_feature_and_reference_as_given() { + let message = solidcraft_engine::doc::DocError::reselect("F4:side:c1#1|F4:top").in_feature("Fillet {2}").to_string(); + assert_eq!(Locale::for_language("en").diagnostic(&message), message); + for language in ["ar", "de", "he", "ja", "ko", "zh"] { + let translated = Locale::for_language(language).diagnostic(&message); + assert_ne!(translated, message, "{language}"); + // Right-to-left text comes back in display order, so only what it holds is checked. + assert!(translated.contains("Fillet {2}") && translated.contains("`F4:side:c1#1|F4:top`"), "{language}: {translated}"); + } + } + /// English first, then by id, so adding a locale edits only its own line. #[test] fn locales_are_listed_english_first_then_by_id() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8b0819186..e46720621 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -982,6 +982,7 @@ impl SolveApp { // next frame applies them. self.session.metric_tap_drill_major_less_pitch = self.preferences.metric_tap_drill_major_less_pitch; self.session.surface_extrude_symmetric_per_side = self.preferences.surface_extrude_symmetric_per_side; + self.session.set_validation(self.preferences.validation); let t0 = now_ms(); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS; @@ -1010,6 +1011,8 @@ impl SolveApp { self.ui.visual_style = index; } } + // The command and the preference are one setting. + "diagnostics.validation" => self.preferences.validation = self.session.validation(), "view.grid" => self.ui.show_grid = v.get("on").and_then(Value::as_bool).unwrap_or(!self.ui.show_grid), "view.ground_shadow" => self.ui.ground_shadow = v.get("on").and_then(Value::as_bool).unwrap_or(!self.ui.ground_shadow), "view.navigation_bar" => { diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index d817ec44a..39f9658ae 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -647,6 +647,10 @@ preference_settings! { /// extrudes; off by default: the distance is the total, split evenly around the start plane. /// Saved designs keep the reading they stored either way. surface_extrude_symmetric_per_side: bool = false, PAGE_DESIGN => check_id("prefs.surface_extrude_symmetric_per_side"); + /// When SMLib's full check runs while features are computed (`diagnostics.validation`): + /// `each_feature` (the default) checks the bodies each feature keeps once; `each_step`, as + /// before, checks after every sweep, boolean and blend; `off` (experimental) never does. + validation: solidcraft_engine::kernel::Validation = solidcraft_engine::kernel::Validation::EachFeature, PAGE_DESIGN; /// Reopen the saved designs that were open when the app was last closed (#5542). reopen_designs: bool = true, PAGE_GENERAL; /// Those designs' files, in tab order, as the last quit left them. @@ -1142,6 +1146,8 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) { // symmetric reading. app.session.metric_tap_drill_major_less_pitch = app.preferences.metric_tap_drill_major_less_pitch; app.session.surface_extrude_symmetric_per_side = app.preferences.surface_extrude_symmetric_per_side; + // The features computed from now on are checked as the preference says. + app.session.set_validation(app.preferences.validation); // The profiler records while the preference is on (switched when it changes; at start-up only // when on, so SOLIDCRAFT_PROFILE=1 is not undone by the default). let profile = app.preferences.profile_operations; @@ -2366,6 +2372,11 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result "prefs.validation.each_step", + Validation::EachFeature => "prefs.validation.each_feature", + Validation::Off => "prefs.validation.off", + }; + let labels: Vec = Validation::ALL.iter().map(|v| app.tr(label(v)).to_string()).collect(); + let options: Vec<&str> = labels.iter().map(String::as_str).collect(); + let mut selected = Validation::ALL.iter().position(|v| *v == app.preferences.validation).unwrap_or(1); + ui_kit::row(ui, app.tr("prefs.validation.label"), |ui| { + ui_kit::segmented(ui, &mut selected, &options, ui_kit::Segments { intrinsic: true, ..Default::default() }); + }); + if let Some(v) = Validation::ALL.get(selected) { + app.preferences.validation = *v; + } + ui_kit::text(ui, app.tr("prefs.validation_note"), ui_kit::Text::Hint("validation")); + }); ui_kit::settings_section(ui, "orientation", app.tr("prefs.orientation"), |ui| { ui.horizontal_wrapped(|ui| { for (id, label, y_up) in [("z", "Z up", false), ("y", "Y up", true)] { diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 88c957f02..6dd6bbf75 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -398,7 +398,7 @@ pub(crate) fn import_summary(report: &ImportReport) -> String { } let sentences = [ ("import_report.not_imported", parts_of(IssueKind::NotImported)), - ("import_report.mesh", parts_of(IssueKind::ShownAsMesh)), + ("import_report.refused", parts_of(IssueKind::Refused)), ("import_report.surfaces", parts_of(IssueKind::ImportedAsSurfaces)), ("import_report.left_out", faces_of(IssueKind::FaceLeftOut)), ("import_report.open", parts_of(IssueKind::OpenBody)), @@ -408,7 +408,7 @@ pub(crate) fn import_summary(report: &ImportReport) -> String { ("import_report.file", file), ]; out.extend(sentences.iter().filter(|(_, n)| *n > 0).map(|(key, n)| counted(key, *n))); - let lost = [IssueKind::NotImported, IssueKind::ShownAsMesh, IssueKind::ImportedAsSurfaces, IssueKind::FaceLeftOut, IssueKind::OpenBody]; + let lost = [IssueKind::NotImported, IssueKind::Refused, IssueKind::ImportedAsSurfaces, IssueKind::FaceLeftOut, IssueKind::OpenBody]; if lost.iter().any(|k| parts.contains_key(k)) { out.push(crate::i18n::tr("import_report.hint").to_string()); } @@ -853,10 +853,10 @@ mod tests { solids: 40, issues: vec![ issue( - IssueKind::ShownAsMesh, + IssueKind::Refused, Some(7), 0, - "solid #7: shown as a mesh: pcurves failed on 1 of 122 faces; first: face #9: SMLib pcurves: an edge lies 13.73370504071075 mm off the face's surface", + "solid #7: not imported: pcurves failed on 1 of 122 faces; first: face #9: SMLib pcurves: an edge lies 13.73370504071075 mm off the face's surface", ), issue( IssueKind::FaceLeftOut, @@ -876,7 +876,7 @@ mod tests { let summary = super::import_summary(&report); assert_eq!( summary, - "Imported 40 of 43 parts as solids. 1 part couldn't be imported. 1 part couldn't be made into a solid and is shown as a mesh. \ + "Imported 40 of 43 parts as solids. 1 part couldn't be imported. 1 part couldn't be made into a solid and was not imported. \ 1 part couldn't be made into a solid and came in as surfaces. 3 faces couldn't be repaired and are missing. \ Small flaws were repaired in 2 parts. There was 1 other problem with the file. \ Exporting these parts again from the program that made them may fix this. Copy Warning Message has the details." diff --git a/docs/design-container.md b/docs/design-container.md index 63571e13a..c3a2ff065 100644 --- a/docs/design-container.md +++ b/docs/design-container.md @@ -126,13 +126,15 @@ the final state fits. The model is the whole evaluation: every feature's result (warning, boolean diagnostics, whether it was skipped, its fingerprint) and the state after it (bodies, solved sketches, construction geometry, sheet metal bodies, threads and -the blend records later features read). States share what they share: a body that +the blend records later features read), and the body check mode it was evaluated +under (`each_step`, `each_feature` or `off`): a design opened under another mode is +evaluated again. States share what they share: a body that later features pass through unchanged, its face names and a solved sketch are each recorded once. Face names are kept as worked out (saving works out any not asked for yet), so a body taken from the file is named exactly as when it was saved. -A design whose stored names predate format 14 (marked `?`) finds them through -names worked out from geometry on demand, which the cache does not keep: it saves -without a model. +A design whose stored names predate format 14 (marked `?`) saves without a model: +those names find no face or edge, and the features holding them ask for their +references to be picked again. Both entries are Deflate-compressed (level one) under either compression policy: the encoded bodies shrink about fourfold (an imported assembly) to tenfold (modelled parts), @@ -147,7 +149,7 @@ SHA-256 of their encoding), and a placed copy of a repeated part (an instance fr a STEP assembly) records the part and its matrix, so it shows that part's display again instead of being meshed on its own. -`cache/model.json` records `solidcraft-model-cache/4`, the producer revision +`cache/model.json` records `solidcraft-model-cache/6`, the producer revision `solidcraft-truck-adapter/4`, the application version, the build (source commit, CPU architecture and OS), the SHA-256 of the exact `document.json` (whose blob references pin every STEP, mesh and image payload) and of `cache/bodies.bin`, the diff --git a/tests/action_matrix/baseline.json b/tests/action_matrix/baseline.json index 51d3af3c9..faa8f8df8 100644 --- a/tests/action_matrix/baseline.json +++ b/tests/action_matrix/baseline.json @@ -1177,7 +1177,7 @@ "design": "load" }, "corpus/naming-split-pieces": { - "Body1/F2:side:l1": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F2:side:l1": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:side:l1|F2:side:l2": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l1|F2:side:l4": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l1|F2:start": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", @@ -1186,13 +1186,11 @@ "Body1/F2:side:l1|F4:side:l2": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l1|F4:side:l4": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l1|F4:top": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l1|F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l1|F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l2": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F2:side:l2": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:side:l2|F2:side:l3": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l2|F2:start": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l2|F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]": "edge.axis edge.normal_plane edge.project", - "Body1/F2:side:l3": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", + "Body1/F2:side:l3": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:side:l3|F2:side:l4": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l3|F2:start": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l3|F2:top#[F2:side:l2,F4:side:l2]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", @@ -1200,116 +1198,94 @@ "Body1/F2:side:l3|F4:side:l2": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l3|F4:side:l4": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l3|F4:top": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l3|F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l3|F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l4": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F2:side:l4": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:side:l4|F2:start": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l4|F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:start": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", - "Body1/F2:top#[F2:side:l2,F4:side:l2]": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", + "Body1/F2:start": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F2:top#[F2:side:l2,F4:side:l2]": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:top#[F2:side:l2,F4:side:l2]|F4:side:l2": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:top#[F2:side:l2,F4:side:l2]|F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]": "edge.axis edge.normal_plane edge.project", - "Body1/F2:top#[F2:side:l4,F4:side:l4]": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F2:top#[F2:side:l4,F4:side:l4]": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:top#[F2:side:l4,F4:side:l4]|F4:side:l4": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:top#[F2:side:l4,F4:side:l4]|F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F4:side:l2": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F4:side:l2": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F4:side:l2|F4:top": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F4:side:l4": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F4:side:l4": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1/F4:side:l4|F4:top": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F4:top": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", - "Body1/F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]": "curved.axis curved.tangent_plane", - "Body1/F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", + "Body1/F4:top": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1/body": "body.copy body.mirror body.move body.pattern", "Body1/v[F2:side:l1 & F2:side:l2 & F2:start]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l1 & F2:side:l2 & F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]]": "vertex.plane_three_points vertex.point", + "Body1/v[F2:side:l1 & F2:side:l2 & F2:top#[F2:side:l2,F4:side:l2]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l1 & F2:side:l4 & F2:start]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l1 & F2:side:l4 & F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]]": "vertex.plane_three_points vertex.point", + "Body1/v[F2:side:l1 & F2:side:l4 & F2:top#[F2:side:l4,F4:side:l4]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l1 & F2:top#[F2:side:l2,F4:side:l2] & F4:side:l2]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l1 & F2:top#[F2:side:l2,F4:side:l2] & F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l1 & F2:top#[F2:side:l4,F4:side:l4] & F4:side:l4]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l1 & F2:top#[F2:side:l4,F4:side:l4] & F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l1 & F4:side:l2 & F4:top]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l1 & F4:side:l4 & F4:top]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l2 & F2:side:l3 & F2:start]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l2 & F2:side:l3 & F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]]": "vertex.plane_three_points vertex.point", + "Body1/v[F2:side:l2 & F2:side:l3 & F2:top#[F2:side:l2,F4:side:l2]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l3 & F2:side:l4 & F2:start]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l3 & F2:side:l4 & F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]]": "vertex.plane_three_points vertex.point", + "Body1/v[F2:side:l3 & F2:side:l4 & F2:top#[F2:side:l4,F4:side:l4]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l3 & F2:top#[F2:side:l2,F4:side:l2] & F4:side:l2]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l3 & F2:top#[F2:side:l2,F4:side:l2] & F5:blend:F2:side:l2|F2:top#[F2:side:l2,F4:side:l2]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l3 & F2:top#[F2:side:l4,F4:side:l4] & F4:side:l4]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l3 & F2:top#[F2:side:l4,F4:side:l4] & F6:blend:F2:side:l4|F2:top#[F2:side:l4,F4:side:l4]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l3 & F4:side:l2 & F4:top]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l3 & F4:side:l4 & F4:top]": "vertex.plane_three_points vertex.point", - "design": "load" + "design": "!load" }, "corpus/split-body-pieces": { - "Body1 (1)/F2:side:l1": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1 (1)/F2:side:l1": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1 (1)/F2:side:l1|F2:side:l2#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1 (1)/F2:side:l1|F2:side:l4#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1 (1)/F2:side:l1|F2:start#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1 (1)/F2:side:l1|F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]": "edge.axis edge.normal_plane edge.project", - "Body1 (1)/F2:side:l2#[F2:side:l1,F4:side:l1]": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1 (1)/F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", + "Body1 (1)/F2:side:l2#[F2:side:l1,F4:side:l1]": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1 (1)/F2:side:l2#[F2:side:l1,F4:side:l1]|F2:start#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1 (1)/F2:side:l2#[F2:side:l1,F4:side:l1]|F2:top#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1 (1)/F2:side:l2#[F2:side:l1,F4:side:l1]|F4:side:l1": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1 (1)/F2:side:l2#[F2:side:l1,F4:side:l1]|F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1 (1)/F2:side:l4#[F2:side:l1,F4:side:l1]": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", + "Body1 (1)/F2:side:l4#[F2:side:l1,F4:side:l1]": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1 (1)/F2:side:l4#[F2:side:l1,F4:side:l1]|F2:start#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1 (1)/F2:side:l4#[F2:side:l1,F4:side:l1]|F2:top#[F2:side:l1,F4:side:l1]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1 (1)/F2:side:l4#[F2:side:l1,F4:side:l1]|F4:side:l1": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1 (1)/F2:side:l4#[F2:side:l1,F4:side:l1]|F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1 (1)/F2:start#[F2:side:l1,F4:side:l1]": "face.angle_plane !face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", + "Body1 (1)/F2:start#[F2:side:l1,F4:side:l1]": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1 (1)/F2:start#[F2:side:l1,F4:side:l1]|F4:side:l1": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1 (1)/F2:top#[F2:side:l1,F4:side:l1]": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", + "Body1 (1)/F2:top#[F2:side:l1,F4:side:l1]": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1 (1)/F2:top#[F2:side:l1,F4:side:l1]|F4:side:l1": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1 (1)/F2:top#[F2:side:l1,F4:side:l1]|F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]": "edge.axis edge.normal_plane edge.project", - "Body1 (1)/F4:side:l1": "face.angle_plane !face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", - "Body1 (1)/F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]": "curved.axis curved.tangent_plane", + "Body1 (1)/F4:side:l1": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1 (1)/body": "body.copy body.mirror body.move body.pattern", "Body1 (1)/v[F2:side:l1 & F2:side:l2#[F2:side:l1,F4:side:l1] & F2:start#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", - "Body1 (1)/v[F2:side:l1 & F2:side:l2#[F2:side:l1,F4:side:l1] & F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", + "Body1 (1)/v[F2:side:l1 & F2:side:l2#[F2:side:l1,F4:side:l1] & F2:top#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", "Body1 (1)/v[F2:side:l1 & F2:side:l4#[F2:side:l1,F4:side:l1] & F2:start#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", - "Body1 (1)/v[F2:side:l1 & F2:side:l4#[F2:side:l1,F4:side:l1] & F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", + "Body1 (1)/v[F2:side:l1 & F2:side:l4#[F2:side:l1,F4:side:l1] & F2:top#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", "Body1 (1)/v[F2:side:l2#[F2:side:l1,F4:side:l1] & F2:start#[F2:side:l1,F4:side:l1] & F4:side:l1]": "vertex.plane_three_points vertex.point", "Body1 (1)/v[F2:side:l2#[F2:side:l1,F4:side:l1] & F2:top#[F2:side:l1,F4:side:l1] & F4:side:l1]": "vertex.plane_three_points vertex.point", - "Body1 (1)/v[F2:side:l2#[F2:side:l1,F4:side:l1] & F2:top#[F2:side:l1,F4:side:l1] & F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", "Body1 (1)/v[F2:side:l4#[F2:side:l1,F4:side:l1] & F2:start#[F2:side:l1,F4:side:l1] & F4:side:l1]": "vertex.plane_three_points vertex.point", "Body1 (1)/v[F2:side:l4#[F2:side:l1,F4:side:l1] & F2:top#[F2:side:l1,F4:side:l1] & F4:side:l1]": "vertex.plane_three_points vertex.point", - "Body1 (1)/v[F2:side:l4#[F2:side:l1,F4:side:l1] & F2:top#[F2:side:l1,F4:side:l1] & F5:blend:F2:side:l1|F2:top#[F2:side:l1,F4:side:l1]]": "vertex.plane_three_points vertex.point", "Body1/F2:side:l2#[F2:side:l3,F4:side:l3]": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:side:l2#[F2:side:l3,F4:side:l3]|F2:side:l3": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l2#[F2:side:l3,F4:side:l3]|F2:start#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l2#[F2:side:l3,F4:side:l3]|F2:top#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l2#[F2:side:l3,F4:side:l3]|F4:side:l3": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l2#[F2:side:l3,F4:side:l3]|F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l3": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:side:l3|F2:side:l4#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l3|F2:start#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l3|F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", + "Body1/F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l4#[F2:side:l3,F4:side:l3]": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:side:l4#[F2:side:l3,F4:side:l3]|F2:start#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l4#[F2:side:l3,F4:side:l3]|F2:top#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:side:l4#[F2:side:l3,F4:side:l3]|F4:side:l3": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:side:l4#[F2:side:l3,F4:side:l3]|F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:start#[F2:side:l3,F4:side:l3]": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:start#[F2:side:l3,F4:side:l3]|F4:side:l3": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F2:top#[F2:side:l3,F4:side:l3]": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1/F2:top#[F2:side:l3,F4:side:l3]|F4:side:l3": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", - "Body1/F2:top#[F2:side:l3,F4:side:l3]|F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]": "edge.axis edge.chamfer edge.fillet edge.normal_plane edge.project", "Body1/F4:side:l3": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", - "Body1/F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]": "face.angle_plane face.draft_neutral face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", "Body1/body": "body.copy body.mirror body.move body.pattern", "Body1/v[F2:side:l2#[F2:side:l3,F4:side:l3] & F2:side:l3 & F2:start#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l2#[F2:side:l3,F4:side:l3] & F2:side:l3 & F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", + "Body1/v[F2:side:l2#[F2:side:l3,F4:side:l3] & F2:side:l3 & F2:top#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l2#[F2:side:l3,F4:side:l3] & F2:start#[F2:side:l3,F4:side:l3] & F4:side:l3]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l2#[F2:side:l3,F4:side:l3] & F2:top#[F2:side:l3,F4:side:l3] & F4:side:l3]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l2#[F2:side:l3,F4:side:l3] & F2:top#[F2:side:l3,F4:side:l3] & F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l3 & F2:side:l4#[F2:side:l3,F4:side:l3] & F2:start#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l3 & F2:side:l4#[F2:side:l3,F4:side:l3] & F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", + "Body1/v[F2:side:l3 & F2:side:l4#[F2:side:l3,F4:side:l3] & F2:top#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l4#[F2:side:l3,F4:side:l3] & F2:start#[F2:side:l3,F4:side:l3] & F4:side:l3]": "vertex.plane_three_points vertex.point", "Body1/v[F2:side:l4#[F2:side:l3,F4:side:l3] & F2:top#[F2:side:l3,F4:side:l3] & F4:side:l3]": "vertex.plane_three_points vertex.point", - "Body1/v[F2:side:l4#[F2:side:l3,F4:side:l3] & F2:top#[F2:side:l3,F4:side:l3] & F6:blend:F2:side:l3|F2:top#[F2:side:l3,F4:side:l3]]": "vertex.plane_three_points vertex.point", - "design": "load" + "design": "!load" }, "demo/crazy-geom-cuts": { "Body1/F2:side:l1": "face.angle_plane face.draft_neutral face.extrude face.hole face.midplane face.offset_plane face.press_pull !face.shell face.sketch", diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index 9ad00ffe5..eade6e13b 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -44,6 +44,7 @@ diagnostics.crash_reports crash reports diagnostics.crash_reports.clear crash reports diagnostics.crash_test crash reports diagnostics.profile timing: where a command's time goes +diagnostics.validation a setting: when the body check runs doc.open opening and recovering documents doc.recover opening and recovering documents doc.recovery_discard opening and recovering documents diff --git a/tests/kernel-cases/README.md b/tests/kernel-cases/README.md index 1153aa0d0..2111e11a9 100644 --- a/tests/kernel-cases/README.md +++ b/tests/kernel-cases/README.md @@ -15,6 +15,10 @@ The CLI links SMLib by default (`scripts/fetch-smlib.sh` fetches the prebuilt li built with `--no-default-features`, every operation answers that SMLib is not built. The run's output folder (`--out`, default `target/kernel-cases`) gets `results.json`, every case's full result, and `dumps/-/`: the inputs of each SMLib call a case failed in, for replay (the CLI's `--dumps=DIR`, which the rig always passes). +`--validation MODE` runs the cases' features under that mode of SMLib's check +(`diagnostics.validation`): `each_feature` (the default: the bodies each feature keeps are checked +once), `each_step` (after every sweep, boolean and blend, as before) or `off`; the +`KNOWN_FAILING` lists are each_feature's. `--kernel smlib|solidcore|both` (default `smlib`) picks the backend each case's process runs on, through `SOLIDCRAFT_KERNEL`. A `solidcore` run keeps its `results.json`, `dumps/` and `report.md` diff --git a/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2-refused/expected.json deleted file mode 100644 index 8c2e70989..000000000 --- a/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#1080" - ], - "what": "all four top rim edges of a basin whose walls all slope 10 over 20, its front rim 1 mm wide, chamfered 2: the front chamfer's leg runs off the rim, so it is refused, naming the largest distance that fits", - "source": "analytic", - "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 11)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 140333.333333. The front chamfer's leg on the 1 mm rim would reach y = -1, over the slab's front face: refused (the owner's ruling of 2026-10-30).", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2/expected.json b/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2/expected.json new file mode 100644 index 000000000..7130c90bc --- /dev/null +++ b/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2/expected.json @@ -0,0 +1,25 @@ +{ + "sources": [ + "tangency-labs/solidcraft#1080" + ], + "what": "all four top rim edges of a basin whose walls all slope 10 over 20, its front rim 1 mm wide, chamfered 2: the front chamfer's leg runs off the rim over the slab's front face (a cliff), so the loop builds as if the top went on, mitred at the rim's corners, and is cut by the front face", + "source": "analytic", + "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 11)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 140333.333333. Sliced at depth t below the top, each picked edge's chamfer is a strip beside its wall w(t) = d (1 - t/delta) wide, delta = d / sqrt(1 + k^2), k the wall's run over its drop; picked neighbours meet in mitres (each runs on past the corner and the quadrant beyond both walls loses what both take) and an unpicked neighbour's wall, extended, ends it, so the section removed is the pocket's rectangle at t grown by w(t) on each picked side, clipped to the slab's front face y >= 0 (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds), less the pocket's rectangle. That area is quadratic in t between the breakpoints (each delta, and where the front strip's edge y0 + k t - w(t) crosses y = 0), so Simpson's rule on each piece is exact. Removed 375.673069. V = 139957.660264", + "body_count": 1, + "volume_mm3": 139957.66026433042, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 100, + 60, + 30 + ] + }, + "tolerance": { + "rel": 1e-06 + } +} diff --git a/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2-refused/recipe.json b/tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2-refused/recipe.json rename to tests/kernel-cases/fillets/1080-chamfer-equal-slope-basin-1-mm-rim-loop-2/recipe.json diff --git a/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-cut-by-them/expected.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/expected.json rename to tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-cut-by-them/expected.json diff --git a/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/recipe.json b/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-cut-by-them/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/recipe.json rename to tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-cut-by-them/recipe.json diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim-refused/expected.json deleted file mode 100644 index f8c0a8681..000000000 --- a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#1080" - ], - "what": "the 0.5 mm front rim of a sloped basin's top chamfered 4: its leg on the top runs off the rim over the slab's front face, so it is refused, naming the largest distance that fits", - "source": "analytic", - "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. The chamfer's leg on the rim's top (0.5 mm wide) would reach y = -3.5, off the rim and over the slab's front face y = 0, lowering that face: the owner's ruling of 2026-10-30 refuses a chamfer whose leg runs off the face beside its edge, naming the largest distance that fits.", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim/expected.json new file mode 100644 index 000000000..e8c618de6 --- /dev/null +++ b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim/expected.json @@ -0,0 +1,25 @@ +{ + "sources": [ + "tangency-labs/solidcraft#1080" + ], + "what": "the 0.5 mm front rim of a sloped basin's top chamfered 4: its leg on the top runs off the rim over the slab's front face (a cliff), so it builds as if the top went on and is cut by the front face, which it lowers to z = 28.524233 where it crosses it", + "source": "analytic", + "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. The chamfer's triangle in (y, z): the edge (0.5, 30), its leg on the top to (-3.5, 30), past the front face y = 0, and d down the wall to (0.5 + d (20-0.5)/L, 30 - 20 d/L), L = sqrt((20-0.5)^2 + 400), built as if the top went on and cut by the front face (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds): the triangle clipped to y >= 0, the quadrilateral (0.5, 30), (0, 30), (0, 28.524233), (3.292401, 27.135999). At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed (shoelace for the area and its first moment) 184.526613. V = 144082.140054", + "body_count": 1, + "volume_mm3": 144082.14005363008, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 100, + 60, + 30 + ] + }, + "tolerance": { + "rel": 1e-06 + } +} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim-refused/recipe.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim-refused/recipe.json rename to tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim/recipe.json diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim-refused/expected.json deleted file mode 100644 index c09bde3e1..000000000 --- a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#1080" - ], - "what": "the 0.5 mm front rim of a sloped basin's top chamfered 0.5: as wide as the rim, the chamfer would use the rim's top up: refused", - "source": "analytic", - "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. A chamfer as wide as the face beside its edge uses it up: full-width chamfers are refused (the owner's ruling of 2026-10-30).", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim/expected.json new file mode 100644 index 000000000..c2c4a4bba --- /dev/null +++ b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim/expected.json @@ -0,0 +1,25 @@ +{ + "sources": [ + "tangency-labs/solidcraft#1080" + ], + "what": "the 0.5 mm front rim of a sloped basin's top chamfered 0.5, as wide as the rim: its leg on the top ends on the slab's front edge, using the rim's top up, and it builds", + "source": "analytic", + "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. The chamfer's triangle in (y, z): the edge (0.5, 30), its leg on the top to (0, 30), the slab's front edge, and d down the wall to (0.5 + d (20-0.5)/L, 30 - 20 d/L), L = sqrt((20-0.5)^2 + 400) (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds). At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed (shoelace for the area and its first moment) 5.359321. V = 144261.307346", + "body_count": 1, + "volume_mm3": 144261.307345957, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 100, + 60, + 30 + ] + }, + "tolerance": { + "rel": 1e-06 + } +} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim-refused/recipe.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim-refused/recipe.json rename to tests/kernel-cases/fillets/1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim/recipe.json diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim-refused/expected.json deleted file mode 100644 index 7338a22c3..000000000 --- a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#1080" - ], - "what": "the 1 mm front rim of a sloped basin's top chamfered 2: its leg on the top runs off the rim over the slab's front face, so it is refused, naming the largest distance that fits", - "source": "analytic", - "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's leg on the rim's top (1 mm wide) would reach y = -1, off the rim and over the slab's front face y = 0, lowering that face: the owner's ruling of 2026-10-30 refuses a chamfer whose leg runs off the face beside its edge, naming the largest distance that fits.", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim/expected.json new file mode 100644 index 000000000..77ad7f676 --- /dev/null +++ b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim/expected.json @@ -0,0 +1,25 @@ +{ + "sources": [ + "tangency-labs/solidcraft#1080" + ], + "what": "the 1 mm front rim of a sloped basin's top chamfered 2: its leg on the top runs off the rim over the slab's front face (a cliff), so it builds as if the top went on and is cut by the front face, which it lowers to z = 29.570689 where it crosses it", + "source": "analytic", + "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's triangle in (y, z): the edge (1, 30), its leg on the top to (-1, 30), past the front face y = 0, and d down the wall to (1 + d (20-1)/L, 30 - 20 d/L), L = sqrt((20-1)^2 + 400), built as if the top went on and cut by the front face (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds): the triangle clipped to y >= 0, the quadrilateral (1, 30), (0, 30), (0, 29.570689), (2.377499, 28.550001). At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed (shoelace for the area and its first moment) 73.450475. V = 144459.882858", + "body_count": 1, + "volume_mm3": 144459.8828581631, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 100, + 60, + 30 + ] + }, + "tolerance": { + "rel": 1e-06 + } +} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim-refused/recipe.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim-refused/recipe.json rename to tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim/recipe.json diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim-refused/expected.json deleted file mode 100644 index 85d86b88e..000000000 --- a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#1080" - ], - "what": "the 1 mm front rim of a sloped basin's top chamfered 3: its leg on the top runs off the rim over the slab's front face, so it is refused, naming the largest distance that fits", - "source": "analytic", - "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's leg on the rim's top (1 mm wide) would reach y = -2, off the rim and over the slab's front face y = 0, lowering that face: the owner's ruling of 2026-10-30 refuses a chamfer whose leg runs off the face beside its edge, naming the largest distance that fits.", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim/expected.json new file mode 100644 index 000000000..91c72f822 --- /dev/null +++ b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim/expected.json @@ -0,0 +1,25 @@ +{ + "sources": [ + "tangency-labs/solidcraft#1080" + ], + "what": "the 1 mm front rim of a sloped basin's top chamfered 3: its leg on the top runs off the rim over the slab's front face (a cliff), so it builds as if the top went on and is cut by the front face, which it lowers to z = 29.141377 where it crosses it", + "source": "analytic", + "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's triangle in (y, z): the edge (1, 30), its leg on the top to (-2, 30), past the front face y = 0, and d down the wall to (1 + d (20-1)/L, 30 - 20 d/L), L = sqrt((20-1)^2 + 400), built as if the top went on and cut by the front face (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds): the triangle clipped to y >= 0, the quadrilateral (1, 30), (0, 30), (0, 29.141377), (3.066248, 27.825002). At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed (shoelace for the area and its first moment) 142.112912. V = 144391.220421", + "body_count": 1, + "volume_mm3": 144391.22042136008, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 100, + 60, + 30 + ] + }, + "tolerance": { + "rel": 1e-06 + } +} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim-refused/recipe.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim-refused/recipe.json rename to tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim/recipe.json diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim-refused/expected.json deleted file mode 100644 index 0a666d397..000000000 --- a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#1080" - ], - "what": "the 1 mm front rim of a sloped basin's top chamfered 1: as wide as the rim, the chamfer would use the rim's top up: refused", - "source": "analytic", - "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. A chamfer as wide as the face beside its edge uses it up: full-width chamfers are refused (the owner's ruling of 2026-10-30).", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim/expected.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim/expected.json new file mode 100644 index 000000000..4433f2f2f --- /dev/null +++ b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim/expected.json @@ -0,0 +1,25 @@ +{ + "sources": [ + "tangency-labs/solidcraft#1080" + ], + "what": "the 1 mm front rim of a sloped basin's top chamfered 1, as wide as the rim: its leg on the top ends on the slab's front edge, using the rim's top up, and it builds", + "source": "analytic", + "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's triangle in (y, z): the edge (1, 30), its leg on the top to (0, 30), the slab's front edge, and d down the wall to (1 + d (20-1)/L, 30 - 20 d/L), L = sqrt((20-1)^2 + 400) (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds). At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed (shoelace for the area and its first moment) 21.662379. V = 144511.670954", + "body_count": 1, + "volume_mm3": 144511.67095435527, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 100, + 60, + 30 + ] + }, + "tolerance": { + "rel": 1e-06 + } +} diff --git a/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim-refused/recipe.json b/tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim-refused/recipe.json rename to tests/kernel-cases/fillets/1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim/recipe.json diff --git a/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height-refused/expected.json b/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height-refused/expected.json deleted file mode 100644 index 22e9a7c0e..000000000 --- a/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height-refused/expected.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#1113", - "tangency-labs/solidcraft#851" - ], - "what": "the top edge of #851's concave R21 wall chamfered 10, the wall's full height: refused as too large", - "source": "analytic", - "method": "a chamfer as tall as the wall would leave the wall a face of no area (its two boundary arcs on one line): refused as too large (#1113), naming the largest distance that fits", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height/expected.json b/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height/expected.json new file mode 100644 index 000000000..ff9c5f72b --- /dev/null +++ b/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height/expected.json @@ -0,0 +1,15 @@ +{ + "sources": [ + "tangency-labs/solidcraft#1113", + "tangency-labs/solidcraft#851" + ], + "what": "the top edge of #851's concave R21 wall chamfered 10, the wall's full height: its leg down the wall ends on the wall's bottom edge, using the wall up, and it builds", + "source": "analytic", + "method": "plate x 0..41.1667, y -21..0 and the corner x 41.1667..62.1667 less the cylinder r 21 about (62.1667, -21), 10 high (tessellation/1263): V0 = 10 (62.1667 x 21 - pi 21^2/4) = 9591.394099. s = 10, the wall's full height (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds). The blend's section in (rho, z) about the wall's axis, the triangle (rho - 21) + (10 - z) <= s, is swept round it from the front face (square to the arc) to the back face y = 0, which the arc runs into tangent at the tip: at radius rho the part spans the angle asin(21/rho), so the blend takes Int_21^31 rho asin(21/rho) h(rho) drho with h(rho) = s - (rho - 21), integrated as Int u (21/sin u) h(21/sin u) 21 cos u / sin^2 u du over u = asin(21/rho) in [asin(21/31), pi/2] (smooth there), Gauss-Legendre 30 points on 64 pieces, converged to the last digit: 1303.400331. V = 8287.993768", + "body_count": 1, + "volume_mm3": 8287.993767991788, + "bbox": null, + "continuity": { + "order": "g0" + } +} diff --git a/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height-refused/recipe.json b/tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height-refused/recipe.json rename to tests/kernel-cases/fillets/1113-chamfer-arc-top-edge-full-wall-height/recipe.json diff --git a/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom-refused/expected.json b/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom-refused/expected.json deleted file mode 100644 index e7ef07957..000000000 --- a/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#2893" - ], - "what": "the top rim of a cylinder r10 x 20 chamfered 2 across the top and 25 down a 20 mm wall: refused", - "source": "analytic", - "method": "25 down the 20 mm wall runs past the bottom face: no chamfer of the rim between the top and the wall has those sizes, so the right answer is a refusal saying why", - "outcome": "refused", - "refusal": "larger than" -} diff --git a/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom/expected.json b/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom/expected.json new file mode 100644 index 000000000..7c1b20b66 --- /dev/null +++ b/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom/expected.json @@ -0,0 +1,23 @@ +{ + "sources": [ + "tangency-labs/solidcraft#2893" + ], + "what": "the top rim of a cylinder r10 x 20 chamfered 2 across the top and 25 down a 20 mm wall: the leg down the wall runs 5 past the bottom rim, so it builds as if the wall went on and is cut by the bottom face, a cone frustum", + "source": "analytic", + "method": "The chamfer's line in (rho, z) runs from (8, 20) on the top to (10, -5) on the wall continued past the bottom face z = 0 (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds): built as if the wall went on and cut by the bottom face, it takes the whole wall, leaving the frustum from r 8 at z = 20 to r 8 + 2 (20/25) = 9.6 at z = 0: pi h (R1^2 + R1 R2 + R2^2) / 3 = pi 20 (64 + 76.8 + 92.16) / 3 = 4879.102831. Faces: the top, the cone and the bottom: 3.", + "body_count": 1, + "volume_mm3": 4879.102830535188, + "faces": 3, + "bbox": { + "min": [ + -9.6, + -9.6, + 0 + ], + "max": [ + 9.6, + 9.6, + 20 + ] + } +} diff --git a/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom-refused/recipe.json b/tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom-refused/recipe.json rename to tests/kernel-cases/fillets/2893-chamfer-two-distances-past-the-bottom/recipe.json diff --git a/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges-refused/expected.json b/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges-refused/expected.json deleted file mode 100644 index b12749e53..000000000 --- a/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges-refused/expected.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "sources": [ - "tangency-labs/solidcraft#5835" - ], - "what": "the front and right top rim edges of a sloped basin with a 1 mm front rim chamfered 2: the front chamfer's leg runs off the rim, so it is refused, naming the largest distance that fits", - "source": "analytic", - "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The front chamfer's leg on the 1 mm rim would reach y = -1, over the slab's front face: refused (the owner's ruling of 2026-10-30).", - "outcome": "refused", - "refusal": "the largest distance that fits is" -} diff --git a/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges/expected.json b/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges/expected.json new file mode 100644 index 000000000..251d9f6e8 --- /dev/null +++ b/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges/expected.json @@ -0,0 +1,25 @@ +{ + "sources": [ + "tangency-labs/solidcraft#5835" + ], + "what": "the front and right top rim edges of a sloped basin with a 1 mm front rim chamfered 2: the front chamfer's leg runs off the rim over the slab's front face (a cliff), so they build as if the top went on, mitred at the rim's corner, and are cut by the front face", + "source": "analytic", + "method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. Sliced at depth t below the top, each picked edge's chamfer is a strip beside its wall w(t) = d (1 - t/delta) wide, delta = d / sqrt(1 + k^2), k the wall's run over its drop; picked neighbours meet in mitres (each runs on past the corner and the quadrant beyond both walls loses what both take) and an unpicked neighbour's wall, extended, ends it, so the section removed is the pocket's rectangle at t grown by w(t) on each picked side, clipped to the slab's front face y >= 0 (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds), less the pocket's rectangle. That area is quadratic in t between the breakpoints (each delta, and where the front strip's edge y0 + k t - w(t) crosses y = 0), so Simpson's rule on each piece is exact. Removed 161.279149. V = 144372.054184", + "body_count": 1, + "volume_mm3": 144372.05418423912, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 100, + 60, + 30 + ] + }, + "tolerance": { + "rel": 1e-06 + } +} diff --git a/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges-refused/recipe.json b/tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges-refused/recipe.json rename to tests/kernel-cases/fillets/5835-chamfer-sloped-basin-1-mm-rim-2-two-edges/recipe.json diff --git a/tests/kernel-cases/fillets/KNOWN_FAILING b/tests/kernel-cases/fillets/KNOWN_FAILING index f18c6d3f8..ed55721c4 100644 --- a/tests/kernel-cases/fillets/KNOWN_FAILING +++ b/tests/kernel-cases/fillets/KNOWN_FAILING @@ -2,8 +2,10 @@ # rig gate (.github/workflows/fillet-rig.yml) fails on a case that fails and is not listed here, # and on a listed case that passes: a fix removes its line in the same pull request. # Baseline: develop 242bbc89f with the SMLib fixes of 2026-10-29 (integration-overnight + b78bd4a), aarch64 Linux. -1080-chamfer-sloped-basin-0-5-mm-rim-as-wide-as-the-rim-refused builds the full-width chamfer where it should be refused, naming the largest that fits -1080-chamfer-sloped-basin-1-mm-rim-as-wide-as-the-rim-refused builds the full-width chamfer where it should be refused, naming the largest that fits +1080-chamfer-equal-slope-basin-1-mm-rim-loop-2 SMLib refuses the chamfers' cliff overflow as too large (SM_FILERR_NO_ROOM, CloseRemovalRegion): the blended loop's boundary closes on one face, where it should build cut by the front face +1080-chamfer-sloped-basin-0-5-mm-rim-4-past-the-rim SMLib refuses the chamfer past the rim as too large (SM_FILERR_NO_ROOM, CloseRemovalRegion): its sheet's boundary along the end wall's top edge line, past the rim, lies on the surfaces of two faces, where it should build cut by the front face +1080-chamfer-sloped-basin-1-mm-rim-2-past-the-rim SMLib refuses the chamfer past the rim as too large (SM_FILERR_NO_ROOM, CloseRemovalRegion): its sheet's boundary along the end wall's top edge line, past the rim, lies on the surfaces of two faces, where it should build cut by the front face +1080-chamfer-sloped-basin-1-mm-rim-3-past-the-rim SMLib refuses the chamfer past the rim as too large (SM_FILERR_NO_ROOM, CloseRemovalRegion): its sheet's boundary along the end wall's top edge line, past the rim, lies on the surfaces of two faces, where it should build cut by the front face 1080-fillet-equal-slope-basin-1-mm-rim-loop-0-5 SMLib's check refuses the round: SmSurfOfRevolution Test #7, polar curve intervals do not match the surface's domain 1080-fillet-equal-slope-basin-1-mm-rim-loop-4 not supported yet: a convex round past its face is not yet built by subtraction 1080-fillet-notched-block-top-outline-r8 not supported yet: a convex round past its face is not yet built by subtraction (largest that fits named 7 mm) @@ -13,18 +15,17 @@ 1080-fillet-sloped-basin-1-mm-rim-r4 not supported yet: a convex round past its face is not yet built by subtraction (largest that fits named 2.329 mm) 1080-fillet-sloped-basin-1-mm-rim-r4-2-edges not supported yet: a convex round past its face is not yet built by subtraction 1080-fillet-sloped-basin-1-mm-rim-r4-4-edges not supported yet: a convex round past its face is not yet built by subtraction -1113-chamfer-arc-top-edge-full-wall-height-refused builds the chamfer as tall as the wall where it should be refused as too large 1207-fillet-bar-top-edge-after-boss-arc-round-r0-5 SMLib's check refuses the round: internal coincident control points in a B-spline curve (an internal pole) 1668-fillet-outer-top-edge-of-thin-wall-r7-past-inside-corner a slit along the hollow, 0.507 mm^3 off: 38458.389 is V0 less the round's whole section along 104, so the section's part over the hollow (0.005068 mm^2 along 100), which is not material, is taken anyway 190-fillet-disc-rim-past-its-2mm-wall SMLib status 1001: a convex round past its face is not yet built by subtraction 2852-fillet-outer-round-r30-past-inner-round-refused refused for another reason: SMLib's result is not a closed solid, not too large naming 25.24 2893-chamfer-distance-and-angle-past-the-wall-refused refused for another reason: SMLib SM_ERR_INVALID_INPUT, not a check saying the angle runs past the wall 2893-chamfer-two-distances-elliptical-rim SMLib status 1001 on the elliptical rim's chamfer -2893-chamfer-two-distances-past-the-bottom-refused refused for another reason: SMLib status 1001, not too large +2893-chamfer-two-distances-past-the-bottom SMLib status 1001: SmFilletNx1ClosedCorner cannot compute the closed rim's corner geometry, where the chamfer past the bottom rim should build the frustum 4782-fillet-bar-edge-wider-than-both-faces SMLib status 1001: a convex round past both its faces is not yet built by subtraction 5158-fillet-round-just-past-a-10mm-face SMLib status 1001: a convex round 0.01 past its face is not yet built by subtraction (10.0001-10.04 open) 5835-chamfer-sloped-basin-1-mm-rim-0-5-4-edges SMLib status 1001 on the chamfers meeting at the rim's re-entrant corners -5835-chamfer-sloped-basin-1-mm-rim-2-two-edges-refused refused for another reason: SMLib status 1001, not too large naming the largest that fits +5835-chamfer-sloped-basin-1-mm-rim-2-two-edges SMLib status 1001: SmFilletNx2Corner, CalcFilletIntSideFace cannot intersect a chamfer with the side face at the rim's corner, where the front chamfer past the rim should build cut by the front face 5835-chamfer-sloped-basin-4-mm-rim-2-2-edges SMLib status 1001 on the chamfers meeting at the rim's re-entrant corner 5835-chamfer-sloped-basin-4-mm-rim-2-4-edges SMLib status 1001 on the chamfers meeting at the rim's re-entrant corners 851-chamfer-knife-edge-tip-0-5 SMLib SM_ERR_INVALID_INPUT on the knife edge (opposite normals on its two faces) @@ -39,12 +40,8 @@ cov-chamfer-concave-edge-through-up-down-joined-squares SMLib status 1001 on the cov-chamfer-outer-corner-edge-of-a-shelled-box-with-a-lip SMLib's chamfer result is not a closed solid where it ends on the lip cov-fillet-arc-edge-on-an-oblique-cut-of-a-bar SMLib's check refuses the round: internal coincident control points in a B-spline curve every-block-cylinder-crease-top-edge-after-arc-round-r1 the r1 round's contact seam with the block's side face reads 60 degrees (the cylinder wall's normal) at its end on the crease (8.660, 5, 15.284): G0 where the round is built tangent -every-chamfer-pocket-rim-5-5-refused refused naming 5 mm as the largest distance: the full-width chamfer (legs as deep as the 5 mm walls) builds instead of being refused -every-chamfer-pocket-rim-5-full-depth-refused the full-width chamfer (legs as deep as the 5 mm walls) builds instead of being refused -every-hole-top-rim-chamfer-10-full-depth-refused the full-width chamfer (leg as deep as the 10 mm plate) builds instead of being refused +every-chamfer-pocket-rim-5-5-past-the-floor SMLib refuses the chamfers' cliff overflow as too large (SM_FILERR_NO_ROOM, CloseRemovalRegion): the blended loop's boundary closes on one face, where it should build with a groove round the floor every-hole-top-rim-r12-past-plate-bottom SMLib status 1001: a convex round past its face on the tangent side is not yet built by subtraction every-pocket-floor-and-rim-edges-r2 a corner patch where two rim rounds meet at each concave pocket corner (23 faces, not 19) instead of the mitre the rounds make running into each other every-pocket-rim-edges-r2 a corner patch where two rim rounds meet at each concave pocket corner (19 faces, not 15) instead of the mitre the rounds make running into each other every-pocket-rim-edges-r5-as-deep-as-pocket a corner patch where two rim rounds meet at each concave pocket corner (15 faces, not 11) instead of the mitre the rounds make running into each other -report-fillet-curvature-three-edges-at-bar-corner SMLib's check refuses the open setback sheet of curvature rounds: a 2D B-spline curve cusp (SmBSplineCurve test 13) -report-fillet-edge-tangent-at-one-end-into-cylinder SMLib refuses the round as larger than the faces beside its edges allow (SMLIB_ERR_NO_ROOM): it fades to nothing at the edge's tangent end, on the wall SMLib now gets back as its cylinder diff --git a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-past-the-floor/expected.json b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-past-the-floor/expected.json new file mode 100644 index 000000000..269601e9d --- /dev/null +++ b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-past-the-floor/expected.json @@ -0,0 +1,24 @@ +{ + "sources": [], + "what": "a 5 mm deep pocket's rim edges chamfered 5.5: the legs run 0.5 past the walls' bottom, so it builds as if the walls went on below the floor, a groove 0.5 deep round the floor's edge", + "source": "analytic", + "method": "plate 60x40x10 with the pocket 30x20x5 (x 15..45, y 10..30, floor z = 5, sharp vertical corners): V0 = 24000 - 3000 = 21000. Each convex rim edge loses the triangle d^2/2 along its length (100 in all); at each pocket corner the two chamfers run on past it and meet in a mitre, the quadrant losing what both remove: points (s, t) past both walls with s + u < d and t + u < d (u the depth), int_0^d (d-u)^2 du = d^3/3: removed = 50 d^2 + (4/3) d^3. d = 5.5 runs 0.5 past the walls' bottom (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds): the chamfers are built as if the walls went on below the floor and what they take is cut from the plate; the formula holds as it is, its section at depth u in [5, 5.5] being the ring between the floor's rectangle and the rectangle grown by d - u, a groove round the floor's edge (the floor's own rectangle is not part of the blends). Faces: the plate's 6, the floor, the 4 chamfers and the groove's 4 walls (the walls' planes from z = 4.5 to 5): 15. Removed 1734.333333. V = 19265.666667.", + "body_count": 1, + "volume_mm3": 19265.666666666668, + "faces": 15, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 60, + 40, + 10 + ] + }, + "continuity": { + "order": "g0" + } +} diff --git a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-refused/recipe.json b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-past-the-floor/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-refused/recipe.json rename to tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-past-the-floor/recipe.json diff --git a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-refused/expected.json b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-refused/expected.json deleted file mode 100644 index 0b13ada99..000000000 --- a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-5-refused/expected.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "sources": [], - "what": "a 5 mm deep pocket's rim edges chamfered 5.5: the legs would run off the walls over the floor: refused, naming the largest distance that fits", - "source": "invariants", - "method": "owner rule: a chamfer whose leg runs off the face beside its edge over another face is refused, naming the largest size that fits, and a full-width chamfer stays refused. The walls are 5 deep, so every distance below 5 fits (every-chamfer-pocket-rim-4-9-fits) and 5 does not; the search names the largest at the request's three significant digits (step 0.001): 4.999.", - "outcome": "refused", - "refusal": "the largest distance that fits is 4.999 mm" -} \ No newline at end of file diff --git a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth-refused/expected.json b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth-refused/expected.json deleted file mode 100644 index 5e695113e..000000000 --- a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth-refused/expected.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "sources": [], - "what": "a 5 mm deep pocket's rim edges chamfered 5: the legs would use the whole walls: refused, naming the largest distance that fits", - "source": "invariants", - "method": "owner rule: a chamfer whose leg runs off the face beside its edge over another face is refused, naming the largest size that fits, and a full-width chamfer stays refused. The walls are 5 deep, so every distance below 5 fits (every-chamfer-pocket-rim-4-9-fits) and 5 does not; the search names the largest at the request's three significant digits (step 0.001): 4.999.", - "outcome": "refused", - "refusal": "the largest distance that fits is 4.999 mm" -} \ No newline at end of file diff --git a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth/expected.json b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth/expected.json new file mode 100644 index 000000000..a1a878392 --- /dev/null +++ b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth/expected.json @@ -0,0 +1,24 @@ +{ + "sources": [], + "what": "a 5 mm deep pocket's rim edges chamfered 5: the legs use the whole walls, ending on the floor's edges, and it builds", + "source": "analytic", + "method": "plate 60x40x10 with the pocket 30x20x5 (x 15..45, y 10..30, floor z = 5, sharp vertical corners): V0 = 24000 - 3000 = 21000. Each convex rim edge loses the triangle d^2/2 along its length (100 in all); at each pocket corner the two chamfers run on past it and meet in a mitre, the quadrant losing what both remove: points (s, t) past both walls with s + u < d and t + u < d (u the depth), int_0^d (d-u)^2 du = d^3/3: removed = 50 d^2 + (4/3) d^3. d = 5, the walls' full depth (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds): the walls are used up, the chamfers meeting the floor along its edges, so the faces are the plate's 6, the floor and the 4 chamfers: 11. Removed 1416.666667. V = 19583.333333.", + "body_count": 1, + "volume_mm3": 19583.333333333332, + "faces": 11, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 60, + 40, + 10 + ] + }, + "continuity": { + "order": "g0" + } +} diff --git a/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth-refused/recipe.json b/tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth-refused/recipe.json rename to tests/kernel-cases/fillets/every-chamfer-pocket-rim-5-full-depth/recipe.json diff --git a/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth-refused/expected.json b/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth-refused/expected.json deleted file mode 100644 index 3414706e7..000000000 --- a/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth-refused/expected.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "sources": [], - "what": "the top rim of a hole through a 10 mm plate chamfered 10: its leg would use the hole's whole wall: refused, naming the largest distance that fits", - "source": "invariants", - "method": "owner rule: a chamfer whose leg runs off the face beside its edge is refused, and a full-width chamfer stays refused (it would replace the wall and turn the bottom rim into the chamfer's edge, changing the user's geometry). The wall is 10 tall, so every distance below 10 fits; the search names the largest at the request's three significant digits (step 0.01): 9.99.", - "outcome": "refused", - "refusal": "the largest distance that fits is 9.99 mm" -} \ No newline at end of file diff --git a/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth/expected.json b/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth/expected.json new file mode 100644 index 000000000..9feffc90f --- /dev/null +++ b/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth/expected.json @@ -0,0 +1,24 @@ +{ + "sources": [], + "what": "the top rim of a hole through a 10 mm plate chamfered 10: its leg uses the hole's whole wall, ending on the bottom rim, and it builds (a cone from the top to the bottom rim)", + "source": "analytic", + "method": "plate 40x40x10 with a through hole R5 at (20, 20): V0 = 16000 - 250 pi = 15214.6018. The chamfer's legs are 10 along the top face (to rho = 15, inside the plate's 20 to its sides) and 10 down the wall, its whole height (the owner's ruling of 2026-10-30 (d7): a chamfer that reaches or runs past a rim builds): the triangle 10^2/2 at centroid rho = 5 + 10/3, revolved once (Pappus): 2500 pi / 3 = 2617.9939. V = 16000 - 3250 pi / 3 = 12596.6080. The wall is used up: the faces are the plate's 6 and the cone: 7.", + "body_count": 1, + "volume_mm3": 12596.607958611057, + "faces": 7, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 40, + 40, + 10 + ] + }, + "continuity": { + "order": "g0" + } +} diff --git a/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth-refused/recipe.json b/tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth/recipe.json similarity index 100% rename from tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth-refused/recipe.json rename to tests/kernel-cases/fillets/every-hole-top-rim-chamfer-10-full-depth/recipe.json diff --git a/tests/kernel-cases/ladder/golden.json b/tests/kernel-cases/ladder/golden.json index 55ccea7e7..b65a5eb63 100644 --- a/tests/kernel-cases/ladder/golden.json +++ b/tests/kernel-cases/ladder/golden.json @@ -1672,7 +1672,7 @@ "measured": { "area_mm2": 5332.688157880919, "body_count": 1, - "edges": 7, + "edges": 9, "faces": 6, "vertices": 7, "volume_mm3": 5540.61199574002 diff --git a/xtask/src/kernel_cases.rs b/xtask/src/kernel_cases.rs index ee64861dc..e2e80df82 100644 --- a/xtask/src/kernel_cases.rs +++ b/xtask/src/kernel_cases.rs @@ -50,6 +50,9 @@ pub(crate) struct Options { routes: Vec, /// `--known-failing FILE`: run as a regression gate against that baseline (see [`gate`]). known_failing: Option, + /// `--validation MODE`: when SMLib's full check runs on the cases' features (each_step, + /// each_feature, off; the CLI's default, each_feature, when not given). + validation: Option, } impl Options { @@ -131,7 +134,11 @@ pub(crate) fn options(rest: &[&str], out: &str) -> Result { if known_failing.is_some() && !kernels.contains(&BACKENDS[0]) { return Err("--known-failing: grades the SMLib results, so needs --kernel smlib or both".into()); } - Ok(Options { cli: arg("--cli"), area: arg("--area"), timeout: Duration::from_secs(secs), jobs, out, kernels, routes, known_failing }) + let validation = arg("--validation"); + if let Some(v) = validation.as_deref().filter(|v| !["each_step", "each_feature", "off"].contains(v)) { + return Err(format!("--validation must be each_step, each_feature or off, not `{v}`")); + } + Ok(Options { cli: arg("--cli"), area: arg("--area"), timeout: Duration::from_secs(secs), jobs, out, kernels, routes, known_failing, validation }) } /// Every case's full result as JSON, into the run's output folder. @@ -224,14 +231,11 @@ fn run_case(o: &Options, case: &Path, kernel: &str) -> Value { }; let mut dumps = std::ffi::OsString::from("--dumps="); dumps.push(o.out_of(kernel).join("dumps")); - cmd.env_remove("SOLIDCRAFT_KERNEL_ROUTES") - .envs(o.env(kernel)) - .current_dir(root()) - .args(["kernel-cases", "--json"]) - .arg(dumps) - .arg(&rel) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); + cmd.env_remove("SOLIDCRAFT_KERNEL_ROUTES").envs(o.env(kernel)).current_dir(root()).args(["kernel-cases", "--json"]).arg(dumps); + if let Some(v) = &o.validation { + cmd.arg(format!("--validation={v}")); + } + cmd.arg(&rel).stdout(Stdio::piped()).stderr(Stdio::piped()); let base = |status: &str, error: String| { let area = case.parent().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let id = case.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 9e46faa25..1b291e3b9 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -47,7 +47,7 @@ commands: replay the reference tests (tests/oracle/*/recipe.json), compare with each case's expected.json and write docs/oracle.md (--cli: a solidcraft-cli already built, instead of cargo run --release) - kernel-cases [--area AREA] [--cli BIN] [--timeout S] [--jobs N] [--out DIR] [--kernel K] [--route R] [--known-failing FILE] [--coverage] + kernel-cases [--area AREA] [--cli BIN] [--timeout S] [--jobs N] [--out DIR] [--kernel K] [--route R] [--known-failing FILE] [--validation MODE] [--coverage] the kernel regression rig: run every case in tests/kernel-cases/// on SMLib (one process each, killed after --timeout, default 180 s), grade it against the case's own answer and write docs/kernel-cases.md; DIR (default @@ -66,6 +66,9 @@ commands: (tests/kernel-cases//KNOWN_FAILING, CI's Kernel rig workflow); it grades the SMLib side, so it needs --kernel smlib or both (with both, every side's results.json is saved, and no report or side by side is written) + --validation MODE: when SMLib's full check runs on the cases' features: + each_step, each_feature (the default) or off (solidcraft-cli kernel-cases + --validation=MODE); with --ladder too --ladder [--record REASON | --gate]: the complexity ladder instead (tests/kernel-cases/ladder/ladder.json, tiers in order), graded and compared with its timing golden (one case at a time unless --jobs), into