From ff3000e10b5b5a8d99279ca4cb40951992bc517d Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Fri, 30 Oct 2026 08:06:05 -0400 Subject: [PATCH] Wave 437/509: Curvature comb: every comb shown at one scale, kept by the command (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 0b7468729 jyviko: Curvature comb: every comb shown at one scale, kept by the command - 6ab96c658 jyviko: View analyses: one toggle group, its state in the session - 9a45d4248 jyviko: Kernel rig: inspect.analysis is a display analysis switch, exempt like the others - 8d590c198 jyviko: Kernel tests: the long-setback G2 patch's reach past the box from its exact surface Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- .../locales/pending/view-analysis-group.json | 17 ++ crates/engine/src/cmd/sketch_inspect.rs | 157 ++++++++++++++---- crates/engine/src/cmd/surface_analysis.rs | 84 +++++++++- crates/engine/src/lib.rs | 34 ++++ crates/engine/src/schema/mod.rs | 1 + crates/engine/src/schema/surface_analysis.rs | 35 ++++ .../src/schema/surface_analysis_tests.rs | 45 +++++ crates/kernel/src/corner_g2_tests.rs | 143 +++++++++++++++- crates/ui-egui/src/sketch_tools.rs | 87 +++++----- crates/ui-egui/src/toolbar.rs | 29 ++-- crates/ui-egui/src/viewport_overlays_tests.rs | 87 +++++++++- tests/kernel-cases/EXEMPT | 1 + 12 files changed, 620 insertions(+), 100 deletions(-) create mode 100644 assets/locales/pending/view-analysis-group.json create mode 100644 crates/engine/src/schema/surface_analysis.rs create mode 100644 crates/engine/src/schema/surface_analysis_tests.rs diff --git a/assets/locales/pending/view-analysis-group.json b/assets/locales/pending/view-analysis-group.json new file mode 100644 index 000000000..dd5f938bc --- /dev/null +++ b/assets/locales/pending/view-analysis-group.json @@ -0,0 +1,17 @@ +{ + "en": { + "cmd.inspect_analysis": "View Analysis" + }, + "ar": { + "cmd.inspect_analysis": "تحليل العرض" + }, + "he": { + "cmd.inspect_analysis": "ניתוח תצוגה" + }, + "ja": { + "cmd.inspect_analysis": "表示解析" + }, + "zh": { + "cmd.inspect_analysis": "视图分析" + } +} diff --git a/crates/engine/src/cmd/sketch_inspect.rs b/crates/engine/src/cmd/sketch_inspect.rs index 88863e72b..a183f7079 100644 --- a/crates/engine/src/cmd/sketch_inspect.rs +++ b/crates/engine/src/cmd/sketch_inspect.rs @@ -6,7 +6,7 @@ use solidcraft_geom::{Aabb3, Seg2, Vec2, Vec3}; use super::CommandSpec; use crate::params::{bad, bool_, num, string_list, vec3}; -use crate::{EngineError, Result, Session}; +use crate::{CombPick, CombView, EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("inspect.curvature_comb", "Curvature Comb Analysis", curvature_comb) @@ -19,10 +19,13 @@ pub static COMMANDS: &[CommandSpec] = &[ combs along the face's iso grid); density?: teeth per curve, 2…2000 (default 40; on an edge or an iso curve exactly \ that many, evenly spaced along its parameter); scale?: comb length per unit curvature (default auto: the longest \ tooth a fifth of the combs' size); length?: a multiplier on the automatic scale, 0.01…100 (default 1; ignored with \ - `scale`). The curvature is exact: from each sketch curve, edge curve (line, circle, ellipse, B-spline, NURBS, \ + `scale`); add?: true keeps the combs shown and adds these, every comb again at one scale (with nothing picked it \ + draws those shown again with this call's options, or turns the analysis on with none); clear?: true turns the \ + analysis off. Every comb of a call shares one scale, so tooth lengths compare across curves; the viewport draws \ + them. The curvature is exact: from each sketch curve, edge curve (line, circle, ellipse, B-spline, NURBS, \ intersection curve) or face surface's own derivatives, never from the display mesh; a face's teeth are the \ surface's normal curvature along each iso curve, along the surface normal. → combs: [{curve, teeth: [[foot, tip]], \ - envelope: [tip], max_curvature, min_radius}], scale", + envelope: [tip], max_curvature, min_radius}] (those shown, with `add`), scale", ), CommandSpec::new("inspect.minimum_radius", "Minimum Radius Analysis", minimum_radius) .at("SKETCH", "INSPECT") @@ -100,18 +103,62 @@ fn edge_teeth(st: &solidcraft_doc::ModelState, at: Vec3, density: usize) -> Resu } } +/// Most curves Curvature Comb Analysis shows at once. +const MAX_COMB_PICKS: usize = 1000; + +/// The combs of one pick, each as (id, teeth (foot, curvature, unit normal)): one for a curve or +/// an edge, one per iso curve for a face. +fn pick_teeth(s: &Session, pick: &CombPick, density: usize) -> Result)>> { + let cmd = "inspect.curvature_comb"; + match pick { + CombPick::Curve { sketch, curve } => { + let st = s.model.state(); + let ss = st.sketch(*sketch).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; + let ci = ss.sketch.curve_index(curve).ok_or_else(|| bad(cmd, format!("unknown curve `{curve}`")))?; + let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)); + let teeth = teeth_2d(&segs, density).into_iter().map(|(q, k, n)| (ss.plane.to_world(q), k, ss.plane.dir_to_world(n))).collect(); + Ok(vec![(curve.clone(), teeth)]) + } + CombPick::Edge { at } => { + let teeth = edge_teeth(&s.model.state(), *at, density)?.ok_or_else(|| bad(cmd, "no edge there"))?; + Ok(vec![(format!("edge@{},{},{}", at.x, at.y, at.z), teeth)]) + } + CombPick::Face { at, count } => { + let world = s.world_state()?; + let (body, face) = iso_face_at(s, &world, *at).ok_or_else(|| bad(cmd, "no face there"))?; + let mut out = Vec::new(); + for (k, line) in body.iso_lines(face, *count)?.iter().enumerate() { + out.push((format!("face@{},{},{}#{k}", at.x, at.y, at.z), teeth_exact(&crate::kernel::iso_comb(&body.body, face, line, density)?))); + } + Ok(out) + } + } +} + +/// `inspect.curvature_comb`: the combs of the picked curves, edges and faces (with `add`, those +/// already shown too), all at one scale, kept so the viewport draws them. View state only. fn curvature_comb(s: &mut Session, p: &Value) -> Result { let cmd = "inspect.curvature_comb"; + if bool_(p, "clear").unwrap_or(false) { + s.comb = None; + s.revision += 1; + return Ok(json!({"analysis": "curvature_comb", "cleared": true})); + } + let add = bool_(p, "add").unwrap_or(false); + let shown = if add { s.comb.clone() } else { None }; let density = num(p, "density") .filter(|d| d.is_finite()) .map(|d| d.clamp(crate::kernel::MIN_COMB_TEETH as f64, crate::kernel::MAX_COMB_TEETH as f64) as usize) - .unwrap_or(40); + .unwrap_or(shown.as_ref().map_or(40, |v| v.density)); let length = match p.get("length") { - None | Some(Value::Null) => 1.0, + None | Some(Value::Null) => shown.as_ref().map_or(1.0, |v| v.length), Some(v) => v.as_f64().filter(|x| (0.01..=100.0).contains(x)).ok_or_else(|| bad(cmd, "`length` must be a multiplier 0.01…100"))?, }; - let st = s.model.state(); - let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new(); + let fixed_scale = match p.get("scale") { + None | Some(Value::Null) => shown.as_ref().and_then(|v| v.fixed_scale), + Some(_) => num(p, "scale").filter(|x| x.is_finite() && *x > 0.0), + }; + let mut picks: Vec = Vec::new(); let curves = string_list(p, "curves"); if !curves.is_empty() { let id = match p.get("sketch") { @@ -120,19 +167,11 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result { _ => s.active_sketch, } .ok_or_else(|| bad(cmd, "no such sketch (and none is active)"))?; - let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?; - for c in curves.iter().take(1000) { - let ci = ss.sketch.curve_index(c).ok_or_else(|| bad(cmd, format!("unknown curve `{c}`")))?; - let segs = ss.sketch.exact_segs(ci).unwrap_or_else(|| ss.sketch.segs(ci)); - let teeth = teeth_2d(&segs, density).into_iter().map(|(q, k, n)| (ss.plane.to_world(q), k, ss.plane.dir_to_world(n))).collect(); - combs.push((c.clone(), teeth)); - } + picks.extend(curves.iter().take(MAX_COMB_PICKS).map(|c| CombPick::Curve { sketch: id, curve: c.clone() })); } if let Some(edges) = p.get("edges").and_then(Value::as_array) { - for e in edges.iter().take(1000) { - let at = vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))?; - let teeth = edge_teeth(&st, at, density)?.ok_or_else(|| bad(cmd, "no edge there"))?; - combs.push((format!("edge@{},{},{}", at.x, at.y, at.z), teeth)); + for e in edges.iter().take(MAX_COMB_PICKS) { + picks.push(CombPick::Edge { at: vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))? }); } } if let Some(faces) = p.get("faces") { @@ -143,39 +182,57 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result { num(p, "count").filter(|c| c.is_finite()).map(|c| c.clamp(1.0, 50.0) as usize).ok_or_else(|| bad(cmd, "`count` must be a number"))? } }; - let world = s.world_state()?; for v in faces.iter().take(100) { - let at = vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?; - let (body, face) = iso_face_at(s, &world, at).ok_or_else(|| bad(cmd, "no face there"))?; - for (k, line) in body.iso_lines(face, count)?.iter().enumerate() { - let teeth = teeth_exact(&crate::kernel::iso_comb(&body.body, face, line, density)?); - combs.push((format!("face@{},{},{}#{k}", at.x, at.y, at.z), teeth)); - } + picks.push(CombPick::Face { at: vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?, count }); } } - if combs.is_empty() { + if picks.is_empty() && !add { return Err(bad(cmd, "give `curves`, `edges` or `faces`")); } + let shown_picks = shown.map(|v| v.picks).unwrap_or_default(); + if shown_picks.len() + picks.len() > MAX_COMB_PICKS { + return Err(bad(cmd, format!("at most {MAX_COMB_PICKS} curves can be combed at once"))); + } + // The curves shown are combed again with these options; one gone with a model change since + // (its sketch, edge or face no longer there) is dropped. A new pick must be there. + let mut kept: Vec = Vec::new(); + let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new(); + for pick in shown_picks { + if let Ok(teeth) = pick_teeth(s, &pick, density) { + combs.extend(teeth); + kept.push(pick); + } + } + for pick in picks { + combs.extend(pick_teeth(s, &pick, density)?); + kept.push(pick); + } // One scale for all combs: the longest tooth is a fifth of the largest curve's size. let kmax = combs.iter().flat_map(|c| c.1.iter().map(|t| t.1.abs())).fold(0.0_f64, f64::max); let bounds: Aabb3 = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).collect(); let diag = bounds.diagonal(); let auto = if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 }; - let scale = num(p, "scale").filter(|x| x.is_finite() && *x > 0.0).unwrap_or(auto * length); + let scale = fixed_scale.unwrap_or(auto * length); + let mut drawn = Vec::with_capacity(combs.len()); let out: Vec = combs .iter() .map(|(id, teeth)| { - let lines: Vec<[[f64; 3]; 2]> = teeth.iter().map(|(q, k, n)| [(*q).into(), (*q - *n * (k * scale)).into()]).collect(); + let lines: Vec<[Vec3; 2]> = teeth.iter().map(|(q, k, n)| [*q, *q - *n * (k * scale)]).collect(); let kmax_c = teeth.iter().map(|t| t.1.abs()).fold(0.0_f64, f64::max); - json!({ + let reply: Vec<[[f64; 3]; 2]> = lines.iter().map(|[a, b]| [(*a).into(), (*b).into()]).collect(); + let value = json!({ "curve": id, - "teeth": lines, - "envelope": lines.iter().map(|l| l[1]).collect::>(), + "envelope": reply.iter().map(|l| l[1]).collect::>(), + "teeth": reply, "max_curvature": kmax_c, "min_radius": if kmax_c > 1e-12 { Value::from(1.0 / kmax_c) } else { Value::Null }, - }) + }); + drawn.push(lines); + value }) .collect(); + s.analyses_off(Some("inspect.curvature_comb")); + s.comb = Some(CombView { picks: kept, density, length, fixed_scale, scale, teeth: drawn }); Ok(json!({"combs": out, "scale": scale})) } @@ -369,7 +426,7 @@ fn isocurves(s: &mut Session, p: &Value) -> Result { s.isocurves.clear(); } s.isocurves.extend(picks.into_iter().map(|(_, k)| k)); - s.revision += 1; + s.analyses_off(Some("inspect.isocurve")); Ok(json!({"curves": curves, "faces": shown})) } @@ -475,6 +532,40 @@ mod tests { assert!(s.execute("inspect.curvature_comb", &json!({"faces": [[58, 0, 5]], "count": "x"})).is_err()); } + /// The combs shown are kept in the session: `add` adds to them and draws them all again at + /// one scale (an R5 circle's teeth twice an R10 circle's), with nothing picked it takes new + /// options, a sketch curve keeps its own sketch, and `clear` turns the analysis off. + #[test] + fn added_combs_share_one_scale_and_clear_turns_them_off() { + use solidcraft_geom::Vec3; + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius": 5, "height": 10})).unwrap(); + s.execute("solid.cylinder", &json!({"base": [40, 0, 0], "radius": 10, "height": 10})).unwrap(); + let one = s.execute("inspect.curvature_comb", &json!({"edges": [[0, 5, 10]], "density": 8})).unwrap(); + let both = s.execute("inspect.curvature_comb", &json!({"edges": [[40, 10, 10]], "add": true})).unwrap(); + let shown = s.comb.as_ref().unwrap(); + assert_eq!((shown.picks.len(), shown.teeth.len(), shown.density), (2, 2, 8), "the first call's density is kept"); + assert_eq!(both["combs"].as_array().unwrap().len(), 2); + let tooth = |c: &[[Vec3; 2]]| c[0][0].dist(c[0][1]); + assert!((tooth(&shown.teeth[0]) / tooth(&shown.teeth[1]) - 2.0).abs() < 1e-9); + assert_ne!(one["scale"], both["scale"], "the scale is the pair's, not the first comb's"); + let longer = s.execute("inspect.curvature_comb", &json!({"add": true, "length": 2})).unwrap(); + assert!((longer["scale"].as_f64().unwrap() - 2.0 * both["scale"].as_f64().unwrap()).abs() < 1e-9); + assert_eq!(s.comb.as_ref().unwrap().picks.len(), 2); + // A sketch curve keeps its sketch after another becomes active. + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + let c = s.execute("sketch.circle.center", &json!({"center": [0, 30], "radius": 5})).unwrap()["curves"][0].clone(); + s.execute("inspect.curvature_comb", &json!({"curves": [c], "add": true})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("sketch.create", &json!({"plane": "XZ"})).unwrap(); + let r = s.execute("inspect.curvature_comb", &json!({"add": true})).unwrap(); + assert_eq!(r["combs"].as_array().unwrap().len(), 3, "{r}"); + s.execute("inspect.curvature_comb", &json!({"clear": true})).unwrap(); + assert!(s.comb.is_none()); + let on = s.execute("inspect.curvature_comb", &json!({"add": true})).unwrap(); + assert!(on["combs"].as_array().unwrap().is_empty() && s.comb.as_ref().is_some_and(|v| v.picks.is_empty())); + } + /// Each tooth of a comb reply as (foot, curvature): the tooth's length over the scale. fn tooth_curvatures(r: &Value, comb: usize) -> Vec<([f64; 3], f64)> { let scale = r["scale"].as_f64().unwrap(); diff --git a/crates/engine/src/cmd/surface_analysis.rs b/crates/engine/src/cmd/surface_analysis.rs index 8dbe452b9..ac0703a28 100644 --- a/crates/engine/src/cmd/surface_analysis.rs +++ b/crates/engine/src/cmd/surface_analysis.rs @@ -1,5 +1,7 @@ //! Surface analyses: zebra stripes, draft angle and curvature map shading of the model's faces. -//! View state only: no geometry changes and no undo step. +//! View state only: no geometry changes and no undo step. The view analyses (these shadings, +//! continuity seams, isocurves and curvature combs) are one group: one at a time is on, and +//! `inspect.analysis` says which or turns it off. use serde_json::{Value, json}; use solidcraft_geom::Vec3; @@ -38,6 +40,18 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("curvature_map") .noundo() .params("radius?: mm shown red (default: a tenth of the model's size); clear?: true turns the analysis off"), + CommandSpec::new("inspect.analysis", "View Analysis", crate::checked!("inspect.analysis", analysis)) + .icon("zebra") + .noundo() + .doc_only() + .contract(&ANALYSIS_CONTRACT) + .output(crate::schema::output_schema_for::) + .params( + "off?: true turns the view analysis on now off. → active: the command id of the view analysis on (inspect.zebra, \ + inspect.draft, inspect.curvature_map, inspect.environment_map, inspect.accessibility, inspect.continuity, \ + inspect.isocurve or inspect.curvature_comb), or null. One is on at a time: turning one on turns the one on before \ + off. Read-only without `off`", + ), CommandSpec::new("inspect.continuity", "Continuity Analysis", continuity).at("SURFACE", "INSPECT").icon("continuity").noundo().params( "body?: name (default: the visible bodies); edges?: [x,y,z] points or {\"index\": i} (default: every edge of the body; \ a pick must match one body); samples?: 3…257 stations along each edge, ends included (default 33); \ @@ -52,10 +66,75 @@ pub static COMMANDS: &[CommandSpec] = &[ ), ]; +const ANALYSIS_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +/// The view analyses, by the command that turns each on: the shadings, the continuity seams, the +/// isocurves and the curvature combs. One at a time is on. +impl Session { + /// The view analysis on now, by its command id, or `None`. + pub fn active_analysis(&self) -> Option<&'static str> { + if let Some(a) = self.analysis { + Some(a.command()) + } else if self.comb.is_some() { + Some("inspect.curvature_comb") + } else if !self.isocurves.is_empty() { + Some("inspect.isocurve") + } else if !self.continuity.is_empty() { + Some("inspect.continuity") + } else { + None + } + } + + /// Turn every view analysis off but the one command `keep` turns on (`None`: all of them). + pub fn analyses_off(&mut self, keep: Option<&str>) { + if self.analysis.is_some_and(|a| Some(a.command()) != keep) { + self.analysis = None; + } + if keep != Some("inspect.curvature_comb") { + self.comb = None; + } + if keep != Some("inspect.isocurve") { + self.isocurves.clear(); + } + if keep != Some("inspect.continuity") { + self.continuity.clear(); + } + self.revision += 1; + } +} + +impl SurfaceAnalysis { + /// The command that turns this analysis on. + pub fn command(self) -> &'static str { + match self { + SurfaceAnalysis::Zebra { .. } => "inspect.zebra", + SurfaceAnalysis::Draft { .. } => "inspect.draft", + SurfaceAnalysis::Curvature { .. } => "inspect.curvature_map", + SurfaceAnalysis::Environment => "inspect.environment_map", + SurfaceAnalysis::Access { .. } => "inspect.accessibility", + } + } +} + +/// `inspect.analysis`: which view analysis is on, and `off` turns it off. +fn analysis(s: &mut Session, p: &Value) -> Result { + let off = match p.get("off") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad("inspect.analysis", "`off` must be true or false")), + }; + if off { + s.analyses_off(None); + } + Ok(json!({"active": s.active_analysis()})) +} + fn set(s: &mut Session, p: &Value, a: SurfaceAnalysis) -> Result { if bool_(p, "clear").unwrap_or(false) { s.analysis = None; } else { + s.analyses_off(Some(a.command())); s.analysis = Some(a); } s.revision += 1; @@ -213,6 +292,9 @@ fn continuity(s: &mut Session, p: &Value) -> Result { } else { s.continuity = seams; } + if !s.continuity.is_empty() { + s.analyses_off(Some("inspect.continuity")); + } s.revision += 1; Ok(json!({ "analysis": "continuity", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1460203f6..4084cf4b4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -439,6 +439,9 @@ pub struct Session { /// The faces Isocurve Analysis shows the isoparametric curves of, for the viewport to draw /// ([`Session::isocurve_lines`]). View state: not part of the design and not an undo step. pub isocurves: Vec, + /// The curvature combs `inspect.curvature_comb` shows, for the viewport to draw; `None` when + /// the analysis is off. View state: not part of the design and not an undo step. + pub comb: Option, /// What is hidden or shown in the view (`browser.visibility`): saved with the design and an /// undo step of its own ([`Snapshot::visibility`]). A design brings its saved visibility when /// it opens (`Session::new`). @@ -538,6 +541,35 @@ pub struct IsoPick { pub count: usize, } +/// What Curvature Comb Analysis shows: the picks, the options every comb is drawn with, and +/// the teeth drawn, all at one scale so their lengths compare. View state only. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct CombView { + pub picks: Vec, + /// Teeth per curve. + pub density: usize, + /// The multiplier on the automatic scale. + pub length: f64, + /// A fixed comb length per unit curvature, in place of the automatic one. + pub fixed_scale: Option, + /// The comb length per unit curvature the teeth are drawn at, shared by every comb. + pub scale: f64, + /// Each comb's teeth as (foot, tip), in world coordinates. + pub teeth: Vec>, +} + +/// A curve Curvature Comb Analysis shows, as it was picked (found again whenever it is drawn). +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum CombPick { + /// A sketch curve. + Curve { sketch: u64, curve: String }, + /// The body edge whose exact curve passes nearest `at`. + Edge { at: Vec3 }, + /// The face at `at`, combed along `count` iso curves each way. + Face { at: Vec3, count: usize }, +} + impl SurfaceAnalysis { /// How a picture shades the faces for this analysis. pub fn mode(self) -> render::AnalysisMode { @@ -633,6 +665,7 @@ impl Session { analysis: None, continuity: Vec::new(), isocurves: Vec::new(), + comb: None, checkpoints: Vec::new(), next_checkpoint: 1, replacements: 0, @@ -1443,6 +1476,7 @@ impl Session { analysis: None, continuity: Vec::new(), isocurves: Vec::new(), + comb: None, checkpoints: Vec::new(), next_checkpoint: 1, replacements: 0, diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index db9bdbcc7..30677748e 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -58,6 +58,7 @@ pub mod browser; pub mod diagnostics; pub mod features; pub mod inspect; +pub mod surface_analysis; pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, output_schema_for, run_checked, run_checked_as}; pub use types::*; diff --git a/crates/engine/src/schema/surface_analysis.rs b/crates/engine/src/schema/surface_analysis.rs new file mode 100644 index 000000000..43336fb2f --- /dev/null +++ b/crates/engine/src/schema/surface_analysis.rs @@ -0,0 +1,35 @@ +//! Contracts and result types for the commands in `cmd/surface_analysis.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// `true`, `false` or null, with the handler's message for anything else. +fn flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(None), + Value::Bool(b) => Ok(Some(b)), + _ => Err(serde::de::Error::custom("must be true or false")), + } +} + +/// Say which view analysis is on (zebra, draft, curvature map, environment map, accessibility, +/// continuity, isocurves or curvature combs: one at a time), or turn it off. +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AnalysisParams { + /// Turn the view analysis on now off. + #[serde(default, deserialize_with = "flag")] + pub off: Option, +} + +/// What `inspect.analysis` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AnalysisState { + /// The command id of the view analysis on (after `off`), or null when none is. + pub active: Option, +} + +#[cfg(test)] +#[path = "surface_analysis_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/surface_analysis_tests.rs b/crates/engine/src/schema/surface_analysis_tests.rs new file mode 100644 index 000000000..e2955ab4a --- /dev/null +++ b/crates/engine/src/schema/surface_analysis_tests.rs @@ -0,0 +1,45 @@ +use serde_json::json; + +use super::AnalysisParams; +use crate::Session; +use crate::schema::input_schema_for; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["off"]); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[("inspect.analysis", json!({"off": "yes"})), ("inspect.analysis", json!({"off": 1}))]); +} + +/// The view analyses are one group: turning one on turns the one on before off, and +/// `inspect.analysis` names the one on and turns it off. +#[test] +fn one_view_analysis_is_on_at_a_time() { + let mut s = Session::default(); + s.execute("solid.cylinder", &json!({"radius": 5, "height": 10})).unwrap(); + let active = |s: &mut Session| s.execute("inspect.analysis", &json!({})).unwrap()["active"].clone(); + assert_eq!(active(&mut s), json!(null)); + s.execute("inspect.zebra", &json!({})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.zebra")); + s.execute("inspect.curvature_comb", &json!({"edges": [[0, 5, 10]]})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.curvature_comb")); + assert!(s.analysis.is_none(), "the zebra stripes went off"); + s.execute("inspect.isocurve", &json!({"faces": [[0, 5, 5]]})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.isocurve")); + assert!(s.comb.is_none(), "the combs went off"); + s.execute("inspect.continuity", &json!({})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.continuity")); + assert!(s.isocurves.is_empty(), "the isocurves went off"); + s.execute("inspect.draft", &json!({})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.draft")); + assert!(s.continuity.is_empty(), "the seams went off"); + // Turning on the comb with nothing picked yet. + s.execute("inspect.curvature_comb", &json!({"add": true})).unwrap(); + assert_eq!(active(&mut s), json!("inspect.curvature_comb")); + assert_eq!(s.execute("inspect.analysis", &json!({"off": true})).unwrap()["active"], json!(null)); + assert!(s.comb.is_none() && s.analysis.is_none()); +} diff --git a/crates/kernel/src/corner_g2_tests.rs b/crates/kernel/src/corner_g2_tests.rs index f80854e46..88125bc27 100644 --- a/crates/kernel/src/corner_g2_tests.rs +++ b/crates/kernel/src/corner_g2_tests.rs @@ -112,21 +112,152 @@ fn set_back_8_the_g2_corner_lies_between_the_hull_and_the_prisms() { assert!(clear <= CURVATURE_SHARE / 5.0, "{clear}"); } +/// How far past the box (60, 40, 20) face `face` of `rec` reaches within its trim: the highest +/// `max(x - 60, y - 40, z - 20)` on it, bracketed `(lo, hi)` from its exact surface alone, with no +/// mesh. The surface (a polynomial B-spline) is cut into its Bézier patches and those split in +/// four (de Casteljau, exact up to rounding) while they can still hold a higher point: a patch +/// lies in the hull of its control points, so its controls' highest value bounds it from above +/// (`hi`), and its corners are points of the surface (`lo`, where inside the trim). A patch +/// clear of the trim (the face's pcurves, sampled densely in its (u, v)) is dropped; one whose +/// hull cannot beat `lo` by 1e-12 is done; one split 18 times counts its hull in `hi`. Returns +/// the bracket and the (u, v) where `lo` is reached. +fn past_the_box(rec: &b::Brep, face: usize) -> (f64, f64, [f64; 2]) { + use solidcraft_geom::bspline::{HPoint, segment}; + let f = &rec.faces[face]; + let (b::Surface::Spline { u_knots, v_knots, points }, None) = (&f.surface, &f.nurbs) else { + panic!("face {face} is no polynomial B-spline: {:?}", std::mem::discriminant(&f.surface)); + }; + let excess = |p: Vec3| (p.x - 60.0).max(p.y - 40.0).max(p.z - 20.0); + // The trim: every loop's pcurves as one polygon set, inside by the even-odd rule. + let mut rings: Vec> = Vec::new(); + for l in &f.loops { + let b::Loop::Edges { edges } = l else { continue }; + let mut ring = Vec::new(); + for oe in edges { + let [t0, t1] = oe.pcurve.interval().unwrap(); + let mut seg: Vec<[f64; 2]> = (0..=400).map(|k| oe.pcurve.eval(t0 + (t1 - t0) * f64::from(k) / 400.0).unwrap()).collect(); + if !oe.forward { + seg.reverse(); + } + ring.extend(seg); + } + rings.push(ring); + } + let inside = |w: [f64; 2]| { + let mut odd = false; + for r in &rings { + for k in 0..r.len() { + let (p, q) = (r[k], r[(k + 1) % r.len()]); + if (p[1] > w[1]) != (q[1] > w[1]) && w[0] < p[0] + (w[1] - p[1]) * (q[0] - p[0]) / (q[1] - p[1]) { + odd = !odd; + } + } + } + odd + }; + let touches = |u: [f64; 2], v: [f64; 2]| { + rings.iter().flatten().any(|w| (u[0]..=u[1]).contains(&w[0]) && (v[0]..=v[1]).contains(&w[1])) + || [[u[0], v[0]], [u[1], v[0]], [u[0], v[1]], [u[1], v[1]]].into_iter().any(inside) + }; + // The Bézier patches: each knot span in u, then in v (control point [i][j], i along u). + let (nu, nv) = (points.len(), points[0].len()); + let (p, q) = (u_knots.len() - nu - 1, v_knots.len() - nv - 1); + let spans = |k: &[f64], n: usize, d: usize| { + let mut x: Vec = k[d..=n].to_vec(); + x.dedup(); + x.windows(2).map(|w| [w[0], w[1]]).collect::>() + }; + type Patch = (Vec>, [f64; 2], [f64; 2], u32); + let mut todo: Vec = Vec::new(); + for su in spans(u_knots, nu, p) { + // Each v column cut to the u span: (p + 1) x nv. + let cols: Vec> = (0..nv) + .map(|j| { + let c: Vec = (0..nu).map(|i| HPoint::weighted(Vec3::from(points[i][j]), 1.0)).collect(); + segment(p, u_knots, &c, su[0], su[1]).unwrap().1 + }) + .collect(); + for sv in spans(v_knots, nv, q) { + let net: Vec> = (0..=p) + .map(|i| { + segment(q, v_knots, &cols.iter().map(|c| c[i]).collect::>(), sv[0], sv[1]).unwrap().1.iter().map(|h| h.xyz()).collect() + }) + .collect(); + todo.push((net, su, sv, 0)); + } + } + let half = |c: &[Vec3]| { + let (mut l, mut r, mut pts) = (Vec::new(), Vec::new(), c.to_vec()); + while let (Some(&a), Some(&z)) = (pts.first(), pts.last()) { + l.push(a); + r.push(z); + pts = pts.windows(2).map(|w| w[0].lerp(w[1], 0.5)).collect(); + } + r.reverse(); + (l, r) + }; + let (mut lo, mut hi, mut at) = (f64::NEG_INFINITY, f64::NEG_INFINITY, [f64::NAN; 2]); + while let Some((net, u, v, depth)) = todo.pop() { + if !touches(u, v) { + continue; + } + for (i, j, uv) in [(0, 0, [u[0], v[0]]), (p, 0, [u[1], v[0]]), (0, q, [u[0], v[1]]), (p, q, [u[1], v[1]])] { + let e = excess(net[i][j]); + if e > lo && inside(uv) { + (lo, at) = (e, uv); + } + } + let hull = net.iter().flatten().map(|c| excess(*c)).fold(f64::NEG_INFINITY, f64::max); + if hull <= lo + 1e-12 { + continue; + } + if depth == 18 { + hi = hi.max(hull); + continue; + } + // Split in u (each column of the net is a v row: split the rows across i), then in v. + let (mut a, mut z) = (vec![Vec::new(); p + 1], vec![Vec::new(); p + 1]); + for j in 0..=q { + let (l, r) = half(&net.iter().map(|row| row[j]).collect::>()); + for i in 0..=p { + a[i].push(l[i]); + z[i].push(r[i]); + } + } + let (um, vm) = (0.5 * (u[0] + u[1]), 0.5 * (v[0] + v[1])); + for (n, uu) in [(a, [u[0], um]), (z, [um, u[1]])] { + let (l, r): (Vec<_>, Vec<_>) = n.iter().map(|row| half(row)).unzip(); + todo.push((l, uu, [v[0], vm], depth + 1)); + todo.push((r, uu, [vm, v[1]], depth + 1)); + } + } + (lo, hi.max(lo), at) +} + /// Long setbacks, where SMLib's own patch bulges past the faces (beyond about 2 r, by 0.25 at /// 3 r): the G2 patch is fitted to the faces' own planes along their curves and stays inside the -/// box but by under a thousandth (where it passes from a round's curvature to a plane's), G2 -/// clear of the hole's corners. +/// box, G2 clear of the hole's corners. The body is convex (a box with its edges and corner +/// rounded), and a convex face lies on the inner side of every tangent plane: the patch meets +/// each of the box's planes tangentially along its seam there, so it reaches past none of them, +/// up to rounding (1e-9 mm, the patch's seams lie on the planes to 1e-13). Measured on the +/// patch's exact surface within its trim ([`past_the_box`]), not on a mesh of it. #[test] fn a_long_setback_keeps_the_g2_patch_inside_the_box() { let (body, edges) = box_corner(); + let mut wrong = Vec::new(); for s in [11.0, 12.0, 13.0, 14.0, 15.0] { let g2 = fillet_g2_corners(&body, &edges, 5.0, &[(Vec3::new(60.0, 40.0, 20.0), s)]).unwrap(); - let m = g2.mesh(&MeshTolerance::chord(1e-3)).unwrap(); - let over = m.positions.iter().map(|p| (p.x - 60.0).max(p.y - 40.0).max(p.z - 20.0)).fold(f64::NEG_INFINITY, f64::max); + let rec = brep_record(&g2).unwrap(); + let patch: Vec = (0..rec.faces.len()).filter(|f| matches!(rec.faces[*f].surface, b::Surface::Spline { .. })).collect(); + assert_eq!(patch.len(), 1, "{s}: one patch"); + let (lo, hi, at) = past_the_box(&rec, patch[0]); let (_, clear, _) = corner_seams(&g2, 0.15); - eprintln!("set back {s}: past the box by {over:.2e}, curvature jump clear of the corners {clear:.3e}"); - assert!(over < 1e-3 && clear <= CURVATURE_SHARE / 5.0, "{s}: {over} {clear}"); + eprintln!("set back {s}: past the box by {lo:.4e} at (u, v) {at:?} (at most {hi:.4e}), curvature jump clear of the corners {clear:.3e}"); + if !(hi <= 1e-9 && clear <= CURVATURE_SHARE / 5.0) { + wrong.push(format!("set back {s}: past the box by {lo:.4e}..{hi:.4e} at (u, v) {at:?}, curvature jump {clear:.3e}")); + } } + assert!(wrong.is_empty(), "{wrong:#?}"); } /// Every edge of a box rounded: eight corners, each set back and filled, one closed solid. diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 30de5703d..2d8ea60cc 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -77,9 +77,6 @@ thread_local! { /// The inference the cursor snapped to last (label, sketch point), for the hint. static SNAP: RefCell> = const { RefCell::new(None) }; static PREV: Cell> = const { Cell::new(None) }; - /// The curvature combs shown while the comb tool is active: each pick (the command's - /// parameters for the curve or edge clicked) and its combs' teeth (foot, tip). - static COMBS: RefCell>)>> = const { RefCell::new(Vec::new()) }; /// The comb tool's options: comb length (a multiplier on the automatic length) and teeth. static COMB_OPTIONS: Cell = const { Cell::new(CombOptions::DEFAULT) }; /// The image file a Canvas or Decal tool places. @@ -328,6 +325,18 @@ pub fn start_hook(app: &mut SolveApp, id: &str) -> bool { app.set_status(format!("Continuity: {} (click the button again to turn it off)", counts.join(", ")), false); return true; } + if id == "inspect.curvature_comb" { + // With combs shown the button turns the analysis off; otherwise it turns it on (any other + // view analysis off) and the tool combs the curves clicked. + if app.session.comb.is_some() { + if app.run(id, json!({"clear": true})).is_ok() { + app.set_status("Analysis off", false); + } + return false; + } + comb(app, json!({})); + return app.session.comb.is_some(); + } if id == "inspect.isocurve" && !app.session.isocurves.is_empty() { // With curves shown, the button turns the analysis off; otherwise the tool picks faces. if app.run(id, json!({"clear": true})).is_ok() { @@ -388,37 +397,23 @@ pub(crate) fn comb_options() -> CombOptions { /// The combs shown, each as its teeth (foot, tip). #[cfg(test)] -pub(crate) fn shown_combs() -> Vec> { - COMBS.with(|c| c.borrow().iter().flat_map(|(_, combs)| combs.clone()).collect()) +pub(crate) fn shown_combs(app: &SolveApp) -> Vec> { + app.session.comb.as_ref().map(|v| v.teeth.clone()).unwrap_or_default() } -/// Run the comb command for `pick` with the tool's options: its combs' teeth (foot, tip), or -/// nothing when it fails (the status line says why). -fn comb_teeth(app: &mut SolveApp, pick: &Value) -> Option>> { +/// Comb `picks` (the comb command's parameters for curves or edges; none: draw those shown +/// again) beside the combs already shown, every comb at one scale with the tool's options. A +/// failure leaves those shown as they were (the status line says why). +fn comb(app: &mut SolveApp, picks: Value) { let options = comb_options(); - let mut params = pick.clone(); + let mut params = picks; + params["add"] = json!(true); params["density"] = json!(options.teeth); params["length"] = json!(options.length); - let v = app.run("inspect.curvature_comb", params).ok()?; - Some( - v["combs"] - .as_array() - .into_iter() - .flatten() - .map(|comb| comb["teeth"].as_array().into_iter().flatten().filter_map(|t| Some([v3(t.get(0)?)?, v3(t.get(1)?)?])).collect()) - .collect(), - ) + let _ = app.run("inspect.curvature_comb", params); } -/// Show the comb of `pick` (the comb command's parameters for a curve or an edge) beside those -/// already shown. -fn add_comb(app: &mut SolveApp, pick: Value) { - if let Some(teeth) = comb_teeth(app, &pick) { - COMBS.with(|c| c.borrow_mut().push((pick, teeth))); - } -} - -/// Change the comb tool's options and run the comb again on every curve already shown. +/// Change the comb tool's options and draw the combs shown again with them. pub(crate) fn set_comb_options(app: &mut SolveApp, options: CombOptions) { let options = CombOptions { length: options.length.clamp(*CombOptions::LENGTH.start(), *CombOptions::LENGTH.end()), @@ -427,9 +422,9 @@ pub(crate) fn set_comb_options(app: &mut SolveApp, options: CombOptions) { if COMB_OPTIONS.with(|o| o.replace(options)) == options { return; } - let picks: Vec = COMBS.with(|c| c.borrow().iter().map(|(pick, _)| pick.clone()).collect()); - let shown: Vec<(Value, Vec>)> = picks.into_iter().filter_map(|pick| comb_teeth(app, &pick).map(|teeth| (pick, teeth))).collect(); - COMBS.with(|c| *c.borrow_mut() = shown); + if app.session.comb.is_some() { + comb(app, json!({})); + } } /// The comb tool's options at the top left of the free viewport while it runs (the analysis and @@ -478,24 +473,19 @@ fn comb_options_card(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) { set_comb_options(app, options); } -/// Curvature combs: teeth and the envelope through their tips. +/// Curvature combs (`Session::comb`): teeth and the envelope through their tips. fn combs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { - if app.tool.as_ref().map(|t| t.cmd) != Some("inspect.curvature_comb") { - COMBS.with(|c| c.borrow_mut().clear()); - return; - } + let Some(shown) = &app.session.comb else { return }; let tk = crate::theme::Tokens::get(); - COMBS.with(|c| { - for comb in c.borrow().iter().flat_map(|(_, combs)| combs) { - let mut tips: Vec = Vec::new(); - for [a, b] in comb { - let (Some(p), Some(q)) = (proj.to_screen(*a), proj.to_screen(*b)) else { continue }; - painter.line_segment([p, q], Stroke::new(1.0, tk.comb_teeth)); - tips.push(q); - } - painter.add(egui::Shape::line(tips, Stroke::new(1.4, tk.comb_envelope))); + for comb in &shown.teeth { + let mut tips: Vec = Vec::new(); + for [a, b] in comb { + let (Some(p), Some(q)) = (proj.to_screen(*a), proj.to_screen(*b)) else { continue }; + painter.line_segment([p, q], Stroke::new(1.0, tk.comb_teeth)); + tips.push(q); } - }); + painter.add(egui::Shape::line(tips, Stroke::new(1.4, tk.comb_envelope))); + } } /// Snap a cursor point on the sketch plane to what is inferred while drawing: a crossing of @@ -952,7 +942,7 @@ pub fn on_click(app: &mut SolveApp, tool: &mut Tool, proj: &Proj, pos: Pos2) { _ => None, }); if let Some(p) = params { - add_comb(app, p); + comb(app, p); } } Mode::ModelRef if cmd == "inspect.isocurve" => { @@ -1225,6 +1215,11 @@ fn run_entities(app: &mut SolveApp, t: &Tool) { /// Right-click with an extra tool: finish a chain or move to the next stage. Returns false /// when the tool should be dropped. pub fn finish(app: &mut SolveApp, tool: &mut Tool) -> bool { + // Esc or a right click ends the comb tool and turns its analysis off. + if tool.cmd == "inspect.curvature_comb" { + let _ = app.run(tool.cmd, json!({"clear": true})); + return false; + } let Some(m) = mode(tool.cmd) else { return false }; match m { Mode::Points(0) if tool.pts.len() >= 2 => { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 26040dfe8..f6ca7ceac 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -208,6 +208,23 @@ fn help_x(report: Rect) -> f32 { report.left() - 18.0 } +/// The command whose tool or dialog is open right now, shown pressed in the toolbar. +fn running_command(app: &SolveApp) -> Option { + match (&app.tool, &app.dialog) { + (Some(tool), _) => Some(tool.cmd.to_string()), + // Create Sketch never lands in last_command (it is not repeatable). + (None, Some(d)) if matches!(d.kind, crate::dialogs::Kind::Sketch) => Some("sketch.create".to_string()), + (None, Some(_)) => app.last_command.as_ref().map(|(id, _)| id.clone()), + _ => None, + } +} + +/// Whether the toolbar shows command `id` pressed: its tool or dialog is open, or it turned on +/// the view analysis on now (one at a time, `Session::active_analysis`), its tool running or not. +pub(crate) fn shows_pressed(app: &SolveApp, id: &str) -> bool { + running_command(app).as_deref() == Some(id) || app.session.active_analysis() == Some(id) +} + /// The Report a bug button: labelled when the layout asks for it and there is room for its text /// (`label_width`, measured in the current language), otherwise just the icon. An icon-only /// layout gives it a square the size of Settings and Help. @@ -1245,14 +1262,6 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { ribbon_tabs(app, ui, Rect::from_min_max(pos2(ribbon_left, r.top()), pos2(r.right(), r.top() + TAB_ROW_HEIGHT))); // Panels. let tab = app.ui.tab.clone(); - // The command whose tool or dialog is open right now, shown pressed in the toolbar. - let running: Option = match (&app.tool, &app.dialog) { - (Some(tool), _) => Some(tool.cmd.to_string()), - // Create Sketch never lands in last_command (it is not repeatable). - (None, Some(d)) if matches!(d.kind, crate::dialogs::Kind::Sketch) => Some("sketch.create".to_string()), - (None, Some(_)) => app.last_command.as_ref().map(|(id, _)| id.clone()), - _ => None, - }; let mut px = ribbon_left; let top = r.top() + TAB_ROW_HEIGHT; let mut drop: Option<(&'static str, &'static str, Option<&'static str>)> = None; @@ -1432,7 +1441,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { } let accent = crate::theme::TabAccent::for_tab(&t, &tab); let family_open = family.is_some_and(|f| egui::Popup::is_id_open(ui.ctx(), ui.id().with(("family", f.label)).with("popup"))); - if !finish && (resp.is_pointer_button_down_on() || running.as_deref() == Some(selected.id) || family_open) { + if !finish && (resp.is_pointer_button_down_on() || shows_pressed(app, selected.id) || family_open) { painter.rect(whole, t.radius_sm, accent.soft, Stroke::new(1.0, accent.color), egui::StrokeKind::Inside); } else if resp.hovered() && info.enabled { painter.rect_filled(whole, t.radius_sm, t.hover); @@ -1499,7 +1508,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { ); let info = crate::render_workspace::interactive_command_info(app, c); let resp = ui.interact(cell, ui.id().with(("cmd", c.id)), Sense::click_and_drag()); - let active = running.as_deref() == Some(c.id); + let active = shows_pressed(app, c.id); let accent = crate::theme::TabAccent::for_tab(&t, &tab); painter.rect( cell, diff --git a/crates/ui-egui/src/viewport_overlays_tests.rs b/crates/ui-egui/src/viewport_overlays_tests.rs index 0590dcf17..8905aaa8e 100644 --- a/crates/ui-egui/src/viewport_overlays_tests.rs +++ b/crates/ui-egui/src/viewport_overlays_tests.rs @@ -623,7 +623,7 @@ fn comb_options_draw_the_combs_shown_again() { assert!(crate::scenario::rect_of("comb_options").is_some(), "the options card is drawn"); assert_eq!((comb_options().length, comb_options().teeth), (1.0, 40)); h.step(&json!({"click": {"world": [10, 0, 20]}})).unwrap(); - let combs = shown_combs(); + let combs = shown_combs(&h.app); assert_eq!(combs.len(), 1, "{:?}", h.app.status); assert_eq!(combs[0].len(), 40); let tooth = |c: &[[solidcraft_engine::geom::Vec3; 2]]| c[0][0].dist(c[0][1]); @@ -635,7 +635,7 @@ fn comb_options_draw_the_combs_shown_again() { h.step(&json!({"drag": [[track.center().x, track.center().y], [track.right() + 40.0, track.center().y]]})).unwrap(); h.frame(); assert_eq!(comb_options().length, 8.0); - let combs = shown_combs(); + let combs = shown_combs(&h.app); assert_eq!(combs.len(), 1, "the card's drag picked nothing"); assert!((tooth(&combs[0]) - 8.0 * auto).abs() < 1e-9 * auto, "{} vs 8 × {auto}", tooth(&combs[0])); // Teeth to its left end: 4. @@ -643,10 +643,89 @@ fn comb_options_draw_the_combs_shown_again() { h.step(&json!({"drag": [[track.center().x, track.center().y], [track.left() - 40.0, track.center().y]]})).unwrap(); h.frame(); assert_eq!(comb_options().teeth, 4); - let combs = shown_combs(); + let combs = shown_combs(&h.app); assert_eq!((combs.len(), combs[0].len()), (1, 4)); // The tool ends: the combs and the card go. h.step(&json!({"key": "Escape"})).unwrap(); h.frames(2); - assert!(shown_combs().is_empty() && crate::scenario::rect_of("comb_options").is_none()); + assert!(shown_combs(&h.app).is_empty() && crate::scenario::rect_of("comb_options").is_none()); + assert!(!crate::toolbar::shows_pressed(&h.app, "inspect.curvature_comb"), "Esc turned the analysis off"); +} + +/// Every comb shown shares one scale: the tool combs each new pick together with those already +/// shown, so tooth lengths compare across curves. An R5 edge's teeth are twice an R10 edge's, +/// after either pick and after the options change. +#[test] +fn combs_shown_together_share_one_scale() { + use crate::sketch_tools::{CombOptions, set_comb_options, shown_combs}; + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.cylinder", json!({"radius": 5, "height": 20})).unwrap(); + h.app.run("solid.cylinder", json!({"base": [30, 0, 0], "radius": 10, "height": 20})).unwrap(); + h.settle(); + h.step(&json!({"start": "inspect.curvature_comb"})).unwrap(); + h.frame(); + h.step(&json!({"click": {"world": [0, 5, 20]}})).unwrap(); + h.step(&json!({"click": {"world": [30, 10, 20]}})).unwrap(); + let ratio = |h: &Harness| { + let combs = shown_combs(&h.app); + assert_eq!(combs.len(), 2, "{:?}", h.app.status); + let tooth = |c: &[[solidcraft_engine::geom::Vec3; 2]]| c[0][0].dist(c[0][1]); + tooth(&combs[0]) / tooth(&combs[1]) + }; + assert!((ratio(&h) - 2.0).abs() < 1e-9, "{}", ratio(&h)); + set_comb_options(&mut h.app, CombOptions { length: 3.0, teeth: 12 }); + assert!((ratio(&h) - 2.0).abs() < 1e-9, "{}", ratio(&h)); + assert_eq!(shown_combs(&h.app)[1].len(), 12); +} + +/// The view analysis buttons are one toggle group, reflecting the session's one analysis on: +/// Curvature Comb on shows it pressed (through another dialog too); its button again turns it off +/// and clears the combs; Zebra on turns the comb off, and Zebra again leaves none on. +#[test] +fn view_analysis_buttons_are_one_toggle_group() { + use crate::sketch_tools::shown_combs; + use crate::toolbar::shows_pressed; + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.cylinder", json!({"radius": 10, "height": 20})).unwrap(); + h.settle(); + let (comb, zebra) = ("inspect.curvature_comb", "inspect.zebra"); + let active = |h: &mut Harness| h.app.run("inspect.analysis", json!({})).unwrap()["active"].clone(); + // Comb on, then off with its button again. + h.step(&json!({"start": comb})).unwrap(); + h.frame(); + assert!(shows_pressed(&h.app, comb) && !shows_pressed(&h.app, zebra)); + assert_eq!(active(&mut h), json!(comb)); + h.step(&json!({"click": {"world": [0, 10, 20]}})).unwrap(); + assert_eq!(shown_combs(&h.app).len(), 1, "{:?}", h.app.status); + h.step(&json!({"start": comb})).unwrap(); + h.frame(); + assert!(shown_combs(&h.app).is_empty() && h.app.tool.is_none() && !shows_pressed(&h.app, comb)); + assert_eq!(active(&mut h), json!(null)); + // Comb on again; it stays on, pressed, while another dialog is open. + h.step(&json!({"start": comb})).unwrap(); + h.step(&json!({"click": {"world": [0, 10, 20]}})).unwrap(); + h.step(&json!({"start": "solid.fillet"})).unwrap(); + h.frame(); + assert!(h.app.dialog.is_some() && h.app.tool.is_none()); + assert!(shows_pressed(&h.app, comb) && shown_combs(&h.app).len() == 1); + h.step(&json!({"key": "Escape"})).unwrap(); + h.frame(); + // Zebra on: the comb goes off and its combs go. + h.step(&json!({"start": zebra})).unwrap(); + h.frame(); + assert!(shows_pressed(&h.app, zebra) && !shows_pressed(&h.app, comb)); + assert!(shown_combs(&h.app).is_empty()); + assert_eq!(active(&mut h), json!(zebra)); + // Comb on: Zebra goes off. + h.step(&json!({"start": comb})).unwrap(); + h.frame(); + assert!(shows_pressed(&h.app, comb) && !shows_pressed(&h.app, zebra) && h.app.session.analysis.is_none()); + // Zebra on, then off: none is on. + h.step(&json!({"start": zebra})).unwrap(); + h.step(&json!({"start": zebra})).unwrap(); + h.frame(); + assert!(!shows_pressed(&h.app, zebra) && !shows_pressed(&h.app, comb)); + assert_eq!(active(&mut h), json!(null)); } diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index 8dcef8701..9ad00ffe5 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -70,6 +70,7 @@ file.slicers a listing of slicers frame.profile.list a listing of the profile library frame.profile.properties a profile's section properties from the library inspect.accessibility display analysis: shading +inspect.analysis display analysis: which one is on inspect.colored_components display: component colours inspect.curvature_map display analysis: shading inspect.environment_map display analysis: shading