From 88736dc9e416179f21a18dfd9c012e2731e6c2a2 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:21:58 -0400 Subject: [PATCH] Wave 259/509: thread: main's screw direction (#4414) out; the thread's hand is the one direction (and 2 more) 3 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - a57ce13e7 jyviko: thread: a shaft thicker than a modelled thread is refused, never turned down - 6b9f5e0e4 jyviko: thread: main's screw direction (#4414) out; the thread's hand is the one direction - 5fc160732 jyviko: Main's new callers of the placing calls that now return their error Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- assets/locales/en.json | 3 - assets/locales/it.json | 3 - assets/locales/ja.json | 3 - assets/locales/zh.json | 3 - crates/doc/src/document.rs | 20 -- crates/doc/src/eval.rs | 17 +- crates/doc/src/eval_surface.rs | 2 +- crates/doc/src/eval_thread.rs | 81 +------ crates/engine/src/cmd/clipboard.rs | 2 +- crates/engine/src/cmd/construct.rs | 2 +- crates/engine/src/cmd/features.rs | 18 +- crates/engine/src/cmd/features_more_tests.rs | 8 +- crates/engine/src/cmd/file_easyprint.rs | 2 +- crates/engine/src/cmd/model_axis_tests.rs | 8 +- crates/engine/src/cmd/occurrence_tests.rs | 6 +- .../engine/src/cmd/sketch_3d_frame_tests.rs | 6 +- crates/engine/src/computed_commands_tests.rs | 10 +- crates/engine/src/lib.rs | 12 +- crates/engine/src/tests.rs | 6 +- crates/engine/src/thread_tests.rs | 226 ++---------------- crates/gpu/tests/depth.rs | 6 +- crates/ui-egui/src/apply_off_thread_tests.rs | 8 +- crates/ui-egui/src/dialogs.rs | 25 +- crates/ui-egui/src/dialogs_all_tests.rs | 12 +- crates/ui-egui/src/dialogs_dense.rs | 1 - crates/ui-egui/src/dialogs_insert_drawing.rs | 2 +- crates/ui-egui/src/dialogs_move.rs | 7 +- crates/ui-egui/src/dialogs_sketch_tests.rs | 4 +- crates/ui-egui/src/dialogs_thread.rs | 12 +- .../ui-egui/src/dimension_create_ui_tests.rs | 6 +- crates/ui-egui/src/edit_clipboard_tests.rs | 2 +- crates/ui-egui/src/feature_edit.rs | 4 +- crates/ui-egui/src/hole_placement_ui_tests.rs | 14 +- crates/ui-egui/src/hole_presets.rs | 10 +- crates/ui-egui/src/pattern_arrow_tests.rs | 2 +- crates/ui-egui/src/prefs.rs | 4 +- crates/ui-egui/src/preselect_tests.rs | 66 +---- crates/ui-egui/src/round_pick_tests.rs | 2 +- crates/ui-egui/src/scale_tests.rs | 28 +-- crates/ui-egui/src/sketch3d_frame_ui_tests.rs | 4 +- .../src/sketch_centre_align_ui_tests.rs | 2 +- crates/ui-egui/src/sketch_dims_tests.rs | 2 +- crates/ui-egui/src/sketch_transform_ui.rs | 2 +- crates/ui-egui/src/tools.rs | 2 +- crates/ui-egui/src/viewport.rs | 6 +- .../ui-egui/src/viewport_appearance_tests.rs | 8 +- docs/book/src/guide/features.md | 10 +- 47 files changed, 145 insertions(+), 544 deletions(-) diff --git a/assets/locales/en.json b/assets/locales/en.json index 459e020ef..dd8bd964a 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -2254,10 +2254,7 @@ "the parts library is not available": "the parts library is not available", "thread.automatic_size": "Automatic size", "thread.designation": "Designation", - "thread.direction": "Thread direction", "thread.iso_metric": "ISO metric", - "thread.left_hand": "Left-hand", - "thread.right_hand": "Right-hand", "thread.select_size": "Select size", "timeline.delete_after_marker_one": "Delete 1 Feature After History Marker", "timeline.delete_after_marker_other": "Delete {count} Features After History Marker", diff --git a/assets/locales/it.json b/assets/locales/it.json index 0044f9e7f..d6756683a 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1153,10 +1153,7 @@ "the parts library is not available": "la libreria delle parti non è disponibile", "thread.automatic_size": "Dimensione automatica", "thread.designation": "Designazione", - "thread.direction": "Verso del filetto", "thread.iso_metric": "Metrica ISO", - "thread.left_hand": "Sinistro", - "thread.right_hand": "Destro", "thread.select_size": "Seleziona dimensione", "timeline.group": "Nuova cartella di lavorazioni", "timeline.move_many": "Sposta elementi della sequenza temporale", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 46536dacf..648f72599 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -2254,10 +2254,7 @@ "the parts library is not available": "パーツライブラリは利用できません", "thread.automatic_size": "サイズを自動選択", "thread.designation": "ねじの呼び", - "thread.direction": "ねじの方向", "thread.iso_metric": "ISOメートルねじ", - "thread.left_hand": "左ねじ", - "thread.right_hand": "右ねじ", "thread.select_size": "サイズを選択", "timeline.delete_after_marker_one": "履歴マーカー以降の 1 個のフィーチャーを削除", "timeline.delete_after_marker_other": "履歴マーカー以降の {count} 個のフィーチャーを削除", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 580364bb7..36de3c2f2 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -2254,10 +2254,7 @@ "the parts library is not available": "零件库不可用", "thread.automatic_size": "自动尺寸", "thread.designation": "螺纹标记", - "thread.direction": "螺纹方向", "thread.iso_metric": "ISO 公制", - "thread.left_hand": "左旋", - "thread.right_hand": "右旋", "thread.select_size": "选择尺寸", "timeline.delete_after_marker_one": "删除历史标记之后的 1 个特征", "timeline.delete_after_marker_other": "删除历史标记之后的 {count} 个特征", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f31400cc8..7da6bf3b8 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -15,21 +15,6 @@ pub const MAX_PARAMS: usize = 10_000; /// numbers, and far from overflowing the next id. pub const MAX_FEATURE_ID: u64 = 1 << 52; -/// Screw direction independent of the cylinder's placement and the picked end. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, solidcraft_derive::Walk)] -#[serde(rename_all = "lowercase")] -pub enum ThreadHandedness { - #[default] - Right, - Left, -} - -impl ThreadHandedness { - pub fn is_right(&self) -> bool { - *self == Self::Right - } -} - /// A named parameter. User parameters are created by the user; model parameters (`d1`, `d2`…) /// are created by dimensions and features. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -843,9 +828,6 @@ pub enum FeatureKind { #[serde(default, skip_serializing_if = "Option::is_none")] #[walk(length = "Thread depth")] thread_depth: Option, - /// Screw direction of the cosmetic thread; older holes are right-handed. - #[serde(default, skip_serializing_if = "ThreadHandedness::is_right")] - handedness: ThreadHandedness, /// To Object: drill down to the face (or point) here instead of `depth`. #[serde(default, skip_serializing_if = "Option::is_none")] to: Option, @@ -868,8 +850,6 @@ pub enum FeatureKind { length: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] modeled: bool, - #[serde(default, skip_serializing_if = "ThreadHandedness::is_right")] - handedness: ThreadHandedness, /// A point near the end of the face the thread starts at; `None`: the face's only free /// end (no material past it), or the end the pick at `face` lies near. #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 60a77fba9..b082bc724 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -3598,11 +3598,12 @@ pub(crate) fn revolve_axis( } /// The model a revolve axis is found in: what construction geometry of component `comp` is built -/// on when the axis is an edge or face of it (only then is it worth placing). -pub(super) fn axis_state<'a>(doc: &Document, st: &'a ModelState, comp: u64, axis: &AxisRef) -> std::borrow::Cow<'a, ModelState> { +/// on when the axis is an edge or face of it (only then is it worth placing); a model that cannot +/// be placed is the error. +pub(super) fn axis_state<'a>(doc: &Document, st: &'a ModelState, comp: u64, axis: &AxisRef) -> Result> { match axis { AxisRef::Model { .. } => construction_state(doc, st, comp), - _ => std::borrow::Cow::Borrowed(st), + _ => Ok(std::borrow::Cow::Borrowed(st)), } } @@ -4535,7 +4536,7 @@ fn feature_tools_with_constructor( )?; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); let (o, d) = - revolve_axis(&ss, axis, &axis_state(doc, st, f.component, axis), &|name| construction_axis_in(Some(doc), st, name, f.component))?; + revolve_axis(&ss, axis, &*axis_state(doc, st, f.component, axis)?, &|name| construction_axis_in(Some(doc), st, name, f.component))?; // To Object is in this feature's component frame: the model as seen from there. let tst = if to.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) }; let angles = if to.is_some() { @@ -5371,7 +5372,7 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_ref, axis_feature } => { // On an edge or round face: about it as it is now; on a construction axis: where it is. let (origin, axis) = match (axis_ref, axis_feature) { - (Some(g), _) => crate::construct::model_axis(&construction_state(doc, st, component), g)?, + (Some(g), _) => crate::construct::model_axis(&*construction_state(doc, st, component)?, g)?, (None, Some(name)) => construction_axis_in(Some(doc), st, name, component)?, (None, None) => (origin.0, axis.0), }; @@ -6283,7 +6284,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: let extra: Vec = if *operation == Operation::Join { to_body.into_iter().collect() } else { Vec::new() }; apply_traced_with(doc, st, f, tools, *operation, &crate::plain(targets), &extra) } - FeatureKind::Hole { thread, thread_depth, diameter, handedness, .. } => { + FeatureKind::Hole { thread, thread_depth, diameter, .. } => { let thread_depth = thread_depth.as_ref().map(|d| val(vals, d, Kind::Length)).transpose()?; if thread_depth.is_some() && thread.is_none() { return Err(DocError::Invalid("thread depth requires a tapped hole".into())); @@ -6310,9 +6311,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } else { parallel_tapped_wall(st, p, dir, r).unwrap_or(p + dir.any_perp() * r + dir * (r * 0.5)) }; - // A tapped hole's screw direction, as the thread's hand. - let hand = if handedness.is_right() { ThreadHand::Right } else { ThreadHand::Left }; - let ask = thread::ThreadAsk { designation: Some(d), tapped: true, hand, ..Default::default() }; + let ask = thread::ThreadAsk { designation: Some(d), tapped: true, ..Default::default() }; let mut t = thread_on(st, f.id, wall, &ask)?.info; if let Some(depth) = thread_depth { let available = t.end - t.start; diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index c403cfb93..d7065a1f0 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -304,7 +304,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; - let (o, d) = revolve_axis(&ss, axis, &super::axis_state(doc, st, f.component, axis), &|name| { + let (o, d) = revolve_axis(&ss, axis, &*super::axis_state(doc, st, f.component, axis)?, &|name| { construction_axis_in(Some(doc), st, name, f.component) })?; let a = val(vals, angle, Kind::Angle)?; diff --git a/crates/doc/src/eval_thread.rs b/crates/doc/src/eval_thread.rs index 1406464d9..be2ff80fa 100644 --- a/crates/doc/src/eval_thread.rs +++ b/crates/doc/src/eval_thread.rs @@ -206,8 +206,7 @@ pub(super) fn thread_on(st: &ModelState, feature: u64, p: Vec3, ask: &ThreadAsk) } else if cyl.internal { (minor - dia).abs() < 0.2 * major || (form.drill(major, pitch) - dia).abs() < 0.15 * major } else { - // A modelled thread also fits a shaft thicker than it, which it turns down first. - (major - dia).abs() < 0.15 * major || (ask.modeled && dia > major) + (major - dia).abs() < 0.15 * major }; if !fits { return Err(DocError::Invalid(format!("an {designation} thread does not fit a {dia:.2} mm {}", if cyl.internal { "hole" } else { "shaft" }))); @@ -493,73 +492,6 @@ fn thread_grooves(t: &ThreadInfo, radius: f64, face: (f64, f64), ends: [End; 2], /// Evaluate a thread feature: a cosmetic thread is listed in the model's threads, a modelled /// one cut into its body. -/// What a modelled external thread turns off a shaft thicker than its major diameter before it -/// cuts, as a lathe would: the ring between the major diameter and the shaft over the threaded -/// length, run on past an end of the face that nothing of the part (`mb`) lies beyond. `None` -/// for a shaft no thicker than the thread. Its inner wall is the turned face, named `turned`; -/// an end that stops inside the face leaves a shoulder, `shoulder:start` or `shoulder:end`. -fn thread_turn(t: &ThreadInfo, cyl: &kernel::CylinderFace, mb: &ModelBody) -> Result> { - let (p, r) = (t.pitch, t.major_diameter / 2.0); - if t.internal || !(cyl.radius > r * (1.0 + 1e-6)) { - return Ok(None); - } - let k = t.axis; - let u = k.cross(if k.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }); - let u = u.normalized().ok_or_else(|| DocError::Invalid("thread axis".into()))?; - let v = k.cross(u); - let mesh = mb.mesh(); - let solid_round = |s: f64, radius: f64| { - (0..12).any(|i| { - let a = std::f64::consts::TAU * f64::from(i) / 12.0; - mesh.contains(t.axis_point + *k * s + (u * a.cos() + v * a.sin()) * radius) - }) - }; - // The ring reaches a little past the shaft; the part must not go on there (a shaft standing - // in a corner, a rounded edge), or the turning would cut into it. - let out = cyl.radius + 0.1 * p; - if [0.25, 0.5, 0.75].iter().any(|f| solid_round(t.start + (t.end - t.start) * f, cyl.radius + 0.05 * p)) { - return Err(DocError::Invalid(format!( - "this {} mm shaft is too thick for a modelled {} thread, and the part around it keeps it from being turned down; make the shaft {} mm", - show_mm(2.0 * cyl.radius), - t.designation, - show_mm(t.major_diameter) - ))); - } - // Past a free end of the face out into the air; elsewhere square at the threaded length's end. - let tol = p * 1e-3; - let mid = (r + cyl.radius) / 2.0; - let free = |at: f64, s: f64, past: f64| (at - s).abs() < tol && !solid_round(s + past * 0.5 * p, mid); - let (open0, open1) = (free(cyl.start, t.start, -1.0), free(cyl.end, t.end, 1.0)); - let s0 = if open0 { t.start - p } else { t.start }; - let s1 = if open1 { t.end + p } else { t.end }; - let plane = Plane { origin: t.axis_point, x: u, y: *k }; - let ring = [Vec2::new(r, s0), Vec2::new(out, s0), Vec2::new(out, s1), Vec2::new(r, s1)]; - let region = Region2 { outer: solidcraft_geom::Loop2::polygon(&ring), holes: vec![] }; - let ring = kernel::revolve(&plane, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)? - .into_iter() - .next() - .ok_or_else(|| DocError::Invalid("thread: the shaft turned down to the thread".into()))?; - // The ring's sides by profile segment: its start end, outside, end end, inner wall. - let role = |segment: usize| -> Vec { - match segment { - 0 if !open0 => vec!["shoulder:start".into()], - 2 if !open1 => vec!["shoulder:end".into()], - 3 => vec!["turned".into()], - _ => Vec::new(), - } - }; - let roles = ring.history().filter(|h| h.operands == 0).map(|h| { - h.faces - .iter() - .map(|f| match f.origins.as_slice() { - [kernel::history::FaceOrigin::Profile { segment }] => role(*segment), - _ => Vec::new(), - }) - .collect() - }); - Ok(Some(Traced::made(ring, roles))) -} - pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState) -> Result<()> { let FeatureKind::Thread { face, @@ -624,16 +556,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, } let i = st.bodies.iter().position(|b| b.name == t.body).ok_or_else(|| DocError::Invalid("threaded body".into()))?; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) }; - // A shaft thicker than the thread is turned down to its major diameter first. - let input = mb.traced(); - let (input, radius) = match thread_turn(&t, &cyl, &mb)? { - Some(ring) => { - let turned = kernel::boolean(&input.body, &ring.body, BoolOp::Cut)? - .ok_or_else(|| DocError::Invalid("turning the shaft down removed everything".into()))?; - (Traced::step(turned, &[&input, &ring]), t.major_diameter / 2.0) - } - None => (input, cyl.radius), - }; + let (input, radius) = (mb.traced(), cyl.radius); // The exact grooves: SMLib's screw sweeps, cut by one B-rep boolean. let mut grooves = Vec::new(); for g in thread_grooves(&t, radius, (cyl.start, cyl.end), ends, steep, ease)? { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index b27e98f37..457dc6efe 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -263,7 +263,7 @@ mod tests { let r = run(&mut s, "timeline.paste", json!({"component": a, "component_path": [at]})); assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}"); assert_eq!(r["pasted"][0]["name"], "S (2)"); - let world = s.world_state(); + let world = s.world_state().unwrap(); let (original, copy) = (world.body("Block").unwrap().mesh().bounds(), world.body("Block (2)").unwrap().mesh().bounds()); assert!(copy.min.dist(original.min) < 1e-6 && copy.max.dist(original.max) < 1e-6, "{original:?} vs {copy:?}"); let state = s.model.state(); diff --git a/crates/engine/src/cmd/construct.rs b/crates/engine/src/cmd/construct.rs index b815b94aa..4c10b18a5 100644 --- a/crates/engine/src/cmd/construct.rs +++ b/crates/engine/src/cmd/construct.rs @@ -97,7 +97,7 @@ pub(super) fn model_axis_param(s: &Session, v: Option<&Value>, cmd: &str) -> Res let saved = |v: &Value| matches!(v.get("type").and_then(Value::as_str), Some("edge" | "face")); let Some(v) = v.filter(|v| v.get("edge").is_some() || v.get("face").is_some() || saved(v)) else { return Ok(None) }; let g = geo(s, Some(v), cmd, "axis")?; - let (o, d) = solidcraft_doc::construct::model_axis(&s.world_state(), &g).map_err(|e| bad(cmd, format!("`axis`: {e}")))?; + let (o, d) = solidcraft_doc::construct::model_axis(&*s.world_state()?, &g).map_err(|e| bad(cmd, format!("`axis`: {e}")))?; Ok(Some((g, o, d))) } diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index e286793f3..bc037b534 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -69,7 +69,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("hole") .key("H") - .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole: metric major minus pitch or tabulated UNC/UNF, G or Rp cut-tap drill) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" or \"1/4-20 UNC\" (cosmetic); handedness?: right|left (default right, needs thread for left); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"), + .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole: metric major minus pitch or tabulated UNC/UNF, G or Rp cut-tap drill) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" or \"1/4-20 UNC\" (cosmetic); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"), CommandSpec::new("solid.pipe", "Pipe", pipe) .at("SOLID", "CREATE") .icon("pipe") @@ -93,7 +93,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.thread", "Thread", thread) .at("SOLID", "CREATE") .icon("thread") - .params("face: [x,y,z] on a cylindrical face; form?: metric|trapezoidal|acme|buttress|buttress_asme (default: the one `designation` names, else metric; square is refused: no current standard defines it); designation?: the size, as its standard writes it: metric \"M8\", \"M8x1\", \"M16xPh3P1.5\" (ISO 68-1, ISO 261, ISO 965-1); trapezoidal \"Tr20x4\", \"Tr40x14(P7)\" (ISO 2904, ISO 2903); buttress \"S20x4\", \"S40x14(P7)\" (DIN 513, 3°/30°); acme \"1/2-10 ACME\" (ASME B1.5); buttress_asme \"2.5-8 BUTT\" (ASME B1.9, 7°/45°, basic profile; no size table) (default: the standard size that fits the face, a shaft its major diameter, a hole its drill); hand?: right|left|both (default right; both: a right- and a left-handed groove crossing); steep_flank?: start|end (buttress only, default end: the steep flank of the screw's teeth faces the thread's end, the way its axis points); starts?: 1..8 (lead = starts x pitch: that many grooves, each a turn's starts-th further round; a designation that gives the lead gives the starts); ease_in?, ease_out?: expr|standard|short (modelled threads: the groove fades out over this length, its section moving out of the material as it turns; standard 2.5 P, short 1.25 P per ISO 3508; ease_in at the end the thread starts from (`from`, or the start of its extent), ease_out at the other; it lies past the full-form length, up to a shoulder's clearance; at a free end, inside the face); tip?: none|chamfer (modelled external threads: each free end the thread reaches is chamfered after the groove is cut, ISO 4753's chamfered end, the last teeth tapering into the cone; chamfer_angle?: angle expr to the axis, default 45 deg; chamfer_depth?: expr, radial from the major diameter, default down to the external minor diameter, the largest ISO 4753 allows); extent?: full|length|up_to (default: length when `length` is given, up_to when `up_to` is, else full: the whole face); length?: expr (from the end the thread starts at); up_to?: [x,y,z] (a point, such as on a shoulder face: the thread runs to its place along the axis) | plane name or {origin, normal} (to where the plane crosses the axis); from?: [x,y,z] near the end of the face the thread starts at (default: the face's only free end, the one with no material past it; else the end the `face` point lies within a third of the face of; a pick in the middle of a face whose ends are alike is refused); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body: past a free end the groove runs out a pitch into the air (or through a chamfer); at a shoulder, a head or a blind hole's bottom it stops with its section clear of it, never cutting into it; a shaft thicker than the thread is first turned down to its major diameter over the threaded length"), + .params("face: [x,y,z] on a cylindrical face; form?: metric|trapezoidal|acme|buttress|buttress_asme (default: the one `designation` names, else metric; square is refused: no current standard defines it); designation?: the size, as its standard writes it: metric \"M8\", \"M8x1\", \"M16xPh3P1.5\" (ISO 68-1, ISO 261, ISO 965-1); trapezoidal \"Tr20x4\", \"Tr40x14(P7)\" (ISO 2904, ISO 2903); buttress \"S20x4\", \"S40x14(P7)\" (DIN 513, 3°/30°); acme \"1/2-10 ACME\" (ASME B1.5); buttress_asme \"2.5-8 BUTT\" (ASME B1.9, 7°/45°, basic profile; no size table) (default: the standard size that fits the face, a shaft its major diameter, a hole its drill); hand?: right|left|both (default right; both: a right- and a left-handed groove crossing); steep_flank?: start|end (buttress only, default end: the steep flank of the screw's teeth faces the thread's end, the way its axis points); starts?: 1..8 (lead = starts x pitch: that many grooves, each a turn's starts-th further round; a designation that gives the lead gives the starts); ease_in?, ease_out?: expr|standard|short (modelled threads: the groove fades out over this length, its section moving out of the material as it turns; standard 2.5 P, short 1.25 P per ISO 3508; ease_in at the end the thread starts from (`from`, or the start of its extent), ease_out at the other; it lies past the full-form length, up to a shoulder's clearance; at a free end, inside the face); tip?: none|chamfer (modelled external threads: each free end the thread reaches is chamfered after the groove is cut, ISO 4753's chamfered end, the last teeth tapering into the cone; chamfer_angle?: angle expr to the axis, default 45 deg; chamfer_depth?: expr, radial from the major diameter, default down to the external minor diameter, the largest ISO 4753 allows); extent?: full|length|up_to (default: length when `length` is given, up_to when `up_to` is, else full: the whole face); length?: expr (from the end the thread starts at); up_to?: [x,y,z] (a point, such as on a shoulder face: the thread runs to its place along the axis) | plane name or {origin, normal} (to where the plane crosses the axis); from?: [x,y,z] near the end of the face the thread starts at (default: the face's only free end, the one with no material past it; else the end the `face` point lies within a third of the face of; a pick in the middle of a face whose ends are alike is refused); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body: past a free end the groove runs out a pitch into the air (or through a chamfer); at a shoulder, a head or a blind hole's bottom it stops with its section clear of it, never cutting into it; a shaft thicker than the thread is refused with the size to make it, never turned down"), CommandSpec::new("solid.shell", "Shell", shell) .at("SOLID", "MODIFY") .icon("shell") @@ -2412,10 +2412,6 @@ fn hole(s: &mut Session, p: &Value) -> Result { _ => None, }; let thread = str_(p, "thread").map(|t| t.trim().to_string()).filter(|t| !t.is_empty()); - let handedness = thread_handedness(p, cmd)?; - if thread.is_none() && !handedness.is_right() { - return Err(bad(cmd, "`handedness` needs `thread` (a tapped hole)")); - } if let Some(t) = &thread && solidcraft_doc::parse_tapped_thread(t).is_none() { @@ -2588,7 +2584,6 @@ fn hole(s: &mut Session, p: &Value) -> Result { points: points.map(|x| x.0), thread, thread_depth, - handedness, to: to.map(FacePick), references, }, @@ -2894,13 +2889,6 @@ fn loft(s: &mut Session, p: &Value) -> Result { add_feature(s, p, FeatureKind::Loft { sections, operation, targets, rails, rail_fit }) } -fn thread_handedness(p: &Value, cmd: &str) -> Result { - match p.get("handedness") { - None => Ok(solidcraft_doc::ThreadHandedness::Right), - Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`handedness` must be `right` or `left`")), - } -} - fn thread(s: &mut Session, p: &Value) -> Result { let cmd = "solid.thread"; let face = p @@ -3000,13 +2988,11 @@ fn thread(s: &mut Session, p: &Value) -> Result { { return Err(bad(cmd, msg)); } - let handedness = thread_handedness(p, cmd)?; let kind = FeatureKind::Thread { face: FacePick(face), designation, length, modeled, - handedness, from, up_to, form, diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 715eb5e9e..53db16ec3 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -228,7 +228,7 @@ fn a_sketch_on_a_turned_sub_components_face_cuts_and_joins_it_from_the_top_level run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); }); for (distance, expected) in [(-3.0, "cut"), (3.0, "join")] { - assert_eq!(crate::auto_operation(&s, &json!({"distance": distance})), Some(expected), "base {base}, {distance}"); + assert_eq!(crate::auto_operation(&s, &json!({"distance": distance})).unwrap(), Some(expected), "base {base}, {distance}"); for operation in ["auto", expected] { let mut t = s.scratch(); run(&mut t, "solid.extrude", json!({"distance": distance, "operation": operation})); @@ -313,7 +313,7 @@ fn a_cut_from_the_top_level_shows_in_every_placement_and_a_later_placement_is_re run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); }); run(&mut first, "solid.extrude", json!({"distance": -3, "operation": "cut"})); - let world = first.world_state(); + let world = first.world_state().unwrap(); let placements: Vec = world.bodies.iter().filter(|b| b.definition_name() == "Stock").map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); let want = 1000.0 - std::f64::consts::PI * 4.0 * 3.0; @@ -342,8 +342,8 @@ fn a_sketch_on_a_top_level_body_beside_a_turned_part_cuts_only_that_body() { sketch_on_face(&mut s, solidcraft_geom::Vec3::new(-30.0, -30.0, 5.0), |s, c, _| { run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2})); }); - assert_eq!(crate::auto_operation(&s, &json!({"distance": -2})), Some("cut")); - assert_eq!(crate::auto_operation(&s, &json!({"distance": 2})), Some("join")); + assert_eq!(crate::auto_operation(&s, &json!({"distance": -2})).unwrap(), Some("cut")); + assert_eq!(crate::auto_operation(&s, &json!({"distance": 2})).unwrap(), Some("join")); let made = run(&mut s, "solid.extrude", json!({"distance": -2, "operation": "auto"})); let feature = s.doc.feature(made["feature"].as_u64().unwrap()).unwrap(); assert!(feature.participants.is_empty(), "{:?}", feature.participants); diff --git a/crates/engine/src/cmd/file_easyprint.rs b/crates/engine/src/cmd/file_easyprint.rs index e899553b6..19257af8a 100644 --- a/crates/engine/src/cmd/file_easyprint.rs +++ b/crates/engine/src/cmd/file_easyprint.rs @@ -31,7 +31,7 @@ pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Fo if bodies.is_empty() { return Err(bad(cmd, "select the bodies to send, or give `bodies`")); } - let doc = s.doc.painted(&s.world_state()); + let doc = s.doc.painted(&*s.world_state()?); let write = |format| solidcraft_io::export_with_metadata(&doc, &bodies, format, &s.doc.name, &s.doc.metadata); let mut fell_back = false; let (bytes, ext) = match (format, write(format)) { diff --git a/crates/engine/src/cmd/model_axis_tests.rs b/crates/engine/src/cmd/model_axis_tests.rs index 5b5ae8521..54fde4b0d 100644 --- a/crates/engine/src/cmd/model_axis_tests.rs +++ b/crates/engine/src/cmd/model_axis_tests.rs @@ -82,7 +82,7 @@ fn surface_revolve_about_a_circular_edge() { ring_profile(&mut s); run(&mut s, "surface.revolve", json!({"sketch": "Profile", "axis": {"edge": [45, 0, 0]}, "angle": "180 deg"})); run(&mut s, "parameters.change", json!({"name": "cx", "expression": "41 mm"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); // A half turn about x = 41: the far side of the profile ends up at x = 41 − 7 ± 1. let b = st.bodies.last().map(|b| b.mesh().bounds()).unwrap(); assert!((b.min.x - (41.0 - 7.0)).abs() < 1e-3, "{b:?}"); @@ -98,14 +98,14 @@ fn circular_pattern_about_a_boss_wall_follows_the_boss() { run(&mut s, "solid.hole", json!({"position": [130, 100, 5], "diameter": 2, "name": "Hole"})); run(&mut s, "solid.pattern.circular", json!({"features": ["Hole"], "axis": {"face": [110, 100, 10]}, "count": 4, "name": "Ring"})); let holes = |s: &Session, cx: f64, r: f64| { - let st = s.world_state(); + let st = s.world_state().unwrap(); let body = &st.bodies[0].body; [(r, 0.0), (0.0, r), (-r, 0.0), (0.0, -r)].iter().all(|(dx, dy)| !body.contains(Vec3::new(cx + dx, 100.0 + dy, 2.5))) }; assert!(holes(&s, 100.0, 30.0), "four holes round the boss"); run(&mut s, "parameters.change", json!({"name": "cx", "expression": "90 mm"})); assert!(holes(&s, 90.0, 40.0), "the copies turn about the boss where it is now"); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.bodies[0].body.contains(Vec3::new(100.0, 130.0, 2.5)), "not where the boss was"); } @@ -158,7 +158,7 @@ fn the_axis_keeps_its_turn_whichever_way_the_edge_runs() { let mut s = shaft(); ring_profile(&mut s); run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"edge": edge}, "angle": "90 deg", "operation": "new"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); st.bodies.last().map(|b| b.mesh().bounds()).unwrap() }; let (top, bottom) = (quarter([45.0, 0.0, 10.0]), quarter([45.0, 0.0, 0.0])); diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index cfeff6321..db5de10cc 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -1351,10 +1351,10 @@ fn pasted_and_moved_things_survive_reopening() { run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [50, 0, 0], "body_name": "Pin"})); run(&mut s, "component.activate", json!({"component": 0})); run(&mut s, "occurrence.reparent", json!({"occurrence": b_at, "parent": a})); - let before = s.world_state(); + let before = s.world_state().unwrap(); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - let after = reopened.world_state(); + let after = reopened.world_state().unwrap(); for name in ["Cube", "Cube (2)", "Pin"] { let (was, is) = (before.body(name).unwrap().mesh().bounds(), after.body(name).unwrap().mesh().bounds()); assert!(was.min.dist(is.min) < 1e-6 && was.max.dist(is.max) < 1e-6, "{name}: {was:?} → {is:?}"); @@ -1377,7 +1377,7 @@ fn a_body_seen_in_another_placement_copies_from_there() { assert_ne!(shown, "Cube"); let out = run(&mut s, "component.copy_bodies", json!({"bodies": [shown.clone()], "component": 0})); assert_eq!(out["bodies"], json!(["Cube (2)"])); - let world = s.world_state(); + let world = s.world_state().unwrap(); let (seen, copy) = (world.body(&shown).unwrap().mesh().bounds(), world.body("Cube (2)").unwrap().mesh().bounds()); assert!(seen.min.dist(copy.min) < 1e-6 && seen.max.dist(copy.max) < 1e-6, "{seen:?} vs {copy:?}"); let state = s.model.state(); diff --git a/crates/engine/src/cmd/sketch_3d_frame_tests.rs b/crates/engine/src/cmd/sketch_3d_frame_tests.rs index a7c00e35b..183afb8ae 100644 --- a/crates/engine/src/cmd/sketch_3d_frame_tests.rs +++ b/crates/engine/src/cmd/sketch_3d_frame_tests.rs @@ -365,14 +365,14 @@ fn arc3d_follows_the_sketch_owner_placement() { near(arc.center, Vec3::new(0.0, 0.0, 5.0)); assert!((arc.radius - 10.0).abs() < 1e-7, "radius {}", arc.radius); let _ = sk; - let world = s.world_state(); + let world = s.world_state().unwrap(); let ws = &world.sketch(sketch).unwrap().sketch; let arc = ws.wires[ws.wire_index(&id).unwrap()].arc.unwrap(); near(arc.center, Vec3::new(20.0, 30.0, 45.0)); near(ws.wires[ws.wire_index(&id).unwrap()].fit[0], Vec3::new(20.0, 40.0, 45.0)); drop(world); run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0]})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let ws = &world.sketch(sketch).unwrap().sketch; let arc = ws.wires[ws.wire_index(&id).unwrap()].arc.unwrap(); near(arc.center, Vec3::new(25.0, 30.0, 45.0)); @@ -411,7 +411,7 @@ fn arc3d_pipes_along_the_arc() { let wire = run(&mut s, "sketch.arc3d", json!({"start":[20,0,0],"through":[d,d,0],"end":[0,20,0]}))["curves"][0].as_str().unwrap().to_string(); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.pipe", json!({"path_sketch":sketch,"path":[wire],"diameter":4})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); let measure = solidcraft_kernel::measure(&body.body).unwrap(); let quarter = 20.0 * std::f64::consts::FRAC_PI_2; diff --git a/crates/engine/src/computed_commands_tests.rs b/crates/engine/src/computed_commands_tests.rs index b5efde92a..8ab1968d7 100644 --- a/crates/engine/src/computed_commands_tests.rs +++ b/crates/engine/src/computed_commands_tests.rs @@ -16,15 +16,15 @@ fn acceptance_preserves_file_history_and_prepared_world_without_evaluation() { let checkpoint = session.checkpoint(); let history = session.undo.len(); let prepared = session.scratch().compute_commands(&commands(), None).unwrap(); - prepared.warm_meshes(|| true); - let world = prepared.computed.world_state(); + prepared.warm_meshes(|| true).unwrap(); + let world = prepared.computed.world_state().unwrap(); let before = session.evaluations; session.accept_commands(prepared).unwrap(); assert_eq!(session.evaluations, before); assert_eq!(session.path.as_deref(), Some("working.solidcraft")); assert!(Arc::ptr_eq(&saved, &session.saved)); assert_eq!(session.undo.len(), history + 1); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); session.restore_checkpoint(checkpoint).unwrap(); assert_eq!(session.undo.len(), history); assert_eq!(session.doc.features.len(), 1); @@ -65,14 +65,14 @@ fn revision_context_selection_and_replaced_document_reject_old_work() { fn editor_marker_restoration_reuses_the_pinned_model_with_an_empty_cache() { let mut session = Session::default(); session.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); let original = session.scratch(); session.execute("timeline.roll_to", &json!({"position":0})).unwrap(); let source = session.scratch(); *session.model.cache.lock().unwrap() = Default::default(); let prepared = session.scratch().compute_editor_commands(&[], &source, original).unwrap(); assert_eq!(prepared.computed.evaluations, 0, "restoring the marker must never evaluate the old suffix"); - assert!(Arc::ptr_eq(&world, &prepared.computed.world_state())); + assert!(Arc::ptr_eq(&world, &prepared.computed.world_state().unwrap())); session.accept_commands(prepared).unwrap(); assert_eq!(session.doc.marker, None); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d160c8644..260cbacb1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -310,15 +310,17 @@ impl ComputedCommands { session.same_document_context(source) && session.selection == source.selection } - /// Prepare display tessellation before returning the transaction to the window. - pub fn warm_meshes(&self, keep_going: impl Fn() -> bool + Sync) { - self.warm_display(solidcraft_doc::display_quality::DisplayQuality::Normal, keep_going); + /// Prepare display tessellation before returning the transaction to the window; a model that + /// cannot be placed is the error. + pub fn warm_meshes(&self, keep_going: impl Fn() -> bool + Sync) -> Result<()> { + self.warm_display(solidcraft_doc::display_quality::DisplayQuality::Normal, keep_going) } /// Prepare both the reference picking mesh and the GPU plan/highlight mesh at the /// selected quality. Warming only the reference mesh leaves cold planning on the UI. - pub fn warm_display(&self, quality: solidcraft_doc::display_quality::DisplayQuality, keep_going: impl Fn() -> bool + Sync) { - self.computed.world_state().warm_display_at(quality, keep_going); + pub fn warm_display(&self, quality: solidcraft_doc::display_quality::DisplayQuality, keep_going: impl Fn() -> bool + Sync) -> Result<()> { + self.computed.world_state()?.warm_display_at(quality, keep_going); + Ok(()) } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 97f0db135..a9d8c3b03 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1980,7 +1980,7 @@ fn components_occurrences_and_world_placement() { assert_eq!(s.pending_moves, pending); // Placed by the first placement, the body stays where it is in the world there. run(&mut s, "component.move_bodies", json!({"bodies": ["Base"], "component": "Arm", "component_path": [occ]})); - assert_eq!(s.world_state().body("Base").unwrap().component, cid); + assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, cid); assert_eq!(bbox(&mut s, "Base")["min"], json!([0.0, 0.0, 0.0])); run(&mut s, "edit.undo", json!({})); assert_eq!(s.doc.to_json(), document); @@ -3657,7 +3657,7 @@ fn an_exact_pick_of_a_region_cut_by_the_face_outline_takes_only_that_region() { let state = s2.model.state(); let Some(solidcraft_doc::FeatureKind::Extrude { profiles, .. }) = s2.doc.features.last().map(|f| &f.kind) else { panic!("an extrude") }; let count = solidcraft_doc::profile_selection_indices(state.sketch(id).unwrap(), profiles).unwrap().len(); - let v = state.bodies.iter().filter(|b| b.name.starts_with("Pad")).map(|b| b.body.tessellate(1e-2).unwrap().measure().volume).sum(); + let v = state.bodies.iter().filter(|b| b.name.starts_with("Pad")).map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-2)).unwrap().measure().volume).sum(); (v, count) }; for (profiles, want, n) in [ @@ -4498,7 +4498,7 @@ fn a_cut_leaves_hidden_bodies_alone() { run(&mut s, "solid.extrude", json!({"distance": 30, "direction": "negative", "operation": "cut"})); s }; - let vol = |s: &Session, name: &str| solidcraft_kernel::measure(&s.world_state().body(name).unwrap().body).unwrap().volume; + let vol = |s: &Session, name: &str| solidcraft_kernel::measure(&s.world_state().unwrap().body(name).unwrap().body).unwrap().volume; let full = 20.0 * 20.0 * 10.0; let mut hidden = setup(true); assert!((vol(&hidden, "Below") - full).abs() < 1e-6, "the hidden body is not cut"); diff --git a/crates/engine/src/thread_tests.rs b/crates/engine/src/thread_tests.rs index 49919d921..b76a220a6 100644 --- a/crates/engine/src/thread_tests.rs +++ b/crates/engine/src/thread_tests.rs @@ -150,149 +150,6 @@ fn tapped_thread_depth_rejects_invalid_or_excessive_values_atomically() { assert_eq!(s.doc.to_json(), before); } -#[test] -fn thread_handedness_cosmetic_defaults_and_save_reopen_keep_axis_and_extent() { - use solidcraft_doc::{Document, FeatureKind, ThreadHandedness}; - for (hole, designation) in [(false, "M6"), (true, "M6"), (true, "G 1/4"), (true, "1/4-20 UNC")] { - let mut reference = None; - for hand in [None, Some("right"), Some("left")] { - let mut s = Session::default(); - let (command, mut params) = if hole { - run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10})); - ( - "solid.hole", - json!({"position":[10,10,10],"thread":designation,"depth":6,"thread_depth":3, - "references":[{"edge":[0,10,10],"distance":"7 mm"},{"edge":[10,0,10],"distance":"8 mm"}]}), - ) - } else { - run(&mut s, "solid.cylinder", json!({"radius":3,"height":6})); - ("solid.thread", json!({"face":[3,0,2],"designation":"M6","length":4})) - }; - if let Some(hand) = hand { - params["handedness"] = json!(hand); - } - run(&mut s, command, params); - let expected = if hand == Some("left") { ThreadHandedness::Left } else { ThreadHandedness::Right }; - let info = s.model.state().threads[0].clone(); - assert_eq!(info.handedness, expected); - if hole { - assert!((info.end - info.start - 3.0).abs() < 1e-8, "direction must retain the independent thread depth"); - } - let dimensions = (info.axis_point, info.axis, info.start, info.end, info.major_diameter, info.pitch); - assert_eq!(*reference.get_or_insert(dimensions), dimensions, "direction must not change axis, length or size"); - let mut kind = serde_json::to_value(&s.doc.features.last().unwrap().kind).unwrap(); - assert_eq!(kind.get("handedness"), (expected == ThreadHandedness::Left).then(|| json!("left")).as_ref()); - // An old feature with no field still deserializes to Right, for both feature types. - kind.as_object_mut().unwrap().remove("handedness"); - let old: FeatureKind = serde_json::from_value(kind).unwrap(); - assert!(matches!( - old, - FeatureKind::Hole { handedness: ThreadHandedness::Right, .. } | FeatureKind::Thread { handedness: ThreadHandedness::Right, .. } - )); - let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); - assert_eq!(reopened.model.state().threads[0], info); - } - } -} - -#[test] -fn thread_handedness_invalid_values_fail_without_changing_the_document() { - for hole in [false, true] { - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius":3,"height":6})); - let saved = s.doc.to_json(); - for hand in [json!("clockwise"), json!("LEFT"), json!(null), json!(true), json!(1)] { - let (command, params) = if hole { - ("solid.hole", json!({"position":[0,0,6],"thread":"M6","handedness":hand})) - } else { - ("solid.thread", json!({"face":[3,0,2],"designation":"M6","handedness":hand})) - }; - assert!(s.execute(command, ¶ms).unwrap_err().to_string().contains("handedness")); - assert_eq!(s.doc.to_json(), saved); - } - if hole { - assert!(s.execute("solid.hole", &json!({"position":[0,0,6],"diameter":2,"handedness":"left"})).is_err()); - assert_eq!(s.doc.to_json(), saved); - } - } -} - -#[test] -fn thread_handedness_modelled_internal_and_external_keep_chirality_and_bounded_volume() { - use solidcraft_doc::Document; - for internal in [false, true] { - let mut bodies = Vec::new(); - for hand in ["right", "left"] { - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius":if internal {6.0} else {3.0},"height":4,"body_name":"Stock"})); - if internal { - run(&mut s, "solid.hole", json!({"position":[0,0,4],"diameter":5})); - } - let face = json!([if internal { 2.5 } else { 3.0 }, 0, 3.5]); - run(&mut s, "solid.thread", json!({"face":face,"designation":"M6x1","length":3,"modeled":true,"handedness":hand})); - let state = s.model.state(); - let body = state.body("Stock").unwrap().body.clone(); - assert!(body.validity().is_empty(), "{internal}/{hand}: {:?}", body.validity()); - let before = volume(&mut s, "Stock"); - let mut reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); - assert!((volume(&mut reopened, "Stock") - before).abs() < 1e-8); - let brep_volume = crate::kernel::measure(&body).unwrap().volume; - bodies.push((body, before, brep_volume)); - } - let [(right, vr, br), (left, vl, bl)] = bodies.as_slice() else { panic!("two directions") }; - eprintln!("handedness internal={internal}: mesh_mm3={vr}/{vl}, brep_mm3={br}/{bl}"); - for body in [right, left] { - let mesh = body.tessellate(0.001).unwrap(); - let low = mesh.positions.iter().map(|p| p.z).fold(f64::INFINITY, f64::min); - let high = mesh.positions.iter().map(|p| p.z).fold(f64::NEG_INFINITY, f64::max); - assert!(low.abs() < 1e-8 && (high - 4.0).abs() < 1e-8, "physical axial bounds: {low}/{high}"); - for z in [0.25, 1.5, 2.5, 3.75] { - assert_eq!(body.contains(Vec3::new(0.0, 0.0, z)), !internal, "axis stays solid in a shaft and open in a bore"); - if internal { - for i in 0..24 { - let a = 2.0 * PI * i as f64 / 24.0; - assert!(body.contains(Vec3::new(4.5 * a.cos(), 4.5 * a.sin(), z)), "the outer wall remains whole"); - } - } - } - } - let radius = if internal { 2.75 } else { 2.65 }; - let mut different = 0; - for z in [0.4, 1.1, 1.4, 1.8, 2.2, 2.6, 3.1, 3.5] { - for i in 0..24 { - let angle = 2.0 * PI * (i as f64 + 0.17) / 24.0; - let p = Vec3::new(radius * angle.cos(), radius * angle.sin(), z); - let reflected = Vec3::new(-p.x, p.y, p.z); - assert_eq!(right.contains(p), left.contains(reflected), "actual mirrored helix: {internal} at {p:?}"); - different += usize::from(right.contains(p) != left.contains(p)); - if z < 1.0 { - assert!(right.contains(p), "the 3 mm thread must leave the lower stub unchanged"); - } - } - } - assert!(different > 20, "Left must change real geometry, not just metadata: {internal}: {different}"); - // The sweep itself is an exact reflection (doc test). The existing Boolean first - // facets the curved stock within pitch * .005 mm. A nominal stock-faceting - // regression envelope uses radial annuli [r-d, r+d], with flat caps unchanged: - // pi*h*((r+d)^2-(r-d)^2) = 4*pi*h*r*d, summed over the outer and bore cylinders. - // Exact-set cutting would not enlarge the stock's symmetric difference. The BSP - // and rebuild also use numerical epsilons, so this conservative secondary ceiling - // is not a rigorous bound on every Boolean error, nor a precision/equal-volume proof. - let delta = 1.0 * 0.005; - let radii = if internal { 6.0 + 2.5 } else { 3.0 }; - let budget = 4.0 * PI * 4.0 * radii * delta; - eprintln!( - "handedness internal={internal}: post_boolean_delta_mm3={}, stock_faceting_budget_mm3={budget}, relative_delta={}", - (br - bl).abs(), - (br - bl).abs() / br - ); - assert!( - (br - bl).abs() <= budget, - "post-Boolean volume exceeds the configured stock faceting envelope: {internal}: {br}/{bl}, budget {budget}" - ); - } -} - /// Keep the original 48-station reproduction of the shell error even though new fine /// threads now use more stations. The same cut polygons must rebuild as a closed solid. #[test] @@ -362,66 +219,25 @@ fn modelled_full_length_fine_threads_on_large_shafts() { } } -/// A modelled thread on a shaft thicker than it turns the shaft down to the major diameter -/// over the threaded length, then cuts the thread: an M6 over the top 8 mm of an 8 mm shaft -/// leaves a 6 mm threaded section on an 8 mm stub, its turned face named for later features. -/// A shaft of the thread's own size is cut as it is. +/// Issue 2705: an M14 over the top 10 mm of a 14.6 mm boss on a plate. A modelled thread never +/// changes the size of the shaft it is on (#1018, #2853): it is refused with the size to make +/// the shaft, and the part is unchanged (tests/kernel-cases/threads/2705). #[test] -fn a_shaft_thicker_than_a_modelled_thread_is_turned_down_to_it() { - let (p, len) = (1.0, 8.0); - let root = 3.0 - 5.0 * p * 3f64.sqrt() / 16.0; - let groove = per_turn(root, 3.0, |r| p / 4.0 + 2.0 * (r - root) * (PI / 6.0).tan()) * len / p; - for (shaft, turned) in [(8.0, true), (6.0, false)] { - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius": shaft / 2.0, "height": 12, "body_name": "Shaft"})); - run(&mut s, "solid.thread", json!({"face": [shaft / 2.0, 0, 11], "designation": "M6", "length": len, "modeled": true})); - let ring = PI * (shaft * shaft / 4.0 - 9.0) * len; - let want = PI * shaft * shaft / 4.0 * 12.0 - ring - groove; - let got = volume(&mut s, "Shaft"); - assert!((got - want).abs() < groove * 0.03, "M6 on {shaft} mm: {got} mm³, want {want}"); - let st = s.model.state(); - let Some(b) = st.body("Shaft") else { panic!("no shaft") }; - assert!(b.body.validity().is_empty(), "{shaft} mm: {:?}", b.body.validity()); - // Nothing past the major diameter over the threaded length; the stub keeps its size. - let round = |z: f64, r: f64| { - (0..24).filter(|i| b.body.contains(Vec3::new(r * (PI * *i as f64 / 12.0).cos(), r * (PI * *i as f64 / 12.0).sin(), z))).count() - }; - assert_eq!(round(8.0, 3.05), 0, "{shaft} mm: the threaded part is turned to 6 mm"); - assert_eq!(round(2.0, shaft / 2.0 - 0.05), 24, "{shaft} mm: the stub is whole"); - let names = solidcraft_doc::naming::face_names(b); - let fid = s.doc.features.last().map(|f| f.id).unwrap_or(0); - let named = |role: &str| names.iter().any(|n| n.starts_with(&format!("F{fid}:{role}"))); - assert_eq!(named("turned"), turned, "{shaft} mm: {names:?}"); - assert_eq!(named("shoulder:"), turned, "{shaft} mm: {names:?}"); - } - - // A 9 mm shaft is close enough to M8 to be offered it; it was refused as too thick (#2688). - let mut s = Session::default(); - run(&mut s, "solid.cylinder", json!({"radius": 4.5, "height": 10, "body_name": "Shaft"})); - run(&mut s, "solid.thread", json!({"face": [4.5, 0, 5], "designation": "M8", "modeled": true})); - let root = 4.0 - 5.0 * 1.25 * 3f64.sqrt() / 16.0; - let groove = per_turn(root, 4.0, |r| 1.25 / 4.0 + 2.0 * (r - root) * (PI / 6.0).tan()) * 10.0 / 1.25; - let (want, got) = (PI * 16.0 * 10.0 - groove, volume(&mut s, "Shaft")); - assert!((got - want).abs() < groove * 0.03, "M8 on 9 mm: {got} mm³, want {want}"); -} - -/// Issue 2705: an M14 over the top 10 mm of a 14.6 mm boss on a plate. Turned to 14 mm first: -/// 1600 + π 7.3² 15 − π (7.3² − 7²) 10 − 5 turns of 50.189 mm³ (tests/kernel-cases/threads/2705). -#[test] -fn an_m14_thread_on_a_14_6_mm_boss_turns_it_to_14_mm() { +fn an_m14_thread_on_a_14_6_mm_boss_is_refused_with_the_size_to_make_it() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"corner": [-10, -10, 0], "length": 20, "width": 20, "height": 4, "body_name": "Part"})); run(&mut s, "solid.cylinder", json!({"radius": 7.3, "height": 15, "base": [0, 0, 4], "operation": "join", "targets": ["Part"]})); - run(&mut s, "solid.thread", json!({"face": [7.3, 0, 17], "designation": "M14", "length": 10, "modeled": true})); - let got = volume(&mut s, "Part"); - assert!((got - 3725.5127).abs() < 3725.5127 * 0.01, "{got} mm³"); + let before = volume(&mut s, "Part"); + let thread = json!({"face": [7.3, 0, 17], "designation": "M14", "length": 10, "modeled": true}); + let e = s.execute("solid.thread", &thread).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("this 14.6 mm shaft is too thick for a modelled M14 thread; make the shaft 14 mm for M14"), "{e}"); + assert!((volume(&mut s, "Part") - before).abs() < 1e-9); } -/// A shaft thinner than the thread's minor diameter is still refused, and so is a cosmetic -/// thread on a shaft thicker than it (a note changes nothing to turn). A shaft the part goes on -/// round (standing against a wall) is not turned into the wall. +/// A shaft thinner than the thread's minor diameter is refused, and so is a thread on a shaft +/// far thicker than it. #[test] -fn a_thin_shaft_or_one_the_part_surrounds_is_refused() { +fn a_shaft_far_off_the_threads_size_is_refused() { let refused = |s: &mut Session, body: &str, p: Value| { let before = volume(s, body); let e = s.execute("solid.thread", &p).err().map(|e| e.to_string()).unwrap_or_default(); @@ -438,11 +254,8 @@ fn a_thin_shaft_or_one_the_part_surrounds_is_refused() { let e = refused(&mut s, "Shaft", json!({"face": [4, 0, 5], "designation": "M6"})); assert!(e.contains("an M6 thread does not fit a 8.00 mm shaft"), "{e}"); - let mut s = Session::default(); - run(&mut s, "solid.box", json!({"corner": [2, -10, 0], "length": 10, "width": 20, "height": 10, "body_name": "Part"})); - run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 10, "operation": "join", "targets": ["Part"]})); - let e = refused(&mut s, "Part", json!({"face": [-4, 0, 5], "designation": "M6", "modeled": true})); - assert!(e.contains("this 8 mm shaft is too thick for a modelled M6 thread") && e.contains("part around it"), "{e}"); + let e = refused(&mut s, "Shaft", json!({"face": [4, 0, 5], "designation": "M6", "modeled": true})); + assert!(e.contains("an M6 thread does not fit a 8.00 mm shaft"), "{e}"); } #[test] @@ -566,9 +379,9 @@ fn a_modelled_thread_that_would_cut_nothing_is_refused() { /// Issue 2688: an M8 modelled thread in a 6 mm hole (narrower than its 6.65 mm minor diameter) /// was refused as "the face is too far from the thread's diameter". It says what is wrong and -/// what to drill, as a hole that is too wide does. (A shaft too thick is turned down.) +/// what to drill, as a hole that is too wide does; and the same for a shaft that is too thick. #[test] -fn a_hole_too_narrow_says_so_and_what_fits() { +fn a_hole_too_narrow_or_a_shaft_too_thick_says_which_and_what_fits() { let mut s = hex_nut(6.0); let before = volume(&mut s, "Nut"); let e = s.execute("solid.thread", &json!({"face": [3.0, 0, 2], "designation": "M8", "modeled": true})).err().map(|e| e.to_string()); @@ -576,6 +389,13 @@ fn a_hole_too_narrow_says_so_and_what_fits() { assert!(e.contains("this 6 mm hole is too narrow for a modelled M8 thread") && e.contains("drill 6.75 mm for M8"), "{e}"); assert!(!e.contains("too far"), "{e}"); assert!((volume(&mut s, "Nut") - before).abs() < 1e-9); + + let mut s = Session::default(); + // 9 mm is close enough to M8 to be offered it, too thick to cut it. + run(&mut s, "solid.cylinder", json!({"radius": 4.5, "height": 10, "body_name": "Shaft"})); + let e = s.execute("solid.thread", &json!({"face": [4.5, 0, 5], "designation": "M8", "modeled": true})).err().map(|e| e.to_string()); + let e = e.unwrap_or_default(); + assert!(e.contains("this 9 mm shaft is too thick for a modelled M8 thread") && e.contains("make the shaft 8 mm for M8"), "{e}"); } /// The limit is a quarter of the basic depth 5H/8: a hole up to 4.78 mm for M5 (4.86 mm for diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rs index 6c168855e..dc5461fc2 100644 --- a/crates/gpu/tests/depth.rs +++ b/crates/gpu/tests/depth.rs @@ -404,9 +404,9 @@ fn a_cut_hides_the_edges_behind_it() { let (w, h) = (400, 300); for (mode, c) in capturers() { for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&plain); + let mut cam = view::home_camera(&plain).unwrap(); cam.fov = fov; - let radius = view::scene(&plain, &cam).radius; + let radius = view::scene(&plain, &cam).unwrap().radius; // The cap on screen: the cut's rectangle, its outline left out (2 px in). let corner = |x: f64, z: f64| cam.to_screen(Vec3::new(x, -16.0, z), f64::from(w), f64::from(h), radius).map(|(x, y, _)| (x, y)); let cap: Vec<(f64, f64)> = [(-20.0, 0.0), (20.0, 0.0), (20.0, 30.0), (-20.0, 30.0)].iter().filter_map(|(x, z)| corner(*x, *z)).collect(); @@ -422,7 +422,7 @@ fn a_cut_hides_the_edges_behind_it() { }; let inside = |x: f64, y: f64| inside_by(x, y, 2.0); // Without the ground grid, whose extent follows the design. - let shot = |s: &Session| c.rgba(&Scene { grid: Vec::new(), ..view::scene(s, &cam) }, &cam, w, h).unwrap(); + let shot = |s: &Session| c.rgba(&Scene { grid: Vec::new(), ..view::scene(s, &cam).unwrap() }, &cam, w, h).unwrap(); let (a, b) = (shot(&plain), shot(&cut_through)); let (mut shown, mut all) = (0, 0); for (i, (p, q)) in pixels(&a).zip(pixels(&b)).enumerate() { diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rs index 69fdc37e4..09ecf61f9 100644 --- a/crates/ui-egui/src/apply_off_thread_tests.rs +++ b/crates/ui-egui/src/apply_off_thread_tests.rs @@ -313,7 +313,7 @@ fn cancelling_an_edit_restores_pinned_geometry_without_evaluating_an_evicted_suf let (mut h, target) = cut_chain(); h.app.run("solid.box", json!({"corner":[100,0,0],"length":2,"width":2,"height":2})).unwrap(); h.app.run("edit.undo", json!({})).unwrap(); - let before = h.app.session.world_state(); + let before = h.app.session.world_state().unwrap(); let history = (h.app.session.undo.len(), h.app.session.redo.len()); let visibility = h.app.session.visibility.clone(); h.call("ui.editFeature", json!({"feature":target})); @@ -336,7 +336,7 @@ fn cancelling_an_edit_restores_pinned_geometry_without_evaluating_an_evicted_suf assert_eq!(h.app.session.visibility, visibility, "temporary sketch display does not change stored visibility"); assert_eq!(h.app.session.doc.marker, None); assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); - assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.world_state())); + assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.world_state().unwrap())); assert_eq!(h.app.session.selection, vec![solidcraft_engine::Sel::Axis { name: "X".into() }]); } @@ -370,7 +370,7 @@ fn a_worker_error_then_cancel_preserves_original_world_history_redo_and_selectio let (mut h, target) = cut_chain(); h.app.run("solid.box", json!({"corner":[100,0,0],"length":2,"width":2,"height":2})).unwrap(); h.app.run("edit.undo", json!({})).unwrap(); - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let document = h.app.session.doc.clone(); let history = (h.app.session.undo.len(), h.app.session.redo.len()); h.app.session.selection = vec![solidcraft_engine::Sel::Feature { id: target }]; @@ -395,7 +395,7 @@ fn a_worker_error_then_cancel_preserves_original_world_history_redo_and_selectio }); assert_eq!(window.features(), (0, 0)); assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc)); - assert!(std::sync::Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(std::sync::Arc::ptr_eq(&world, &h.app.session.world_state().unwrap())); assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); assert_eq!(h.app.session.selection, selection); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c415e3c4a..ff04cc324 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -10,9 +10,7 @@ use serde_json::{Value, json}; use solidcraft_engine::Sel; use solidcraft_engine::Session; use solidcraft_engine::doc::expr::Kind as ValueKind; -use solidcraft_engine::doc::{ - AxisRef, Direction, FeatureKind, FilletStyle, HoleKind, Operation, PatternKind, PlaneRef, ProfileSel, ThinSide, ThreadHandedness, -}; +use solidcraft_engine::doc::{AxisRef, Direction, FeatureKind, FilletStyle, HoleKind, Operation, PatternKind, PlaneRef, ProfileSel, ThinSide}; use solidcraft_engine::geom::{Aabb3, Vec3}; use crate::SolveApp; @@ -240,7 +238,6 @@ crate::dialog_descriptor::dialog_descriptors! { Thread { designation: String, length: String, - handedness: ThreadHandedness, /// The last automatic size; a different value is a manual override. Keep automatic /// features automatic when applying, even though their resolved size is visible. suggested: Option, @@ -418,7 +415,6 @@ pub struct HoleOpts { /// Use the full useful cylindrical wall, independently of the drill extents. pub thread_full_depth: bool, pub thread_depth: String, - pub handedness: ThreadHandedness, } impl Default for HoleOpts { @@ -434,7 +430,6 @@ impl Default for HoleOpts { refs: Default::default(), thread_full_depth: true, thread_depth: "10 mm".into(), - handedness: ThreadHandedness::Right, } } } @@ -621,7 +616,7 @@ fn start_applying( if watching.is_cancelled() { return Err("feature computation cancelled".into()); } - prepared.warm_display(quality, || !watching.is_cancelled()); + prepared.warm_display(quality, || !watching.is_cancelled()).map_err(|e| e.to_string())?; if watching.is_cancelled() { return Err("feature computation cancelled".into()); } @@ -1960,7 +1955,7 @@ pub fn planar_face(s: &Session, body: &str, face: usize) -> Option<(Vec3, Vec3)> /// The fillet or chamfer feature whose blend a body face is (a piece or copy of one too). pub fn blend_feature(s: &Session, body: &str, face: usize) -> Option { use solidcraft_engine::doc::persistent_name; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let b = st.body(body)?; let names = solidcraft_engine::doc::naming::face_names(b); let name = names.get(face).filter(|n| persistent_name::is_blend(n))?; @@ -4408,9 +4403,6 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S if !opts.thread_full_depth { params["thread_depth"] = json!(opts.thread_depth.trim()); } - if !opts.handedness.is_right() { - params["handedness"] = json!(opts.handedness); - } } match *kind { 1 => { @@ -4680,7 +4672,7 @@ pub fn axis_of(app: &SolveApp, sel: &Sel) -> Option<(Vec3, Vec3)> { /// (centre, unit normal, radius). A round edge stands for its circle wherever a 3D pick wants /// an axis (through the centre, along the normal) or a point (the centre). pub(crate) fn edge_circle(s: &Session, body: &str, index: usize) -> Option<(Vec3, Vec3, f64)> { - edge_circle_in(&s.world_state(), body, index) + edge_circle_in(&crate::open_meshing::session_world(s), body, index) } /// [`edge_circle`] in a given model state (a dialog editing a feature looks at the model before it). @@ -4700,7 +4692,7 @@ pub(crate) fn round_axis(s: &Session, sel: &Sel) -> Option<(Vec3, Vec3)> { let (o, d) = match sel { Sel::Edge { body, index, .. } => edge_circle(s, body, *index).map(|(c, n, _)| (c, n))?, Sel::Face { body, index, .. } => { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let b = st.body(body)?; match kernel::guard("axis of a face", || Ok(kernel::face_surface(&b.body, *index))).ok().flatten()? { FaceSurface::Cylinder { origin, axis, .. } => (origin, *axis), @@ -4728,7 +4720,7 @@ fn round_axis_ref(app: &SolveApp, sel: &Sel) -> Option { fn is_straight_edge(s: &Session, sel: &Sel) -> bool { let Sel::Edge { body, index, .. } = sel else { return false }; - let Some(b) = s.world_state().body(body).cloned() else { return false }; + let Some(b) = crate::open_meshing::session_world(s).body(body).cloned() else { return false }; let m = b.mesh(); let Some(e) = m.edges.get(*index) else { return false }; let (Some(a), Some(z)) = (e.first().copied(), e.last().copied()) else { return false }; @@ -5035,7 +5027,7 @@ fn point_sel(s: &Session, g: &solidcraft_engine::doc::construct::GeoRef) -> Opti /// face where it is now. pub(crate) fn model_axis_sel(s: &Session, g: &solidcraft_engine::doc::construct::GeoRef) -> Option { use solidcraft_engine::doc::construct::GeoRef; - let at = g.picked_point(&s.world_state())?; + let at = g.picked_point(&crate::open_meshing::session_world(s))?; match g { GeoRef::Edge { .. } => edge_sel(s, at), GeoRef::Face { .. } => face_sel(s, at), @@ -5315,7 +5307,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + FeatureKind::Hole { position, at, direction, diameter, depth, hole, points, thread, thread_depth, to, references } => { let mut d = start("solid.hole")?; let mut k = hole_defaults(s); if let Kind::Hole { diameter: dia, depth: dep, kind, cb_diameter, cb_depth, cs_diameter, cs_angle, opts } = &mut k { @@ -5323,7 +5315,6 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option json!({"click":{"handle":"dialog:OK"}}), "enter" => json!({"key":"Enter"}), @@ -555,7 +555,7 @@ fn top_dialog_buttons_apply_and_cancel_like_the_footer() { if how == "escape" { assert_eq!(h.app.session.doc.to_json(), design, "Esc leaves the design as it was"); } else { - assert_eq!(h.app.session.world_state().bodies.len(), bodies + 1, "{how}: the revolve is made"); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), bodies + 1, "{how}: the revolve is made"); } } } @@ -634,11 +634,11 @@ fn top_dialog_buttons_and_the_view_corner_agree() { } for handle in ["dialog:ok", "view:confirm:ok"] { let mut h = open("solid.revolve"); - let bodies = h.app.session.world_state().bodies.len(); + let bodies = h.app.session.world_state().unwrap().bodies.len(); h.step(&json!({"click":{"handle":handle}})).unwrap(); h.settle(); assert!(h.app.dialog.is_none(), "{handle}: the dialog closes"); - assert_eq!(h.app.session.world_state().bodies.len(), bodies + 1, "{handle}: the revolve is made"); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), bodies + 1, "{handle}: the revolve is made"); } } @@ -906,7 +906,7 @@ fn extrude_builds_the_one_region_clicked_where_the_face_outline_cuts_a_profile() let sketch = h.app.run("sketch.create", json!({"plane": {"face": [0, 0, 10]}})).unwrap()["sketch"].as_u64().unwrap(); h.app.run("sketch.circle.center", json!({"center": [10, 0], "radius": 6})).unwrap(); h.app.run("sketch.finish", json!({})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let ss = state.sketch(sketch).unwrap(); assert_eq!(ss.profiles.len(), 3, "the lens, the crescent past the face and the rest of the face"); let index = ss.profiles.iter().position(|p| p.region.contains(solidcraft_engine::geom::Vec2::new(x, 0.0))).unwrap(); @@ -924,7 +924,7 @@ fn extrude_builds_the_one_region_clicked_where_the_face_outline_cuts_a_profile() let before = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap(); let made = h.app.run(id, p.clone()).unwrap()["feature"].as_u64().unwrap(); let Some(FeatureKind::Extrude { profiles, .. }) = h.app.session.doc.feature(made).map(|f| f.kind.clone()) else { panic!("an extrude") }; - let after = h.app.session.world_state(); + let after = h.app.session.world_state().unwrap(); let used = solidcraft_engine::doc::profile_selection_indices(after.sketch(sketch).unwrap(), &profiles).unwrap(); assert_eq!(used, vec![index], "the region clicked at x = {x}, and only it"); let volume = h.app.run("inspect.measure", json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap(); diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 2df449cc0..89ea3efd9 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -527,7 +527,6 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: if opts.tapped { enter |= crate::dialogs_thread::hole_rows(ui, &app.session.doc, &mut opts.thread, &mut opts.custom_thread); ui_kit::checkbox_grid(ui, &mut [("Full thread depth", &mut opts.thread_full_depth)], 1); - crate::dialogs_thread::handedness_row(ui, &mut opts.handedness, "hole_handedness"); } // Through all, the tip lies past the part. if !opts.all { diff --git a/crates/ui-egui/src/dialogs_insert_drawing.rs b/crates/ui-egui/src/dialogs_insert_drawing.rs index 2e59b94a3..c59f7b503 100644 --- a/crates/ui-egui/src/dialogs_insert_drawing.rs +++ b/crates/ui-egui/src/dialogs_insert_drawing.rs @@ -105,7 +105,7 @@ mod tests { } fn lines(h: &Harness) -> Vec<(solidcraft_engine::geom::Vec2, solidcraft_engine::geom::Vec2)> { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; (0..sk.curves.len()) .filter_map(|i| match sk.shape(i) { diff --git a/crates/ui-egui/src/dialogs_move.rs b/crates/ui-egui/src/dialogs_move.rs index 87c98d81e..8ee70fbe7 100644 --- a/crates/ui-egui/src/dialogs_move.rs +++ b/crates/ui-egui/src/dialogs_move.rs @@ -98,9 +98,12 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Kind) -> bool { fn sel_point(app: &SolveApp, d: &Dialog, s: Option<&Sel>) -> Option { match s? { Sel::Edge { body, index, point } => { + // As every pick reads the placed model: one that cannot be placed has no bodies here. let st = match d.editing { - Some((id, _)) => std::sync::Arc::new(solidcraft_engine::doc::world_state(&app.session.doc, &app.session.model.state_before(id))), - None => app.session.world_state(), + Some((id, _)) => std::sync::Arc::new( + solidcraft_engine::doc::world_state(&app.session.doc, &app.session.model.state_before(id)).unwrap_or_default(), + ), + None => crate::open_meshing::session_world(&app.session), }; Some(crate::dialogs::edge_circle_in(&st, body, *index).map_or(*point, |(c, ..)| c)) } diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rs index f28699998..a48f1a610 100644 --- a/crates/ui-egui/src/dialogs_sketch_tests.rs +++ b/crates/ui-egui/src/dialogs_sketch_tests.rs @@ -376,7 +376,7 @@ fn transform_handles_and_fields_scale_move_and_turn_the_picks() { h.step(&json!({"key": "Enter"})).unwrap(); h.settle(); assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN)); for p in (0..sk.curves.len()).flat_map(|i| sk.polyline(i)) { @@ -387,7 +387,7 @@ fn transform_handles_and_fields_scale_move_and_turn_the_picks() { assert!((hi.0 - 55.0).abs() < 1.5 && (hi.1 - 40.0).abs() < 1.5, "the far corner went to (55, 40): {hi:?}"); h.app.run("edit.undo", json!({})).unwrap(); h.settle(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let top = (0..sk.curves.len()).flat_map(|i| sk.polyline(i)).fold(f64::MIN, |m, p| m.max(p.x)); assert!((top - 40.0).abs() < 1e-6, "one undo puts it back: {top}"); diff --git a/crates/ui-egui/src/dialogs_thread.rs b/crates/ui-egui/src/dialogs_thread.rs index 7058abbe2..7ba45a9a6 100644 --- a/crates/ui-egui/src/dialogs_thread.rs +++ b/crates/ui-egui/src/dialogs_thread.rs @@ -7,8 +7,8 @@ use serde_json::{Value, json}; use solidcraft_engine::doc::thread_forms::{SteepFlank, ThreadForm, ThreadHand, ThreadTip}; use solidcraft_engine::doc::{ - Document, Expr, FeatureKind, TappedThreadFamily, ThreadHandedness, ThreadLimit, ThreadRunout, metric_thread_sizes, parse_metric_thread, - parse_tapped_thread, tapped_thread_sizes, + Document, Expr, FeatureKind, TappedThreadFamily, ThreadLimit, ThreadRunout, metric_thread_sizes, parse_metric_thread, parse_tapped_thread, + tapped_thread_sizes, }; use solidcraft_engine::{Sel, Session}; @@ -156,14 +156,6 @@ pub(crate) fn hole_rows(ui: &mut egui::Ui, doc: &Document, designation: &mut Str enter || (response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) } -pub(crate) fn handedness_row(ui: &mut egui::Ui, handedness: &mut ThreadHandedness, id: &str) { - let mut selected = usize::from(*handedness == ThreadHandedness::Left); - form_row(ui, "thread.direction", |ui| { - combo(ui, id, &["thread.right_hand", "thread.left_hand"], &mut selected); - }); - *handedness = if selected == 1 { ThreadHandedness::Left } else { ThreadHandedness::Right }; -} - /// The forms offered. The square thread is left out: no standard defines it, and the command /// refuses it ([`ThreadForm::refused`]). const FORMS: &[(&str, ThreadForm)] = &[ diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs index a9e84b78d..f438dc9e0 100644 --- a/crates/ui-egui/src/dimension_create_ui_tests.rs +++ b/crates/ui-egui/src/dimension_create_ui_tests.rs @@ -1160,7 +1160,7 @@ fn model_text(h: &Harness, param: &str) -> [f32; 2] { let sk = h .app .session - .world_state() + .world_state().unwrap() .sketch(h.app.session.doc.features.iter().find(|f| f.name.starts_with("Sketch")).unwrap().id) .unwrap() .sketch @@ -1172,7 +1172,7 @@ fn model_text(h: &Harness, param: &str) -> [f32; 2] { /// The extruded plate's width and depth (x, y), rounded to 0.001 mm. fn plate_max(h: &Harness) -> [f64; 2] { - let b = h.app.session.world_state().body("Plate").unwrap().mesh().bounds(); + let b = h.app.session.world_state().unwrap().body("Plate").unwrap().mesh().bounds(); [((b.max.x - b.min.x) * 1000.0).round() / 1000.0, ((b.max.y - b.min.y) * 1000.0).round() / 1000.0] } @@ -1238,7 +1238,7 @@ fn a_driven_shown_dimension_is_read_only() { h.app.run("sketch.dimension", json!({"entities":["l3"],"driven":true,"text_at":[10,14]})).unwrap(); h.app.run("sketch.finish", json!({})).unwrap(); h.settle(); - let id = h.app.session.world_state().sketch(sketch).unwrap().sketch.constraints.iter().find(|c| c.driven).unwrap().id.clone(); + let id = h.app.session.world_state().unwrap().sketch(sketch).unwrap().sketch.constraints.iter().find(|c| c.driven).unwrap().id.clone(); let (_, _, p) = crate::dim_view::model_drawn().into_iter().find(|(_, d, _)| *d == id).unwrap(); let doc = h.app.session.doc.to_json(); h.step(&json!({"click":[p.x, p.y],"double":true})).unwrap(); diff --git a/crates/ui-egui/src/edit_clipboard_tests.rs b/crates/ui-egui/src/edit_clipboard_tests.rs index 6d15a184b..a572f9003 100644 --- a/crates/ui-egui/src/edit_clipboard_tests.rs +++ b/crates/ui-egui/src/edit_clipboard_tests.rs @@ -641,7 +641,7 @@ fn a_second_placements_body_copies_but_is_not_cut() { select(&mut app, json!({"type": "body", "name": seen})); assert!(super::copy(&mut app)); assert!(super::paste(&mut app, None), "{:?}", app.status); - let world = app.session.world_state(); + let world = app.session.world_state().unwrap(); let (there, copy) = (world.body(&seen).unwrap().mesh().bounds(), world.body("Cube (2)").expect("the copy").mesh().bounds()); assert!(there.min.dist(copy.min) < 1e-6 && there.max.dist(copy.max) < 1e-6, "{there:?} vs {copy:?}"); } diff --git a/crates/ui-egui/src/feature_edit.rs b/crates/ui-egui/src/feature_edit.rs index 93eeb3ac6..2d7ee5d71 100644 --- a/crates/ui-egui/src/feature_edit.rs +++ b/crates/ui-egui/src/feature_edit.rs @@ -49,8 +49,8 @@ impl SolveApp { original.execute("timeline.roll_to", ¶ms).map_err(|error| error.to_string())?; let mut rolled = original.scratch(); rolled.execute("timeline.roll_to", &serde_json::json!({"position": index})).map_err(|error| error.to_string())?; - original.world_state().warm_display_at(quality, || true); - rolled.world_state().warm_display_at(quality, || true); + original.world_state().map_err(|error| error.to_string())?.warm_display_at(quality, || true); + rolled.world_state().map_err(|error| error.to_string())?.warm_display_at(quality, || true); Ok((original, rolled)) }; let (tx, done) = std::sync::mpsc::channel(); diff --git a/crates/ui-egui/src/hole_placement_ui_tests.rs b/crates/ui-egui/src/hole_placement_ui_tests.rs index 500fa2947..954972419 100644 --- a/crates/ui-egui/src/hole_placement_ui_tests.rs +++ b/crates/ui-egui/src/hole_placement_ui_tests.rs @@ -880,8 +880,7 @@ fn a_face_place_snaps_to_the_points_of_shown_geometry_only() { } #[test] -fn combined_recessed_point_presets_keep_left_partial_across_units_and_legacy_defaults() { - use solidcraft_engine::doc::ThreadHandedness; +fn combined_recessed_point_presets_keep_partial_depth_across_units_and_legacy_defaults() { for recessed in [1, 2] { let mut h = personal_preset_harness(); if let Kind::Hole { diameter, kind, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind { @@ -891,14 +890,12 @@ fn combined_recessed_point_presets_keep_left_partial_across_units_and_legacy_def opts.tip_angle = "118 deg".into(); opts.tapped = true; opts.thread = "M8x1.2".into(); - opts.handedness = ThreadHandedness::Left; opts.thread_full_depth = false; opts.thread_depth = "5".into(); } save_preset(&mut h, "Combined point"); let stored = serde_json::to_value(&h.app.preferences.hole_presets).unwrap(); assert_eq!(stored[0]["angled_bottom"], true); - assert_eq!(stored[0]["thread_options"]["handedness"], "left"); assert_eq!(stored[0]["thread_options"]["depth"], "5 mm"); h.app.preferences.hole_presets = serde_json::from_value(stored.clone()).unwrap(); h.app.session.doc_mut().units = "in".into(); @@ -906,18 +903,17 @@ fn combined_recessed_point_presets_keep_left_partial_across_units_and_legacy_def if let Kind::Hole { kind, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind { *kind = 0; opts.angled = false; - opts.handedness = ThreadHandedness::Right; opts.thread_full_depth = true; } let before = h.app.session.doc.to_json(); choose_preset(&mut h, "Combined point"); assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {kind,opts,..} - if *kind==recessed && opts.angled && opts.tip_angle=="118 deg" && opts.handedness==ThreadHandedness::Left + if *kind==recessed && opts.angled && opts.tip_angle=="118 deg" && !opts.thread_full_depth && opts.thread_depth=="5 mm" && opts.thread=="M8x1.2" && opts.custom_thread.as_ref().is_none_or(|draft| draft.error.is_none()))); assert_eq!(h.app.session.doc.to_json(), before, "automatic recall only changes the form"); assert!((h.app.session.doc.eval("5 mm", solidcraft_engine::doc::expr::Kind::Length).unwrap() - 5.0).abs() < 1e-9); - // Old recessed presets omit the additive fields: flat, Right and Full remain their defaults. + // Old recessed presets omit the additive fields: flat and Full remain their defaults. choose_preset(&mut h, "Select a preset"); let mut legacy = stored.clone(); legacy[0].as_object_mut().unwrap().remove("angled_bottom"); @@ -925,7 +921,7 @@ fn combined_recessed_point_presets_keep_left_partial_across_units_and_legacy_def h.app.preferences.hole_presets = serde_json::from_value(legacy).unwrap(); choose_preset(&mut h, "Combined point"); assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {kind,opts,..} - if *kind==recessed && !opts.angled && opts.handedness==ThreadHandedness::Right && opts.thread_full_depth)); + if *kind==recessed && !opts.angled && opts.thread_full_depth)); choose_preset(&mut h, "Select a preset"); let mut future = stored; future[0]["thread_options"]["starts"] = json!(2); @@ -998,7 +994,6 @@ fn hole_presets_dirty_overwrite_keeps_name_and_all_pointed_left_partial_paramete opts.angled = true; opts.tapped = true; opts.thread = "M8".into(); - opts.handedness = solidcraft_engine::doc::ThreadHandedness::Left; opts.thread_full_depth = false; opts.thread_depth = "5 mm".into(); } @@ -1011,7 +1006,6 @@ fn hole_presets_dirty_overwrite_keeps_name_and_all_pointed_left_partial_paramete assert_eq!(saved[0]["name"], "Workshop"); assert_eq!(saved[0]["depth"], "13 mm"); assert_eq!(saved[0]["angled_bottom"], true); - assert_eq!(saved[0]["thread_options"]["handedness"], "left"); assert_eq!(saved[0]["thread_options"]["depth"], "5 mm"); assert!(!preset_dirty_save_enabled(&h)); h.step(&json!({"expect":{"hidden_handles":["dialog:hole_presets.name"],"not_shown":"* Workshop"}})).unwrap(); diff --git a/crates/ui-egui/src/hole_presets.rs b/crates/ui-egui/src/hole_presets.rs index 5cd3e1869..14013714d 100644 --- a/crates/ui-egui/src/hole_presets.rs +++ b/crates/ui-egui/src/hole_presets.rs @@ -35,7 +35,6 @@ enum Extent { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] struct ThreadOptions { - handedness: String, full_length: bool, depth: Option, #[serde(flatten)] @@ -44,7 +43,7 @@ struct ThreadOptions { impl Default for ThreadOptions { fn default() -> Self { - Self { handedness: "right".into(), full_length: true, depth: None, unknown: BTreeMap::new() } + Self { full_length: true, depth: None, unknown: BTreeMap::new() } } } @@ -106,7 +105,6 @@ impl Preset { } } if required.into_iter().any(|text| text.trim().is_empty()) - || !["right", "left"].contains(&self.thread_options.handedness.as_str()) || self.thread_options.depth.as_ref().is_some_and(|text| !valid_text(text, MAX_EXPRESSION)) || self.thread_options.unknown.len() > 8 || self.thread_options.unknown.iter().any(|(key, value)| { @@ -185,7 +183,6 @@ impl Preset { thread: opts.thread.clone(), thread_options: if opts.tapped { ThreadOptions { - handedness: if opts.handedness.is_right() { "right".into() } else { "left".into() }, full_length: opts.thread_full_depth, depth: if opts.thread_full_depth { None } else { Some(portable_length(&opts.thread_depth, true)?) }, unknown: BTreeMap::new(), @@ -264,11 +261,6 @@ impl Preset { opts.tapped = self.tapped; opts.thread.clone_from(&self.thread); opts.custom_thread = None; - opts.handedness = if self.thread_options.handedness == "left" { - solidcraft_engine::doc::ThreadHandedness::Left - } else { - solidcraft_engine::doc::ThreadHandedness::Right - }; opts.thread_full_depth = self.thread_options.full_length; opts.thread_depth = self.thread_options.depth.clone().unwrap_or_else(|| crate::dialogs::HoleOpts::default().thread_depth); // Existing placement picks stay with this dialog. To Object stores its mode only: diff --git a/crates/ui-egui/src/pattern_arrow_tests.rs b/crates/ui-egui/src/pattern_arrow_tests.rs index a6d8bc9b0..ab9dc84d3 100644 --- a/crates/ui-egui/src/pattern_arrow_tests.rs +++ b/crates/ui-egui/src/pattern_arrow_tests.rs @@ -173,7 +173,7 @@ fn a_solid_pattern_spacing_arrow_dragged_past_zero_goes_negative() { // Applied, the copies sit on the negative side, as a typed negative spacing puts them. h.step(&json!({"widget": "OK"})).unwrap(); assert!(h.app.dialog.is_none(), "{:?}", h.app.status); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); for (copy, k) in [("Body1 (2)", 1.0), ("Body1 (3)", 2.0)] { let x = st.body(copy).unwrap_or_else(|| panic!("no {copy}: {:?}", h.app.status)).mesh().bounds().center().x; assert!((x - (5.0 + k * v)).abs() < 1e-6, "{copy} centred at x = {x} for Spacing {spacing}"); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 430f20aef..8f9e70e34 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -3491,10 +3491,10 @@ mod tests { use serde_json::json; let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); let mut row = hole_preset_row("Fixture"); - row["thread_options"] = json!({"handedness":"left","full_length":false,"depth":"4 mm"}); + row["thread_options"] = json!({"full_length":false,"depth":"4 mm"}); super::set(&mut app, &json!({"hole_presets":[row]})).unwrap(); let expected = serde_json::to_value(&app.preferences.hole_presets).unwrap(); - assert_eq!(expected[0]["thread_options"]["handedness"], "left"); + assert_eq!(expected[0]["thread_options"]["depth"], "4 mm"); for page in 0..super::PAGES.len() { super::reset_preferences(&mut app.preferences, page); } diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 93cc21185..ffcd75693 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1309,58 +1309,6 @@ fn thread_size_suggestion_can_be_cleared_and_edited_in_the_dialog() { assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["designation"], "M8"); } -#[test] -fn thread_handedness_choices_create_edit_and_restore_the_saved_direction() { - use solidcraft_engine::doc::{FeatureKind, ThreadHandedness}; - let mut h = crate::scenario::Harness::new(); - h.app.run("solid.cylinder", json!({"radius":3,"height":6})).unwrap(); - h.app.session.selection = vec![thread_face(&h.app, "Body1")]; - h.step(&json!({"start":"solid.thread"})).unwrap(); - h.frames(2); - assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, crate::dialogs::Kind::Thread { handedness: ThreadHandedness::Right, .. })); - h.step(&json!({"click":{"handle":"dialog:thread.direction"}})).unwrap(); - h.step(&json!({"click":{"handle":"dialog:thread.direction:thread.left_hand"}})).unwrap(); - let command = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); - assert_eq!(command[0].1["handedness"], "left"); - h.step(&json!({"widget":"OK"})).unwrap(); - let id = h.app.session.doc.features.last().unwrap().id; - h.call("ui.editFeature", json!({"feature":id})); - h.frames(2); - assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, crate::dialogs::Kind::Thread { handedness: ThreadHandedness::Left, .. })); - h.step(&json!({"click":{"handle":"dialog:thread.direction"}})).unwrap(); - h.step(&json!({"click":{"handle":"dialog:thread.direction:thread.right_hand"}})).unwrap(); - h.step(&json!({"widget":"OK"})).unwrap(); - assert!(matches!(&h.app.session.doc.feature(id).unwrap().kind, FeatureKind::Thread { handedness: ThreadHandedness::Right, .. })); - assert_eq!(h.app.session.model.state().threads[0].handedness, ThreadHandedness::Right); -} - -#[test] -fn thread_handedness_tapped_hole_edit_retains_and_changes_direction() { - use solidcraft_engine::doc::{FeatureKind, ThreadHandedness}; - let mut h = crate::scenario::Harness::new(); - h.app.run("solid.box", json!({"length":20,"width":20,"height":10})).unwrap(); - let id = - h.app.run("solid.hole", json!({"position":[10,10,10],"thread":"M6","depth":6,"thread_depth":"3 mm","handedness":"left"})).unwrap()["feature"] - .as_u64() - .unwrap(); - h.call("ui.editFeature", json!({"feature":id})); - h.frames(2); - assert!( - matches!(&h.app.dialog.as_ref().unwrap().kind, crate::dialogs::Kind::Hole { opts, .. } if opts.handedness == ThreadHandedness::Left && !opts.thread_full_depth && opts.thread_depth == "3 mm") - ); - h.step(&json!({"click":{"handle":"dialog:thread.direction"}})).unwrap(); - h.step(&json!({"click":{"handle":"dialog:thread.direction:thread.right_hand"}})).unwrap(); - let command = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); - assert_eq!(command[0].0, "timeline.redefine"); - assert_eq!(command[0].1["command"], "solid.hole"); - assert_eq!(command[0].1["params"]["thread_depth"], "3 mm", "editing direction must retain the independent thread depth"); - h.step(&json!({"widget":"OK"})).unwrap(); - assert!(matches!(&h.app.session.doc.feature(id).unwrap().kind, FeatureKind::Hole { handedness: ThreadHandedness::Right, .. })); - let state = h.app.session.model.state(); - assert_eq!(state.threads[0].handedness, ThreadHandedness::Right); - assert!((state.threads[0].end - state.threads[0].start - 3.0).abs() < 1e-8); -} - #[test] fn modeled_thread_survives_timeline_double_click_and_ok() { for (analytic_pick, change_length) in [(false, false), (false, true), (true, false), (true, true)] { @@ -1585,19 +1533,7 @@ fn modelled_thread_preview_updates_reports_errors_and_cancels_without_changes() designation(&mut h, "M8x1.3"); wait_feature_preview(&mut h); assert_ne!(h.app.preview.key, first_key, "changing pitch updates the preview before OK"); - // An 8 mm shaft is turned down for an M6. - let m8_key = h.app.preview.key; designation(&mut h, "M6x1.3"); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); - while h.app.preview.key == m8_key && std::time::Instant::now() < deadline { - h.frames(2); - std::thread::sleep(std::time::Duration::from_millis(10)); - } - wait_feature_preview(&mut h); - assert!(h.app.preview.error.is_none(), "{:?}", h.app.preview.error); - assert_eq!(h.app.preview.replaced, ["Body1"]); - // A shaft thinner than the thread is still refused. - designation(&mut h, "M10x1.5"); for _ in 0..500 { h.frames(2); if !h.app.preview.busy && h.app.preview.error.is_some() { @@ -1607,7 +1543,7 @@ fn modelled_thread_preview_updates_reports_errors_and_cancels_without_changes() } assert!(h.app.preview.error.as_deref().is_some_and(|e| e.contains("does not fit")), "{:?}", h.app.preview.error); designation(&mut h, "M8x1.3"); - // The M10 error stays until the new preview starts; wait for it to go, or + // The M6 error stays until the new preview starts; wait for it to go, or // `wait_feature_preview` would stop at the stale error on a host that schedules the // preview a few frames later. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); diff --git a/crates/ui-egui/src/round_pick_tests.rs b/crates/ui-egui/src/round_pick_tests.rs index 7a5552763..00bb3efac 100644 --- a/crates/ui-egui/src/round_pick_tests.rs +++ b/crates/ui-egui/src/round_pick_tests.rs @@ -27,7 +27,7 @@ fn shaft() -> Harness { /// The shaft's wall, top rim and top cap, as picks. fn picks(h: &Harness) -> (Sel, Sel, Sel) { use solidcraft_engine::kernel::{FaceSurface, face_surface}; - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let b = st.body("Shaft").unwrap(); let face = |want: fn(&FaceSurface) -> bool, point: Vec3| { let index = (0..b.body.face_count()).find(|i| face_surface(&b.body, *i).is_some_and(|f| want(&f))).unwrap(); diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs index 3d1c1075f..96c5a45cf 100644 --- a/crates/ui-egui/src/scale_tests.rs +++ b/crates/ui-egui/src/scale_tests.rs @@ -80,9 +80,9 @@ fn appearance_and_selection_rebuild_cost() { let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); for n in [200usize, 1000, 5000] { let mut h = grid(n); - h.app.session.world_state().warm_meshes(|| true); + h.app.session.world_state().unwrap().warm_meshes(|| true); h.frames(2); - let body = h.app.session.world_state().bodies[0].name.clone(); + let body = h.app.session.world_state().unwrap().bodies[0].name.clone(); let cold = ms(|| drop(crate::viewport::build_scene(&h.app))); let again = ms(|| drop(crate::viewport::build_scene(&h.app))); let proj = crate::viewport::projection(&h.app, rect); @@ -123,11 +123,11 @@ fn large_body_scene_rebuild_cost() { .run("solid.torus", json!({"major": 100, "minor": 10, "center": [k as f64 * 220.0, 0.0, 0.0], "body_name": format!("T{k}")})) .unwrap(); } - h.app.session.world_state().warm_meshes(|| true); + h.app.session.world_state().unwrap().warm_meshes(|| true); h.frames(2); - let bodies = h.app.session.world_state().bodies.len(); - let triangles: usize = h.app.session.world_state().bodies.iter().map(|b| b.mesh().triangles.len()).sum(); - let body = h.app.session.world_state().bodies[0].name.clone(); + let bodies = h.app.session.world_state().unwrap().bodies.len(); + let triangles: usize = h.app.session.world_state().unwrap().bodies.iter().map(|b| b.mesh().triangles.len()).sum(); + let body = h.app.session.world_state().unwrap().bodies[0].name.clone(); let cold = ms(|| drop(crate::viewport::build_scene(&h.app))); h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699"})).unwrap(); let colour = ms(|| drop(crate::viewport::build_scene(&h.app))); @@ -164,7 +164,7 @@ fn assembly(unique: usize, placed: usize) -> Harness { json!({"components": ["Wheel"], "dir1": [1, 0, 0], "count1": p1, "spacing1": 100, "dir2": [0, 1, 0], "count2": p2, "spacing2": 100}), ) .unwrap(); - h.app.session.world_state().warm_meshes(|| true); + h.app.session.world_state().unwrap().warm_meshes(|| true); h.frames(3); h } @@ -178,7 +178,7 @@ fn assembly_scene_rebuild_cost() { let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); for (unique, placed) in [(100, 100), (300, 500)] { let mut h = assembly(unique, placed); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let bodies = st.bodies.len(); let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum(); let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap(); @@ -224,7 +224,7 @@ fn assembly_tree_hover_highlight_cost() { for (unique, placed) in [(100, 100), (300, 500)] { let mut h = assembly(unique, placed); let _ = crate::viewport::build_scene(&h.app); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap(); let wheels: Vec = st.bodies.iter().filter(|b| b.component != 0).map(|b| b.name.clone()).collect(); let everything: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); @@ -297,7 +297,7 @@ pub(crate) fn view_frame( /// component, the whole design), each hover change building, uploading and drawing the highlight. #[cfg(not(target_arch = "wasm32"))] fn hover_rows(h: &mut Harness, frames: &mut crate::gpu::OffscreenFrames, size: u32, model_key: u64, label: &str) -> String { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap(); let wheels: Vec = st.bodies.iter().filter(|b| b.component != 0).map(|b| b.name.clone()).collect(); let everything: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); @@ -362,7 +362,7 @@ fn assembly_tree_hover_frame_cost() { h.app.run("component.activate", json!({"component": "Wheel"})).unwrap(); println!("{}", hover_rows(&mut h, &mut frames, SIZE, base + 1_000_000, &format!("{label} mode=component_active"))); h.app.run("component.activate", json!({"component": 0})).unwrap(); - let parts: Vec = h.app.session.world_state().bodies.iter().filter(|b| b.component == 0).map(|b| b.name.clone()).collect(); + let parts: Vec = h.app.session.world_state().unwrap().bodies.iter().filter(|b| b.component == 0).map(|b| b.name.clone()).collect(); h.app.run("appearance.assign", json!({"bodies": parts, "color": "#88aacc", "opacity": 0.5})).unwrap(); println!("{}", hover_rows(&mut h, &mut frames, SIZE, base + 2_000_000, &format!("{label} mode=glass_parts"))); } @@ -448,11 +448,11 @@ fn step_file_cost() { }; let import = ms(|| drop(h.app.run("file.insert_step", json!({"path": path.to_string_lossy()})).unwrap())); phase(&mut line, "import", import); - let world = ms(|| drop(h.app.session.world_state())); + let world = ms(|| drop(h.app.session.world_state().unwrap())); phase(&mut line, "world", world); - let mesh = ms(|| h.app.session.world_state().warm_meshes(|| true)); + let mesh = ms(|| h.app.session.world_state().unwrap().warm_meshes(|| true)); phase(&mut line, "mesh", mesh); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let bodies: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum(); let components = h.app.session.doc.components.len(); diff --git a/crates/ui-egui/src/sketch3d_frame_ui_tests.rs b/crates/ui-egui/src/sketch3d_frame_ui_tests.rs index 511eb9b15..9d2bb7463 100644 --- a/crates/ui-egui/src/sketch3d_frame_ui_tests.rs +++ b/crates/ui-egui/src/sketch3d_frame_ui_tests.rs @@ -217,7 +217,7 @@ fn arc_tool_draws_an_exact_3d_arc_off_the_plane() { h.step(&json!({"click": {"world": p}})).unwrap(); } h.step(&json!({"key": "Escape"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let wires = &state.sketch(sketch).unwrap().sketch.wires; assert_eq!(wires.len(), 1, "three off-plane clicks draw one 3D arc"); let w = &wires[0]; @@ -245,7 +245,7 @@ fn arc3d_button_starts_its_own_tool() { for p in [[10.0, 0.0, 10.0], [10.0, 10.0, 10.0], [20.0, 10.0, 10.0]] { h.step(&json!({"click": {"world": p}})).unwrap(); } - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let wires = &state.sketch(sketch).unwrap().sketch.wires; assert_eq!(wires.len(), 1, "three clicks draw one exact 3D arc"); let arc = wires[0].arc.expect("the drawn arc is stored exactly"); diff --git a/crates/ui-egui/src/sketch_centre_align_ui_tests.rs b/crates/ui-egui/src/sketch_centre_align_ui_tests.rs index 7ec95215f..9a4e84017 100644 --- a/crates/ui-egui/src/sketch_centre_align_ui_tests.rs +++ b/crates/ui-egui/src/sketch_centre_align_ui_tests.rs @@ -30,7 +30,7 @@ fn point(h: &Harness, id: &str) -> Vec2 { #[test] fn selecting_the_centre_and_an_edge_preselects_the_alignment() { let h = square_with_circle(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let edge = || SketchCurve { id: "l2".into(), sketch: None }; let centre = || SketchPoint { id: "c1.center".into() }; diff --git a/crates/ui-egui/src/sketch_dims_tests.rs b/crates/ui-egui/src/sketch_dims_tests.rs index 3a4572249..06fe19923 100644 --- a/crates/ui-egui/src/sketch_dims_tests.rs +++ b/crates/ui-egui/src/sketch_dims_tests.rs @@ -397,7 +397,7 @@ fn a_midpoint_line_takes_a_typed_length_and_angle() { tab(&mut h, false); type_value(&mut h, "45 deg"); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert_eq!(sk.curves.len(), 1, "{:?}", h.app.status); assert!( diff --git a/crates/ui-egui/src/sketch_transform_ui.rs b/crates/ui-egui/src/sketch_transform_ui.rs index f8f57ba92..e7af6b7b9 100644 --- a/crates/ui-egui/src/sketch_transform_ui.rs +++ b/crates/ui-egui/src/sketch_transform_ui.rs @@ -76,7 +76,7 @@ fn pointer_on_sketch(plane: &Plane, proj: &Proj, at: Pos2) -> Option { /// The picked curves (as polylines on the sketch) and the box around them and the picked points: /// its middle and its size. None when nothing usable is picked or the box has no extent. fn picked_box(app: &SolveApp, d: &crate::dialogs::Dialog) -> Option<(Vec>, [f64; 2], [f64; 2])> { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let sk = &state.sketch(app.session.active_sketch?)?.sketch; let mut lines: Vec> = Vec::new(); let mut points: Vec = Vec::new(); diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 478f2782b..0c47fae74 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -268,7 +268,7 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) { let params = match first { None => Some(json!({"line": id})), Some(point) => { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); app.session.active_sketch.and_then(|sid| state.sketch(sid)).and_then(|ss| point_line_alignment(&ss.sketch, &point, id)) } }; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 9a4a615a9..c4084688b 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -6175,7 +6175,7 @@ mod tests { let built: usize = planned.blocks.iter().map(|b| b.bytes.vertices.len()).sum(); assert_eq!(built, 0, "and none is built on the CPU"); // Hovered, a faded body drawn from its plan lights through the plan's triangles. - let faded = app.session.world_state().bodies.iter().find(|b| b.name.starts_with("Faded")).map(|b| b.name.clone()).unwrap(); + let faded = app.session.world_state().unwrap().bodies.iter().find(|b| b.name.starts_with("Faded")).map(|b| b.name.clone()).unwrap(); app.viewport.hover_bodies = vec![faded]; assert_eq!(build_highlight(&app).hover_planned.len(), 1, "the faded body's plan is lit"); app.viewport.hover_bodies.clear(); @@ -6317,7 +6317,7 @@ mod tests { app.fit_view(); const SIZE: u32 = 128; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); - let body = app.session.world_state().bodies[0].clone(); + let body = app.session.world_state().unwrap().bodies[0].clone(); let proj = projection(&app, rect); let e = proj.cam.eye().to_f32(); let eye = [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]; @@ -8350,7 +8350,7 @@ mod tests { } fn app_body(app: &SolveApp, name: &str) -> solidcraft_engine::doc::ModelBody { - app.session.world_state().body(name).cloned().unwrap() + app.session.world_state().unwrap().body(name).cloned().unwrap() } #[test] diff --git a/crates/ui-egui/src/viewport_appearance_tests.rs b/crates/ui-egui/src/viewport_appearance_tests.rs index bee2f4723..d7842aaeb 100644 --- a/crates/ui-egui/src/viewport_appearance_tests.rs +++ b/crates/ui-egui/src/viewport_appearance_tests.rs @@ -161,7 +161,7 @@ fn selection_does_not_rebuild_the_model_scene() { let highlight = h.app.viewport.hl_key; // Clear the scene the first frame uploaded; an untouched model must not upload another. let _ = h.app.viewport.slot.lock().unwrap().take(); - let name = h.app.session.world_state().bodies[0].name.clone(); + let name = h.app.session.world_state().unwrap().bodies[0].name.clone(); h.app.session.selection = vec![solidcraft_engine::Sel::Body { name }]; h.frame(); assert_eq!(h.app.viewport.key, key, "a selection does not change the model scene key"); @@ -190,7 +190,7 @@ fn a_colour_edit_reuses_every_block_vertex() { app.ui.ground_shadow = false; app.set_origin_shown(false); app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); - let name = app.session.world_state().bodies[0].name.clone(); + let name = app.session.world_state().unwrap().bodies[0].name.clone(); let first = build_scene(&app); let block = first.blocks.iter().find(|b| !b.bytes.vertices.is_empty()).expect("the box has a block"); let (key, vertices) = (block.key, block.bytes.vertices.clone()); @@ -207,7 +207,7 @@ fn an_opacity_class_change_keeps_vertices_and_rewrites_only_the_runs() { app.ui.ground_shadow = false; app.set_origin_shown(false); app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); - let name = app.session.world_state().bodies[0].name.clone(); + let name = app.session.world_state().unwrap().bodies[0].name.clone(); let first = build_scene(&app); let block = first.blocks.iter().find(|b| !b.bytes.vertices.is_empty()).expect("the box has a block"); let (key, bytes) = (block.key, block.bytes.clone()); @@ -243,7 +243,7 @@ fn appearance_edits_upload_palette_rows_only() { Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); app.fit_view(); - let name = app.session.world_state().bodies[0].name.clone(); + let name = app.session.world_state().unwrap().bodies[0].name.clone(); let highlight: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None)); let mut key = 0; let mut draw = |app: &SolveApp| { diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index adecfcd96..6a63551e6 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -138,13 +138,9 @@ The Hole dialog draws a section through the hole as its options make it (type, e point, tapped) and puts each size in a field beside the dimension it sets; hovering a field, or typing in it, lights its dimension. -Tapped holes and **Thread** features have a **Thread direction** choice: **Right-hand** -(the default) or **Left-hand**. Editing and reopening keep the chosen direction. Tapped -holes carry a cosmetic thread; the separate Thread feature can also cut a **Modeled** -left-hand helix. Cosmetic direction is recorded with the thread annotation and does not -change the body. Scripts use `handedness: "left"` or `"right"` on `solid.hole` (with `thread`) -and `solid.thread`. Existing designs and omitted values remain right-handed. Changing the -direction keeps the pitch, thread length and axis; it does not change a hole's drill size. +The **Thread** feature's **Hand** is **Right** (the default), **Left**, or **Both** (a right- and +a left-handed groove crossing, as on a reversing screw). Scripts use `hand: "left"` (or `"right"`, +`"both"`) on `solid.thread`; omitted, a thread is right-handed. Tapped holes are right-handed. Fillets and chamfers handle straight edges between planar faces, whole smooth loops, runs of neighbouring edges with mitred or spherical corners, and closed chains of curved edges (a rolling