* claim: #11483 * Interference: intersect and mesh each overlap on a kernel worker (#11483) Compute in Inspect > Interference intersected each overlapping pair and meshed the shared volume on the window thread. Its stack is 1 MiB on Windows, too small for the kernel's recursion, so the app could close without a crash message. Each pair now runs through kernel::map_with_local_pools, on a worker with the kernel's 8 MiB stack, as inspect.interference and inspect.clearance already do. * Interference: Compute checks off the window thread (#11483) On 0.30.0 the report's two parts took the window thread 95 s (x64) to 154 s (x86) in the overlap boolean, and the window stopped responding until the app was closed. Compute now runs inspect.clearance and the shared volumes on a copy of the session, on a kernel thread, when the app runs commands off the window thread (as Find Limits does). The dialog shows the elapsed seconds with Cancel meanwhile, and drops the reply of a design changed since. * Interference: Cancel on its own row while Compute checks (#11483) --------- Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com>
This commit is contained in:
@@ -126,11 +126,23 @@ pub enum Asm {
|
||||
of: Vec<Sel>,
|
||||
/// Pairs closer than this (mm, as typed) are listed too.
|
||||
clearance: String,
|
||||
/// Compute's check under way (its reply lands here).
|
||||
check: Option<Check>,
|
||||
},
|
||||
/// Motion Trace: a picked point's path, previewed; OK keeps it as a 3D sketch spline.
|
||||
Trace(Box<TraceForm>),
|
||||
}
|
||||
|
||||
/// Interference's check off the window thread: where it leaves its reply (the check's and the
|
||||
/// shared volumes' meshes), the design and the picks it checked, and when it started.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Check {
|
||||
reply: std::sync::Arc<std::sync::Mutex<Option<(Value, Vec<Mesh>)>>>,
|
||||
design: std::sync::Weak<solidcraft_engine::doc::Document>,
|
||||
of: Vec<Sel>,
|
||||
started: f64,
|
||||
}
|
||||
|
||||
/// The snap under the cursor, remembered for the selection it was found for.
|
||||
pub type Hover = Option<(Sel, Option<SnapPt>)>;
|
||||
|
||||
@@ -288,7 +300,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
|
||||
"joint.gear" | "joint.rack_pinion" | "joint.screw" => crate::dialogs_coupling::start(app, id)?,
|
||||
"joint.cam" => crate::dialogs_coupling::cam::start(app),
|
||||
"inspect.interference" => (
|
||||
Asm::Interference { result: None, overlaps: Vec::new(), of: Vec::new(), clearance: "0".into() },
|
||||
Asm::Interference { result: None, overlaps: Vec::new(), of: Vec::new(), clearance: "0".into(), check: None },
|
||||
vec![SelInput::new("Bodies (all if none)", BODIES, true)],
|
||||
),
|
||||
_ => return None,
|
||||
@@ -957,10 +969,45 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
|
||||
}
|
||||
Asm::Coupling(f) => enter |= crate::dialogs_coupling::rows(app, ui, f, inputs),
|
||||
Asm::Cam(f) => enter |= crate::dialogs_coupling::cam::rows(app, ui, f, inputs),
|
||||
Asm::Interference { result, overlaps, of, clearance } => {
|
||||
Asm::Interference { result, overlaps, of, clearance, check } => {
|
||||
let picked: Vec<Sel> = inputs.first().map(|i| i.items.clone()).unwrap_or_default();
|
||||
if let Some(c) = check.take() {
|
||||
match c.reply.lock().map(|mut r| r.take()).map_err(|_| ()) {
|
||||
Ok(None) => {
|
||||
*check = Some(c);
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
// Done: shown unless the design changed meanwhile (a script, the control
|
||||
// channel, undo). A poisoned lock (its thread panicked) leaves nothing.
|
||||
Ok(Some((r, o))) => {
|
||||
if c.design.upgrade().is_some_and(|d| std::sync::Arc::ptr_eq(&d, &app.session.doc)) {
|
||||
(*result, *overlaps, *of) = (Some(r), o, c.of);
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
Err(()) => {}
|
||||
}
|
||||
}
|
||||
enter |= expr_row(ui, "Clearance", clearance);
|
||||
// While it checks: the seconds so far, and Cancel where Compute was.
|
||||
if let Some(started) = check.as_ref().map(|c| c.started) {
|
||||
let t = Tokens::get();
|
||||
form_row(ui, "", |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let seconds = ((crate::now_ms() - started) / 1000.0).floor().max(0.0);
|
||||
ui.add(egui::Spinner::new().size(t.font_small));
|
||||
ui.label(RichText::new(crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))])).color(t.text_dim));
|
||||
});
|
||||
});
|
||||
}
|
||||
form_row(ui, "", |ui| {
|
||||
if check.is_some() {
|
||||
if crate::ui_kit::button(ui, crate::i18n::tr("ui.cancel"), crate::ui_kit::Button::Normal).clicked() {
|
||||
// Its thread finishes the check; the reply is left unread.
|
||||
*check = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let stale = result.is_some() && *of != picked;
|
||||
if crate::ui_kit::button(
|
||||
ui,
|
||||
@@ -969,13 +1016,14 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
let (r, o) = interference(app, &picked, clearance);
|
||||
*result = Some(r);
|
||||
*overlaps = o;
|
||||
*of = picked;
|
||||
(*result, *overlaps) = (None, Vec::new());
|
||||
*check = Some(interference(app, &picked, clearance));
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
});
|
||||
if let Some(r) = result.as_ref() {
|
||||
if check.is_none()
|
||||
&& let Some(r) = result.as_ref()
|
||||
{
|
||||
interference_rows(app, ui, r);
|
||||
}
|
||||
}
|
||||
@@ -1175,34 +1223,73 @@ fn fill_limits(doc: &solidcraft_engine::doc::Document, f: &mut JointForm, reply:
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the check (overlaps, pairs closer than the clearance, each body's nearest neighbour) and
|
||||
/// find the overlapping volumes (world placement) to show in red.
|
||||
fn interference(app: &mut SolveApp, picked: &[Sel], clearance: &str) -> (Value, Vec<Mesh>) {
|
||||
/// Start Compute's check (overlaps, pairs closer than the clearance, each body's nearest
|
||||
/// neighbour) and find the overlapping volumes (world placement) to show in red. Off the window
|
||||
/// thread, on a kernel thread, when the app runs commands there: a slow pair froze the window
|
||||
/// until the app was closed (#11483). Else at once.
|
||||
fn interference(app: &SolveApp, picked: &[Sel], clearance: &str) -> Check {
|
||||
let check =
|
||||
Check { reply: Default::default(), design: std::sync::Arc::downgrade(&app.session.doc), of: picked.to_vec(), started: crate::now_ms() };
|
||||
let names: Vec<String> = picked.body_names();
|
||||
let (scale, _) = crate::prefs::unit_scale(&app.session.doc.units);
|
||||
let clearance = match crate::prefs::parse_length_mm(clearance, scale) {
|
||||
Some(v) if v >= 0.0 => v,
|
||||
_ => return (json!({ "error": crate::i18n::tr("dialog.clearance_invalid") }), Vec::new()),
|
||||
};
|
||||
let mut p = json!({ "clearance": clearance, "nearest": 1 });
|
||||
if !names.is_empty() {
|
||||
p["bodies"] = json!(names);
|
||||
}
|
||||
let r = match app.run("inspect.clearance", p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return (json!({ "error": e }), Vec::new()),
|
||||
};
|
||||
let st = crate::open_meshing::session_world(&app.session);
|
||||
let mut meshes = Vec::new();
|
||||
for hit in r["overlaps"].as_array().into_iter().flatten() {
|
||||
let (Some(a), Some(b)) = (hit["a"].as_str().and_then(|n| st.body(n)), hit["b"].as_str().and_then(|n| st.body(n))) else { continue };
|
||||
if let Ok(Some(o)) = solidcraft_engine::kernel::boolean(&a.body, &b.body, solidcraft_engine::kernel::BoolOp::Intersect)
|
||||
&& let Ok(m) = o.mesh(&solidcraft_engine::kernel::MeshTolerance::chord((o.size() * 2e-3).max(1e-3)))
|
||||
{
|
||||
meshes.push(m);
|
||||
let reply = match crate::prefs::parse_length_mm(clearance, scale) {
|
||||
Some(v) if v >= 0.0 => {
|
||||
let mut p = json!({ "clearance": v, "nearest": 1 });
|
||||
if !names.is_empty() {
|
||||
p["bodies"] = json!(names);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if app.apply_off_thread.is_some() {
|
||||
let (ahead, world, out, params) =
|
||||
(app.session.ahead(), crate::open_meshing::session_world(&app.session), check.reply.clone(), p.clone());
|
||||
let spawned = solidcraft_engine::kernel::kernel_thread("interference").spawn(move || {
|
||||
let r = check_now(ahead, &world, params);
|
||||
if let Ok(mut slot) = out.lock() {
|
||||
*slot = Some(r);
|
||||
}
|
||||
});
|
||||
if spawned.is_ok() {
|
||||
return check;
|
||||
}
|
||||
}
|
||||
check_now(app.session.ahead(), &crate::open_meshing::session_world(&app.session), p)
|
||||
}
|
||||
_ => (json!({ "error": crate::i18n::tr("dialog.clearance_invalid") }), Vec::new()),
|
||||
};
|
||||
if let Ok(mut slot) = check.reply.lock() {
|
||||
*slot = Some(reply);
|
||||
}
|
||||
(r, meshes)
|
||||
check
|
||||
}
|
||||
|
||||
/// `inspect.clearance` with `p` on a copy of the session, and the volume each pair it finds
|
||||
/// overlapping shares ([`overlap_meshes`]).
|
||||
fn check_now(ahead: solidcraft_engine::Ahead, world: &solidcraft_engine::doc::ModelState, p: Value) -> (Value, Vec<Mesh>) {
|
||||
// One reply for the one command.
|
||||
match ahead.replies(&[("inspect.clearance".to_string(), p)]).pop() {
|
||||
Some(Ok(r)) => {
|
||||
let meshes = overlap_meshes(world, &r);
|
||||
(r, meshes)
|
||||
}
|
||||
Some(Err(e)) => (json!({ "error": e.to_string() }), Vec::new()),
|
||||
None => (json!({}), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The volume each pair in an `inspect.clearance` reply's `overlaps` shares, meshed in world
|
||||
/// placement. Each pair runs on a kernel worker with the kernel's stack, whatever thread asks
|
||||
/// (the window thread's is 1 MiB on Windows).
|
||||
fn overlap_meshes(st: &solidcraft_engine::doc::ModelState, r: &Value) -> Vec<Mesh> {
|
||||
use solidcraft_engine::kernel;
|
||||
let pairs: Vec<_> =
|
||||
r["overlaps"].as_array().into_iter().flatten().filter_map(|hit| Some((st.body(hit["a"].as_str()?)?, st.body(hit["b"].as_str()?)?))).collect();
|
||||
kernel::map_with_local_pools(&pairs, usize::MAX, |&(a, b)| {
|
||||
let Some(o) = kernel::boolean(&a.body, &b.body, kernel::BoolOp::Intersect)? else { return Ok(None) };
|
||||
o.mesh(&kernel::MeshTolerance::chord((o.size() * 2e-3).max(1e-3))).map(Some)
|
||||
})
|
||||
.into_iter()
|
||||
.filter_map(|m| m.ok().flatten())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn interference_rows(app: &SolveApp, ui: &mut egui::Ui, r: &Value) {
|
||||
|
||||
@@ -1337,3 +1337,66 @@ fn find_limits_searches_the_joint_as_edited_and_leaves_a_free_side() {
|
||||
find_limits(&app, f, id, &d.inputs);
|
||||
assert!(f.found_note.is_some() && f.found.is_empty(), "{:?}", f.found_note);
|
||||
}
|
||||
|
||||
/// Compute in Interference intersects and meshes each overlap on the kernel's workers. On the
|
||||
/// window thread (a 1 MiB stack on Windows) the kernel ran out of stack and the app closed
|
||||
/// (#11483); here the dialog's own thread has 64 KiB.
|
||||
#[test]
|
||||
fn interference_meshes_each_overlap_on_the_kernels_stack() {
|
||||
let mut s = Session::default();
|
||||
crate::test_support::grounded_boxes(&[("A", 0), ("B", 10)], |id, p| s.execute(id, &p).unwrap());
|
||||
let r = s.execute("inspect.clearance", &json!({"clearance": 0, "nearest": 1})).unwrap();
|
||||
assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let st = s.world_state().unwrap();
|
||||
let meshes = std::thread::Builder::new().stack_size(64 << 10).spawn(move || overlap_meshes(&st, &r)).unwrap().join().unwrap();
|
||||
// A's 0..20 and B's 10..30 along X share 10..20.
|
||||
let b = meshes.first().map(Mesh::bounds).expect("the shared volume");
|
||||
assert_eq!(meshes.len(), 1);
|
||||
let near = |p: Vec3, q: [f64; 3]| (p.x - q[0]).abs() < 1e-6 && (p.y - q[1]).abs() < 1e-6 && (p.z - q[2]).abs() < 1e-6;
|
||||
assert!(near(b.min, [10.0, 0.0, 0.0]) && near(b.max, [20.0, 20.0, 10.0]), "{b:?}");
|
||||
}
|
||||
|
||||
/// With the app running commands off the window thread, Compute in Interference checks on a
|
||||
/// thread of its own (a slow pair froze the window until the app was closed, #11483): the
|
||||
/// overlap and its shared volume arrive in a later frame, and a check of a design changed
|
||||
/// meanwhile is dropped.
|
||||
#[test]
|
||||
fn interference_checks_off_the_window_thread_and_drops_a_check_of_a_changed_design() {
|
||||
let mut s = Session::default();
|
||||
crate::test_support::grounded_boxes(&[("A", 0), ("B", 10)], |id, p| s.execute(id, &p).unwrap());
|
||||
let mut app = SolveApp::new(s, Services::default());
|
||||
app.apply_off_thread = Some(std::time::Duration::ZERO);
|
||||
app.start("inspect.interference");
|
||||
let ctx = crate::fonts::test_context();
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0));
|
||||
let state = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) {
|
||||
Some(Kind::Assembly(Asm::Interference { result, overlaps, check, .. })) => (result.clone(), overlaps.len(), check.is_some()),
|
||||
_ => panic!("the dialog stays open"),
|
||||
};
|
||||
// Compute as its button starts it, then frames until its reply is read.
|
||||
let compute = |app: &mut SolveApp, change: bool| {
|
||||
let c = interference(app, &[], "0");
|
||||
if let Some(Kind::Assembly(Asm::Interference { result, overlaps, check, .. })) = app.dialog.as_mut().map(|d| &mut d.kind) {
|
||||
(*result, *overlaps, *check) = (None, Vec::new(), Some(c));
|
||||
}
|
||||
if change {
|
||||
app.run("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [100, 0, 0]})).unwrap();
|
||||
}
|
||||
for _ in 0..3000 {
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| crate::dialogs::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
if !state(app).2 {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
panic!("the check never came back");
|
||||
};
|
||||
compute(&mut app, false);
|
||||
let (result, overlaps, _) = state(&app);
|
||||
let result = result.expect("the check's reply");
|
||||
assert_eq!(result["overlaps"].as_array().map(Vec::len), Some(1), "{result}");
|
||||
assert_eq!(overlaps, 1, "the shared volume, drawn in red");
|
||||
compute(&mut app, true);
|
||||
assert_eq!(state(&app), (None, 0, false), "a check of the design before the change is dropped");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user