Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions assets/locales/pending/auto-join-new-cut.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"en": {
"dialog.no_shown_body": "No shown body to change: show one, or choose New Body",
"prefs.auto_operation": "Choose the operation automatically",
"prefs.auto_operation_note": "Feature windows pick Join, New Body or Cut from what the new material touches, until you pick one. Off: they keep the operation they open with."
},
"ar": {
"dialog.no_shown_body": "لا يوجد جسم ظاهر لتغييره: أظهر جسمًا، أو اختر «جسم جديد»",
"prefs.auto_operation": "اختيار العملية تلقائيًا",
"prefs.auto_operation_note": "تختار نوافذ الميزات «ضم» أو «جسم جديد» أو «قص» بحسب ما تلامسه المادة الجديدة، إلى أن تختار عملية بنفسك. عند الإيقاف: تحتفظ بالعملية التي تُفتح بها."
},
"he": {
"dialog.no_shown_body": "אין גוף מוצג לשינוי: הציגו גוף, או בחרו „גוף חדש”",
"prefs.auto_operation": "בחירת הפעולה באופן אוטומטי",
"prefs.auto_operation_note": "חלונות הפיצ'רים בוחרים „איחוד”, „גוף חדש” או „הסרה” לפי מה שהחומר החדש נוגע בו, עד שתבחרו פעולה בעצמכם. כבוי: הם שומרים על הפעולה שאיתה נפתחו."
},
"ja": {
"dialog.no_shown_body": "変更できる表示中のボディがありません。ボディを表示するか、新規ボディを選択してください",
"prefs.auto_operation": "操作を自動で選択",
"prefs.auto_operation_note": "フィーチャーのウィンドウは、新しい形状が何に接するかから結合・新規ボディ・切り取りを選びます(手動で選ぶまで)。オフ:開いたときの操作のままです。"
},
"tr": {
"dialog.no_shown_body": "Değiştirilecek görünür gövde yok: bir gövdeyi gösterin ya da Yeni gövde seçin",
"prefs.auto_operation": "İşlemi otomatik seç",
"prefs.auto_operation_note": "Özellik pencereleri, yeni malzemenin neye değdiğine göre Birleştir, Yeni gövde ya da Kes işlemini seçer; siz bir işlem seçene kadar. Kapalıyken açıldıkları işlemi korurlar."
},
"vi": {
"dialog.no_shown_body": "Không có thân khối đang hiển thị để thay đổi: hãy hiển thị một thân khối, hoặc chọn “Tạo mới Thân khối”",
"prefs.auto_operation": "Tự động chọn thao tác",
"prefs.auto_operation_note": "Cửa sổ tính năng chọn “Nối liền”, “Tạo mới Thân khối” hoặc “Cắt” theo những gì vật liệu mới chạm vào, cho đến khi bạn tự chọn. Tắt: cửa sổ giữ nguyên thao tác lúc mở."
},
"zh": {
"dialog.no_shown_body": "没有可更改的显示实体:请显示一个实体,或选择新建实体",
"prefs.auto_operation": "自动选择操作",
"prefs.auto_operation_note": "特征窗口根据新材料接触的对象选择连接、新建实体或剪切,直到您手动选择。关闭:保持窗口打开时的操作。"
}
}
26 changes: 15 additions & 11 deletions crates/doc/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2721,10 +2721,22 @@ fn note_join_apart(before: &ModelState, after: &ModelState, f: &Feature, warning
if operation != Operation::Join {
return;
}
for (name, n) in join_pieces_added(before, after) {
append_warning(
warning,
format!("the joined piece doesn't touch `{name}`, so `{name}` is now in {n} separate pieces (New Body makes it a body of its own)"),
);
}
}

/// The bodies a Join from `before` to `after` left in more separate pieces than it found, with
/// their piece counts now: empty when the joined material made one body with what it touched
/// (or bridged pieces). A lid closing a cavity adds a void, not a piece.
pub fn join_pieces_added(before: &ModelState, after: &ModelState) -> Vec<(String, usize)> {
let pieces = |b: &Body| b.lumps().map_or(1, |l| l.len());
// Pieces of the bodies the join changed or absorbed before it, and of those it kept after.
let (mut had, mut have) = (0usize, 0usize);
let mut grown: Vec<(&str, usize)> = Vec::new();
let mut grown: Vec<(String, usize)> = Vec::new();
for was in &before.bodies {
match after.body(&was.name) {
Some(now) if now.body.same_shape(&was.body) => {}
Expand All @@ -2733,21 +2745,13 @@ fn note_join_apart(before: &ModelState, after: &ModelState, f: &Feature, warning
had += old;
have += new;
if new > old {
grown.push((now.name.as_str(), new));
grown.push((now.name.clone(), new));
}
}
None => had += pieces(&was.body),
}
}
if have <= had {
return;
}
for (name, n) in grown {
append_warning(
warning,
format!("the joined piece doesn't touch `{name}`, so `{name}` is now in {n} separate pieces (New Body makes it a body of its own)"),
);
}
if have <= had { Vec::new() } else { grown }
}

/// Add tool bodies to the model according to the operation.
Expand Down
8 changes: 4 additions & 4 deletions crates/doc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ pub use assembly::{
pub use document::*;
pub use eval::{
EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error,
edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, map_wire, metric_thread_sizes,
object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction,
sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance, world_state,
world_state_reusing,
edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, join_pieces_added, map_wire,
metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles,
sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance,
world_state, world_state_reusing,
};
pub use eval::{EvalCache, KeptResults};
pub use expr::Expr;
Expand Down
27 changes: 15 additions & 12 deletions crates/engine/src/cmd/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -880,7 +880,8 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
p.to_mut()["participants"] = json!(parts);
}
if matches!(operation, Operation::Cut | Operation::Intersect) && targets.is_empty() && string_list(cmd, &p, "participants")?.is_empty() {
targets = shown_scope(s);
// With every body hidden, every body, as before.
targets = shown_scope(s).unwrap_or_default();
}
let kind = FeatureKind::Extrude {
sketch: SketchId(sketch),
Expand Down Expand Up @@ -1026,17 +1027,6 @@ fn face_body_reached(s: &Session, sketch: u64) -> Result<Option<String>> {
Ok(Some(body.name.clone()))
}

/// A cut or intersect that names no bodies leaves hidden bodies alone, as hiding a body to keep
/// it out of a cut is the usual way to (#3961): while some of the active component's bodies
/// are hidden, its shown ones, stored as the feature's targets so showing the others again
/// later changes nothing. Empty (every body, as before) when none is hidden, or all are.
fn shown_scope(s: &Session) -> Vec<String> {
let st = s.model.state();
let scope = active_scope(s, &st);
let shown: Vec<String> = scope.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect();
if shown.len() == scope.len() { Vec::new() } else { shown }
}

/// The body whose face `sketch` is attached to (on the face itself, not offset from it), when
/// it is one the active component works on ([`active_scope`]).
fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {
Expand Down Expand Up @@ -1064,6 +1054,19 @@ fn face_join_targets(s: &Session, p: &Value, operation: Operation, sketches: &[u
Ok(targets.into_iter().map(BodyName).collect())
}

/// The bodies a Join, Cut or Intersect that names none may change, less the hidden ones, when
/// some of them are hidden: stored as the feature's `targets`, so a hidden body is left alone
/// (#3961, #6901) and showing it again later doesn't change the model. None when every one is
/// shown; empty when none is.
pub fn shown_scope(s: &Session) -> Option<Vec<String>> {
let st = s.model.state();
let scope = active_scope(s, &st);
if scope.iter().all(|b| s.body_visible(&b.name)) {
return None;
}
Some(scope.into_iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect())
}

/// The bodies a feature of the active component works on when it names none: the component's
/// own. A component with no body of its own (the root of an opened STEP assembly, whose parts
/// are components inside it) works on the bodies of the components inside it whose geometry is
Expand Down
125 changes: 125 additions & 0 deletions crates/engine/src/cmd/join_pieces.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//! What a feature's material does when it is joined: the test the feature windows use to choose
//! Join, New Body or Cut by themselves (#6901). It runs the Join itself, so it agrees with the
//! result OK makes, and with the warning a Join apart gets (#4434).

use serde_json::Value;

use crate::Session;

/// The most commands a feature window previews at once.
const MAX_COMMANDS: usize = 64;

/// What a feature's material makes, joined to the bodies it may join.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Addition {
/// It would be a separate piece (or there is no body to join): a New Body.
Apart,
/// It makes one body with what it touches: a Join.
Joins,
/// It adds no material: it lies inside a body (a Cut, where the window offers one).
Inside,
}

/// What `cmds` (a feature window's commands, with operation New Body or Join) make when run with
/// Join (see [`crate::Ahead::addition`]).
pub fn addition(s: &Session, cmds: &[(String, Value)], inside: bool) -> Option<Addition> {
s.ahead().addition(cmds, inside).0
}

impl crate::Ahead {
/// What `cmds` (a feature window's commands, with operation New Body or Join) make when run
/// with Join, and, when they join, the Join evaluated (OK takes it rather than computing it
/// again, [`crate::Session::prime`]). `inside`: tell material lying inside a body
/// ([`Addition::Inside`]) from material that joins. None when they have no such operation
/// (Combine, a Cut chosen by hand, a feature without one), the model has no body, or the Join
/// fails.
///
/// Material that touches no body can't be fused to one: that is found from the material alone
/// and a contact test, without the Join (a boolean that takes seconds on a large body).
pub fn addition(self, cmds: &[(String, Value)], inside: bool) -> (Option<Addition>, Option<crate::Evaluated>) {
let s = self.0;
let before = s.model.state();
if cmds.is_empty() || cmds.len() > MAX_COMMANDS || before.bodies.is_empty() {
return (None, None);
}
let (Some(alone), Some(joined)) = (with_operation(cmds, "new"), with_operation(cmds, "join")) else { return (None, None) };
let Ok(tools) = s.preview(&alone) else { return (None, None) };
let tools: Vec<&solidcraft_doc::ModelBody> = tools.after.bodies.iter().filter(|b| tools.before.body(&b.name).is_none()).collect();
// Every body the Join could take part in (its scope is narrower): none touched, none joined.
let named: Vec<String> = joined
.iter()
.flat_map(|(_, p)| {
let p = p.get("params").filter(|_| p.get("command").is_some()).unwrap_or(p);
crate::params::string_list_or_default(p, "targets").into_iter().chain(crate::params::string_list_or_default(p, "participants"))
})
.collect();
let candidates: Vec<&solidcraft_doc::ModelBody> = before
.bodies
.iter()
.filter(|b| named.is_empty() || named.iter().any(|n| n == "*" || *n == b.name))
.filter(|b| !b.body.is_mesh())
.collect();
if !tools.is_empty() && !tools.iter().any(|t| candidates.iter().any(|b| t.body.meets(&b.body).unwrap_or(true))) {
return (Some(Addition::Apart), None);
}
let Ok((after, _)) = s.preview_in_place(&joined, None) else { return (None, None) };
let state = after.model.state();
// A Join with nothing to join makes a new body.
if state.bodies.iter().any(|b| before.body(&b.name).is_none()) || !solidcraft_doc::join_pieces_added(&before, &state).is_empty() {
return (Some(Addition::Apart), None);
}
if inside && adds_nothing(&before, &state, &tools) {
return (Some(Addition::Inside), None);
}
after.world_state().warm_display();
(Some(Addition::Joins), Some(crate::Evaluated(after.model)))
}
}

/// Whether the Join from `before` to `after` added (next to) no volume: its material lies inside
/// the bodies. Display meshes are close enough for that, against the material's own volume;
/// measuring a large body exactly takes seconds.
fn adds_nothing(before: &solidcraft_doc::ModelState, after: &solidcraft_doc::ModelState, tools: &[&solidcraft_doc::ModelBody]) -> bool {
let (mut had, mut have) = (0.0, 0.0);
for was in &before.bodies {
match after.body(&was.name) {
Some(now) if now.body.same_shape(&was.body) => {}
Some(now) => {
had += mesh_volume(&was.mesh());
have += mesh_volume(&now.mesh());
}
None => had += mesh_volume(&was.mesh()),
}
}
let material: f64 = tools.iter().map(|t| mesh_volume(&t.mesh())).sum();
material > 0.0 && (have - had) < material * 0.01
}

/// The volume a closed mesh encloses.
fn mesh_volume(m: &solidcraft_geom::Mesh) -> f64 {
m.triangles.iter().filter_map(|t| m.tri(t)).map(|[a, b, c]| a.dot(b.cross(c)) / 6.0).sum::<f64>().abs()
}

/// `cmds` with their New Body or Join operation set to `op`; None when none has one.
fn with_operation(cmds: &[(String, Value)], op: &str) -> Option<Vec<(String, Value)>> {
let mut out = cmds.to_vec();
let mut any = false;
for (command, p) in &mut out {
let inner = p.get("command").and_then(Value::as_str).unwrap_or(command.as_str());
if inner == "solid.combine" {
return None;
}
let fields = if p.get("command").is_some() { p.get_mut("params")? } else { p };
if let Some(o) = fields.get_mut("operation")
&& o.as_str().is_some_and(|o| o == "new" || o == "join")
{
*o = Value::from(op);
any = true;
}
}
any.then_some(out)
}

#[cfg(test)]
#[path = "join_pieces_tests.rs"]
mod tests;
Loading
Loading