diff --git a/assets/i18n/en_US.json b/assets/i18n/en_US.json index d7b4256..f4f8b7c 100644 --- a/assets/i18n/en_US.json +++ b/assets/i18n/en_US.json @@ -580,6 +580,13 @@ "core.measurements.invalid_dimension_attachment": "Invalid dimension attachment", "core.measurements.invalid_dimension_attachment_weights": "Invalid dimension attachment weights", "core.measurements.invalid_dimension_position": "Invalid dimension position", + "core.dimension_stretch.angle_dimensions_cannot_resize_geometry": "Angle dimensions can't resize geometry yet", + "core.dimension_stretch.another_fixed_dimension_holds_this_size": "Another fixed dimension holds this size. Free it first.", + "core.dimension_stretch.attach_the_moving_end_to_geometry": "Attach the moving end of the dimension to geometry to resize it", + "core.dimension_stretch.enter_a_positive_length": "Enter a positive length", + "core.dimension_stretch.that_length_would_fold_the_geometry": "That length is too short: the geometry would fold over itself", + "core.dimension_stretch.the_dimension_no_longer_exists": "The dimension no longer exists", + "core.dimension_stretch.this_dimension_cannot_resize_its_geometry": "This dimension can't resize its geometry to that length", "core.modeling.cannot_offset_a_folded_boundary": "Cannot offset a folded boundary", "core.modeling.cannot_offset_this_corner": "Cannot offset this corner", "core.modeling.choose_a_rotation_axis_first": "Choose a rotation axis first", @@ -1095,6 +1102,20 @@ "joinery_cards.a_tenon_with_shoulders_fits_into_a_rectangular": "A tenon with shoulders fits into a rectangular mortise.", "joinery_cards.alternating_straight_fingers_interlock_across_the_joint": "Alternating straight fingers interlock across the joint.", "joinery_cards.opposing_half_depth_cuts_let_the_two_parts": "Opposing half-depth cuts let the two parts overlap.", + "dimension_length.apply": "Apply", + "dimension_length.a_fixed_dimension_holds_this_size": "Can't change this: a fixed dimension holds it at {length}. Free or delete the dimension first.", + "dimension_length.center": "Center", + "dimension_length.end_point": "End point", + "dimension_length.fix_dimension": "Fix dimension", + "dimension_length.fix_length": "Fix length", + "dimension_length.fix_length_hint": "Edits that would change this length, such as Push/Pull, Move or Scale, are refused.", + "dimension_length.free_dimension": "Free dimension", + "dimension_length.keep_fixed": "Keep fixed", + "dimension_length.keep_fixed_hint": "The start point is the first point you clicked when creating the dimension.", + "dimension_length.new_part_keeps_the_fixed_dimension": "A fixed dimension holds this part, so Push/Pull added a new part with its own size.", + "dimension_length.resize_from_dimension": "Resize from dimension", + "dimension_length.resize_hint": "Type a new length and press Enter to resize the geometry this dimension measures.", + "dimension_length.start_point": "Start point", "measurement_tools.add_angle_dimension": "Add angle dimension", "measurement_tools.add_dimension": "Add dimension", "measurement_tools.add_guide": "Add guide", diff --git a/assets/i18n/es_419.json b/assets/i18n/es_419.json index 0dc8717..733e2a9 100644 --- a/assets/i18n/es_419.json +++ b/assets/i18n/es_419.json @@ -580,6 +580,13 @@ "core.measurements.invalid_dimension_attachment": "Anclaje de cota no válido", "core.measurements.invalid_dimension_attachment_weights": "Pesos de anclaje de cota no válidos", "core.measurements.invalid_dimension_position": "Posición de cota no válida", + "core.dimension_stretch.angle_dimensions_cannot_resize_geometry": "Las cotas de ángulo aún no pueden cambiar el tamaño de la geometría", + "core.dimension_stretch.another_fixed_dimension_holds_this_size": "Otra cota fija mantiene esta medida. Libérala primero.", + "core.dimension_stretch.attach_the_moving_end_to_geometry": "Ancla a la geometría el extremo de la cota que se mueve para cambiar su tamaño", + "core.dimension_stretch.enter_a_positive_length": "Introduce una longitud positiva", + "core.dimension_stretch.that_length_would_fold_the_geometry": "Esa longitud es demasiado corta: la geometría se doblaría sobre sí misma", + "core.dimension_stretch.the_dimension_no_longer_exists": "La cota ya no existe", + "core.dimension_stretch.this_dimension_cannot_resize_its_geometry": "Esta cota no puede ajustar su geometría a esa longitud", "core.modeling.cannot_offset_a_folded_boundary": "No se puede desfasar un contorno plegado", "core.modeling.cannot_offset_this_corner": "No se puede desfasar esta esquina", "core.modeling.choose_a_rotation_axis_first": "Elige primero un eje de rotación", @@ -1095,6 +1102,20 @@ "joinery_cards.a_tenon_with_shoulders_fits_into_a_rectangular": "Una espiga con hombros encaja en una caja rectangular.", "joinery_cards.alternating_straight_fingers_interlock_across_the_joint": "Dedos rectos alternados se entrelazan a lo largo de la unión.", "joinery_cards.opposing_half_depth_cuts_let_the_two_parts": "Cortes opuestos a media profundidad permiten que las dos piezas se solapen.", + "dimension_length.apply": "Aplicar", + "dimension_length.a_fixed_dimension_holds_this_size": "No se puede cambiar: una cota fija lo mantiene en {length}. Libera o borra la cota primero.", + "dimension_length.center": "Centro", + "dimension_length.end_point": "Punto final", + "dimension_length.fix_dimension": "Fijar cota", + "dimension_length.fix_length": "Fijar medida", + "dimension_length.fix_length_hint": "Se rechazan las ediciones que cambiarían esta medida, como Empujar/Tirar, Mover o Escalar.", + "dimension_length.free_dimension": "Liberar cota", + "dimension_length.keep_fixed": "Mantener fijo", + "dimension_length.keep_fixed_hint": "El punto inicial es el primer punto en el que hiciste clic al crear la cota.", + "dimension_length.new_part_keeps_the_fixed_dimension": "Una cota fija mantiene esta parte, así que Empujar/Tirar agregó una parte nueva con su propia medida.", + "dimension_length.resize_from_dimension": "Redimensionar desde cota", + "dimension_length.resize_hint": "Escribe una nueva longitud y pulsa Intro para cambiar el tamaño de la geometría que mide esta cota.", + "dimension_length.start_point": "Punto inicial", "measurement_tools.add_angle_dimension": "Agregar cota angular", "measurement_tools.add_dimension": "Agregar cota", "measurement_tools.add_guide": "Agregar guía", diff --git a/assets/i18n/it_IT.json b/assets/i18n/it_IT.json index e7c7428..b920090 100644 --- a/assets/i18n/it_IT.json +++ b/assets/i18n/it_IT.json @@ -580,6 +580,13 @@ "core.measurements.invalid_dimension_attachment": "Ancoraggio della quota non valido", "core.measurements.invalid_dimension_attachment_weights": "Pesi dell'ancoraggio della quota non validi", "core.measurements.invalid_dimension_position": "Posizione della quota non valida", + "core.dimension_stretch.angle_dimensions_cannot_resize_geometry": "Le quote angolari non possono ancora ridimensionare la geometria", + "core.dimension_stretch.another_fixed_dimension_holds_this_size": "Un'altra quota fissa blocca questa misura. Sbloccala prima.", + "core.dimension_stretch.attach_the_moving_end_to_geometry": "Aggancia alla geometria l'estremità mobile della quota per ridimensionarla", + "core.dimension_stretch.enter_a_positive_length": "Inserisci una lunghezza positiva", + "core.dimension_stretch.that_length_would_fold_the_geometry": "Questa lunghezza è troppo corta: la geometria si ripiegherebbe su se stessa", + "core.dimension_stretch.the_dimension_no_longer_exists": "La quota non esiste più", + "core.dimension_stretch.this_dimension_cannot_resize_its_geometry": "Questa quota non può ridimensionare la sua geometria a quella lunghezza", "core.modeling.cannot_offset_a_folded_boundary": "Impossibile applicare l'offset a un contorno ripiegato", "core.modeling.cannot_offset_this_corner": "Impossibile applicare l'offset a questo angolo", "core.modeling.choose_a_rotation_axis_first": "Scegli prima un asse di rotazione", @@ -1095,6 +1102,20 @@ "joinery_cards.a_tenon_with_shoulders_fits_into_a_rectangular": "Un tenone con spalle si inserisce in una mortasa rettangolare.", "joinery_cards.alternating_straight_fingers_interlock_across_the_joint": "Denti dritti alternati si incastrano lungo il giunto.", "joinery_cards.opposing_half_depth_cuts_let_the_two_parts": "Tagli opposti a metà spessore permettono ai due pezzi di sovrapporsi.", + "dimension_length.apply": "Applica", + "dimension_length.a_fixed_dimension_holds_this_size": "Impossibile modificare: una quota fissa lo mantiene a {length}. Sblocca o elimina prima la quota.", + "dimension_length.center": "Centro", + "dimension_length.end_point": "Punto finale", + "dimension_length.fix_dimension": "Fissa quota", + "dimension_length.fix_length": "Fissa misura", + "dimension_length.fix_length_hint": "Le modifiche che cambierebbero questa misura, come Spingi/Tira, Sposta o Scala, vengono rifiutate.", + "dimension_length.free_dimension": "Sblocca quota", + "dimension_length.keep_fixed": "Mantieni fisso", + "dimension_length.keep_fixed_hint": "Il punto iniziale è il primo punto su cui hai fatto clic creando la quota.", + "dimension_length.new_part_keeps_the_fixed_dimension": "Una quota fissa blocca questa parte, quindi Spingi/Tira ha aggiunto una nuova parte con la sua misura.", + "dimension_length.resize_from_dimension": "Ridimensiona da quota", + "dimension_length.resize_hint": "Digita una nuova lunghezza e premi Invio per ridimensionare la geometria misurata da questa quota.", + "dimension_length.start_point": "Punto iniziale", "measurement_tools.add_angle_dimension": "Aggiungi quota angolare", "measurement_tools.add_dimension": "Aggiungi quota", "measurement_tools.add_guide": "Aggiungi guida", diff --git a/assets/i18n/pt_BR.json b/assets/i18n/pt_BR.json index 5406d62..9d6ca76 100644 --- a/assets/i18n/pt_BR.json +++ b/assets/i18n/pt_BR.json @@ -580,6 +580,13 @@ "core.measurements.invalid_dimension_attachment": "Vínculo da cota inválido", "core.measurements.invalid_dimension_attachment_weights": "Pesos do vínculo da cota inválidos", "core.measurements.invalid_dimension_position": "Posição da cota inválida", + "core.dimension_stretch.angle_dimensions_cannot_resize_geometry": "Cotas de ângulo ainda não podem redimensionar a geometria", + "core.dimension_stretch.another_fixed_dimension_holds_this_size": "Outra cota fixa mantém esta medida. Libere-a primeiro.", + "core.dimension_stretch.attach_the_moving_end_to_geometry": "Prenda à geometria a extremidade móvel da cota para redimensioná-la", + "core.dimension_stretch.enter_a_positive_length": "Insira um comprimento positivo", + "core.dimension_stretch.that_length_would_fold_the_geometry": "Esse comprimento é curto demais: a geometria se dobraria sobre si mesma", + "core.dimension_stretch.the_dimension_no_longer_exists": "A cota não existe mais", + "core.dimension_stretch.this_dimension_cannot_resize_its_geometry": "Esta cota não consegue redimensionar sua geometria para esse comprimento", "core.modeling.cannot_offset_a_folded_boundary": "Não é possível aplicar equidistância a um contorno dobrado", "core.modeling.cannot_offset_this_corner": "Não é possível aplicar equidistância neste canto", "core.modeling.choose_a_rotation_axis_first": "Escolha primeiro um eixo de rotação", @@ -1093,6 +1100,20 @@ "joinery_cards.a_tenon_with_shoulders_fits_into_a_rectangular": "Uma espiga com ombros encaixa em uma caixa retangular.", "joinery_cards.alternating_straight_fingers_interlock_across_the_joint": "Dedos retos alternados se intertravam ao longo do encaixe.", "joinery_cards.opposing_half_depth_cuts_let_the_two_parts": "Cortes opostos de meia profundidade permitem que as duas peças se sobreponham.", + "dimension_length.apply": "Aplicar", + "dimension_length.a_fixed_dimension_holds_this_size": "Não é possível alterar: uma cota fixa o mantém em {length}. Libere ou exclua a cota primeiro.", + "dimension_length.center": "Centro", + "dimension_length.end_point": "Ponto final", + "dimension_length.fix_dimension": "Fixar cota", + "dimension_length.fix_length": "Fixar medida", + "dimension_length.fix_length_hint": "Edições que alterariam esta medida, como Empurrar/Puxar, Mover ou Escala, são recusadas.", + "dimension_length.free_dimension": "Liberar cota", + "dimension_length.keep_fixed": "Manter fixo", + "dimension_length.keep_fixed_hint": "O ponto inicial é o primeiro ponto em que você clicou ao criar a cota.", + "dimension_length.new_part_keeps_the_fixed_dimension": "Uma cota fixa mantém esta parte, então Empurrar/Puxar adicionou uma nova parte com sua própria medida.", + "dimension_length.resize_from_dimension": "Redimensionar pela cota", + "dimension_length.resize_hint": "Digite um novo comprimento e pressione Enter para redimensionar a geometria medida por esta cota.", + "dimension_length.start_point": "Ponto inicial", "measurement_tools.add_angle_dimension": "Adicionar cota angular", "measurement_tools.add_dimension": "Adicionar cota", "measurement_tools.add_guide": "Adicionar guia", diff --git a/assets/i18n/vi_VN.json b/assets/i18n/vi_VN.json index 98126f3..e90141e 100644 --- a/assets/i18n/vi_VN.json +++ b/assets/i18n/vi_VN.json @@ -580,6 +580,13 @@ "core.measurements.invalid_dimension_attachment": "Tệp đính kèm kích thước không hợp lệ", "core.measurements.invalid_dimension_attachment_weights": "Trọng số đính kèm kích thước không hợp lệ", "core.measurements.invalid_dimension_position": "Vị trí kích thước không hợp lệ", + "core.dimension_stretch.angle_dimensions_cannot_resize_geometry": "Kích thước góc chưa thể thay đổi kích thước hình học", + "core.dimension_stretch.another_fixed_dimension_holds_this_size": "Một kích thước cố định khác đang giữ số đo này. Hãy bỏ cố định nó trước.", + "core.dimension_stretch.attach_the_moving_end_to_geometry": "Gắn đầu di chuyển của kích thước vào hình học để thay đổi kích thước", + "core.dimension_stretch.enter_a_positive_length": "Nhập độ dài dương", + "core.dimension_stretch.that_length_would_fold_the_geometry": "Độ dài đó quá ngắn: hình học sẽ tự gập lên chính nó", + "core.dimension_stretch.the_dimension_no_longer_exists": "Kích thước không còn tồn tại", + "core.dimension_stretch.this_dimension_cannot_resize_its_geometry": "Kích thước này không thể đổi hình học của nó thành độ dài đó", "core.modeling.cannot_offset_a_folded_boundary": "Không thể bù đắp ranh giới gấp", "core.modeling.cannot_offset_this_corner": "Không thể bù góc này", "core.modeling.choose_a_rotation_axis_first": "Chọn trục quay trước", @@ -1095,6 +1102,20 @@ "joinery_cards.a_tenon_with_shoulders_fits_into_a_rectangular": "Mộng có vai khớp với lỗ mộng hình chữ nhật.", "joinery_cards.alternating_straight_fingers_interlock_across_the_joint": "Các ngón tay thẳng xen kẽ đan xen vào nhau trên khớp.", "joinery_cards.opposing_half_depth_cuts_let_the_two_parts": "Cắt giảm nửa độ sâu để hai phần chồng lên nhau.", + "dimension_length.apply": "Áp dụng", + "dimension_length.a_fixed_dimension_holds_this_size": "Không thể thay đổi: một kích thước cố định đang giữ ở {length}. Hãy bỏ cố định hoặc xóa kích thước trước.", + "dimension_length.center": "Tâm", + "dimension_length.end_point": "Điểm cuối", + "dimension_length.fix_dimension": "Cố định kích thước", + "dimension_length.fix_length": "Cố định độ dài", + "dimension_length.fix_length_hint": "Các chỉnh sửa làm thay đổi độ dài này, như Đẩy/Kéo, Di chuyển hoặc Tỷ lệ, sẽ bị từ chối.", + "dimension_length.free_dimension": "Bỏ cố định kích thước", + "dimension_length.keep_fixed": "Giữ cố định", + "dimension_length.keep_fixed_hint": "Điểm đầu là điểm đầu tiên bạn nhấp khi tạo kích thước.", + "dimension_length.new_part_keeps_the_fixed_dimension": "Một kích thước cố định đang giữ phần này, nên Đẩy/Kéo đã thêm một phần mới với kích thước riêng.", + "dimension_length.resize_from_dimension": "Đổi kích thước theo kích thước đo", + "dimension_length.resize_hint": "Nhập độ dài mới và nhấn Enter để thay đổi kích thước hình học mà kích thước này đo.", + "dimension_length.start_point": "Điểm đầu", "measurement_tools.add_angle_dimension": "Thêm kích thước góc", "measurement_tools.add_dimension": "Thêm kích thước", "measurement_tools.add_guide": "Thêm hướng dẫn", diff --git a/assets/i18n/zh_CN.json b/assets/i18n/zh_CN.json index 3a5e228..e88d36c 100644 --- a/assets/i18n/zh_CN.json +++ b/assets/i18n/zh_CN.json @@ -580,6 +580,13 @@ "core.measurements.invalid_dimension_attachment": "尺寸标注附着对象无效", "core.measurements.invalid_dimension_attachment_weights": "尺寸标注附着权重无效", "core.measurements.invalid_dimension_position": "尺寸标注位置无效", + "core.dimension_stretch.angle_dimensions_cannot_resize_geometry": "角度标注暂时无法调整几何体尺寸", + "core.dimension_stretch.another_fixed_dimension_holds_this_size": "另一个固定标注锁定了此尺寸,请先取消固定。", + "core.dimension_stretch.attach_the_moving_end_to_geometry": "请将标注的移动端附着到几何体上以调整尺寸", + "core.dimension_stretch.enter_a_positive_length": "请输入正数长度", + "core.dimension_stretch.that_length_would_fold_the_geometry": "该长度过短:几何体会自身折叠", + "core.dimension_stretch.the_dimension_no_longer_exists": "该标注已不存在", + "core.dimension_stretch.this_dimension_cannot_resize_its_geometry": "此标注无法将其几何体调整到该长度", "core.modeling.cannot_offset_a_folded_boundary": "无法偏移折起的边界", "core.modeling.cannot_offset_this_corner": "无法偏移此角点", "core.modeling.choose_a_rotation_axis_first": "请先选择旋转轴", @@ -1095,6 +1102,20 @@ "joinery_cards.a_tenon_with_shoulders_fits_into_a_rectangular": "带肩的榫头嵌入矩形榫眼中。", "joinery_cards.alternating_straight_fingers_interlock_across_the_joint": "交替的直指齿在接合处相互咬合。", "joinery_cards.opposing_half_depth_cuts_let_the_two_parts": "对向的半深度切削使两个部件相互搭接。", + "dimension_length.apply": "应用", + "dimension_length.a_fixed_dimension_holds_this_size": "无法更改:一个固定标注将其锁定为 {length}。请先取消固定或删除该标注。", + "dimension_length.center": "中心", + "dimension_length.end_point": "终点", + "dimension_length.fix_dimension": "固定标注", + "dimension_length.fix_length": "固定长度", + "dimension_length.fix_length_hint": "会改变此长度的编辑(如推/拉、移动或缩放)将被拒绝。", + "dimension_length.free_dimension": "取消固定标注", + "dimension_length.keep_fixed": "保持固定", + "dimension_length.keep_fixed_hint": "起点是创建标注时单击的第一个点。", + "dimension_length.new_part_keeps_the_fixed_dimension": "此部分由固定标注锁定,因此推/拉添加了一个具有独立尺寸的新部分。", + "dimension_length.resize_from_dimension": "按标注调整尺寸", + "dimension_length.resize_hint": "输入新长度并按 Enter,即可调整此标注所测几何体的尺寸。", + "dimension_length.start_point": "起点", "measurement_tools.add_angle_dimension": "添加角度标注", "measurement_tools.add_dimension": "添加尺寸标注", "measurement_tools.add_guide": "添加参考线", diff --git a/crates/benchup-app/src/app.rs b/crates/benchup-app/src/app.rs index d948fb6..bd838db 100644 --- a/crates/benchup-app/src/app.rs +++ b/crates/benchup-app/src/app.rs @@ -53,6 +53,8 @@ mod cutting_view; pub(crate) mod display_scene; #[path = "construction_guides.rs"] mod construction_guides; +#[path = "dimension_length.rs"] +mod dimension_length; #[path = "dimension_overlay.rs"] mod dimension_overlay; #[path = "drawing_inference.rs"] @@ -436,6 +438,11 @@ pub struct BenchUpApp { move_modifier_down: bool, last_move_copy: Option, measurement: Option, + dimension_length_input: dimension_length::DimensionLengthInput, + dimension_fixed_point: benchup_core::DimensionFixedPoint, + /// The dimension whose typed value is being applied; it alone may change + /// while other fixed dimensions are enforced. + driving_dimension: Option, create_guides: bool, guide_modifier_down: bool, guide_toggle_pending: bool, @@ -475,6 +482,8 @@ pub struct BenchUpApp { release_notes: crate::release_notes::ReleaseNotes, shortcut_filter: String, notice: Option<(String, f64)>, + /// The current notice explains why an action was refused. + notice_warning: bool, dirty_since: Option, save_error: Option, storage_recovery: bool, @@ -636,6 +645,9 @@ impl BenchUpApp { move_modifier_down: false, last_move_copy: None, measurement: None, + dimension_length_input: Default::default(), + dimension_fixed_point: Default::default(), + driving_dimension: None, create_guides: true, guide_modifier_down: false, guide_toggle_pending: false, @@ -674,6 +686,7 @@ impl BenchUpApp { about: false, release_notes: crate::release_notes::ReleaseNotes::default(), shortcut_filter: String::new(), + notice_warning: error.is_some(), notice: error.map(|e| { ( tr!("app.could_not_restore_your_model_a_new_workspace", e = e), @@ -760,8 +773,15 @@ impl BenchUpApp { } fn say(&mut self, ctx: &egui::Context, text: impl Into) { self.notice = Some((text.into(), ctx.input(|i| i.time) + 5.)); + self.notice_warning = false; ctx.request_repaint_after(Duration::from_secs(5)); } + /// Explain why an action was refused, with a warning marker. + fn warn(&mut self, ctx: &egui::Context, text: impl Into) { + self.notice = Some((text.into(), ctx.input(|i| i.time) + 6.)); + self.notice_warning = true; + ctx.request_repaint_after(Duration::from_secs(6)); + } fn set_tool(&mut self, tool: Tool) { self.selection_click = None; let original_camera = (tool == Tool::Walk).then(|| { @@ -859,13 +879,19 @@ impl BenchUpApp { } /// Records an edit the caller already knows changed the model, without /// comparing the models again. Returns false if it was refused (shared - /// project without edit access) and rolled back. + /// project without edit access, or a fixed dimension would change) and + /// rolled back. fn commit_changed_edit(&mut self, label: &str, before: Model, ctx: &egui::Context) -> bool { if !self.shared_edit_allowed(ctx) { self.doc.model = before; self.say(ctx, self.shared_edit_block_reason(ctx)); return false; } + if let Some(message) = self.fixed_dimension_block(&before) { + self.doc.model = before; + self.warn(ctx, message); + return false; + } let author = self.current_history_author(); self.doc.history.record_applied_attributed( label, @@ -1713,7 +1739,7 @@ impl BenchUpApp { return; }; if self.doc.model.is_locked(id) { - self.say(ctx, tr!("app.unlock_the_face_before_editing_it")); + self.warn(ctx, tr!("app.unlock_the_face_before_editing_it")); return; } face_id = Some(id); @@ -1760,7 +1786,7 @@ impl BenchUpApp { return; } if self.doc.model.selection_locked(&self.selected) { - self.say(ctx, tr!("app.unlock_the_selection_before_editing_it")); + self.warn(ctx, tr!("app.unlock_the_selection_before_editing_it")); return; } let Some(snap) = grip.map(|grip| Snap { point: grip.point, kind: Inference::Endpoint }) @@ -2244,6 +2270,25 @@ impl BenchUpApp { Some(Snap { point, kind }) } + /// Stretching a face would change a fixed dimension, but adding a new + /// layer of faces keeps the measured part's size. Push/Pull then builds the + /// new part instead, so each part keeps its own specific measurement. + /// When neither respects the dimension, the commit refuses with a notice. + fn push_pull_layers_for_fixed_dimension(edit: &Modeling, scoped: &Model, face: u64, delta: DVec3) -> bool { + if !edit.base.dimensions.values().any(|d| d.fixed) { + return false; + } + let mut stretched = scoped.clone(); + if stretched.push_pull_along(face, delta).is_err() + || stretched.changed_fixed_dimension(&edit.base, None).is_none() + { + return false; + } + let mut layered = scoped.clone(); + layered.push_pull_along_with_new_faces(face, delta).is_ok() + && layered.changed_fixed_dimension(&edit.base, None).is_none() + } + fn modeling_result(tool: Tool, edit: &Modeling, value: f64) -> Result { let mut model = edit.base.clone(); match tool { @@ -2252,10 +2297,11 @@ impl BenchUpApp { let face_id = face.id; let context = model.edit_context; model.edit_context = model.parent(face_id); - if edit.keep_starting_face { - model.push_pull_along_with_new_faces(face_id, edit.direction * value)?; + let delta = edit.direction * value; + if edit.keep_starting_face || Self::push_pull_layers_for_fixed_dimension(edit, &model, face_id, delta) { + model.push_pull_along_with_new_faces(face_id, delta)?; } else { - model.push_pull_along(face_id, edit.direction * value)?; + model.push_pull_along(face_id, delta)?; } model.edit_context = context; } @@ -2325,6 +2371,13 @@ impl BenchUpApp { match Self::modeling_result(self.tool, edit, value) { Ok(model) => { let before = edit.base.clone(); + let layered = self.tool == Tool::PushPull + && !edit.keep_starting_face + && edit.face.is_some_and(|face| { + let mut scoped = before.clone(); + scoped.edit_context = scoped.parent(face); + Self::push_pull_layers_for_fixed_dimension(edit, &scoped, face, edit.direction * value) + }); if self.tool == Tool::PushPull { let group = edit.face.and_then(|face| before.entity_in_context(face)) .filter(|id| before.objects.contains_key(id)); @@ -2365,9 +2418,12 @@ impl BenchUpApp { before, ctx, ); + if layered { + self.say(ctx, tr!("dimension_length.new_part_keeps_the_fixed_dimension")); + } self.last_move_copy = copy; } - Err(message) => self.say(ctx, message), + Err(message) => self.warn(ctx, message), } } @@ -4199,6 +4255,7 @@ impl BenchUpApp { } self.solid_inspector(ui); self.measurement_inspector(ui); + self.dimension_length_inspector(ui); self.text_entity_info(ui); self.grain_direction_inspector(ui); if self.selected.is_empty() { @@ -6956,26 +7013,44 @@ impl BenchUpApp { self.paint_dimension_overlay(&p, rect); if let Some((notice, until)) = &self.notice { if ui.input(|i| i.time) < *until { - let galley = p.layout( - notice.clone(), - FontId::proportional(12.), - colors.ink, - (rect.width() - 80.).clamp(120., 600.), - ); - let r = Rect::from_min_size( - rect.left_top() + egui::vec2(20., 20.), - galley.size() + egui::vec2(24., 20.), - ); - p.rect_filled(r, 7, colors.paper); - p.rect_stroke( - r, - 7, - Stroke::new(1., colors.border), - egui::StrokeKind::Inside, - ); - p.galley(r.min + egui::vec2(12., 10.), galley, colors.ink); - } + Self::paint_notice(&p, rect, notice, self.notice_warning); + } + } + } + /// A console-style line at the bottom of the viewport. Refusals carry a + /// warning marker and accent so the reason stands out from routine hints. + fn paint_notice(p: &egui::Painter, rect: Rect, notice: &str, warning: bool) { + const BACKGROUND: Color32 = Color32::from_rgba_premultiplied(20, 24, 22, 235); + const TEXT: Color32 = Color32::from_rgb(222, 230, 222); + const AMBER: Color32 = Color32::from_rgb(242, 184, 64); + let icon = if warning { 22. } else { 0. }; + let text_color = if warning { AMBER } else { TEXT }; + let galley = p.layout( + notice.to_owned(), + FontId::monospace(12.), + text_color, + (rect.width() - 80. - icon).clamp(120., 720.), + ); + let size = galley.size() + egui::vec2(28. + icon, 18.); + let r = Rect::from_min_size( + egui::pos2(rect.center().x - size.x * 0.5, rect.bottom() - 24. - size.y), + size, + ); + p.rect_filled(r, 6, BACKGROUND); + let edge = if warning { AMBER } else { Color32::from_gray(70) }; + p.rect_stroke(r, 6, Stroke::new(1., edge), egui::StrokeKind::Inside); + if warning { + // Font-independent triangle with an exclamation mark. + let c = egui::pos2(r.left() + 14. + 7., r.center().y); + p.add(egui::Shape::convex_polygon( + vec![c + egui::vec2(0., -7.), c + egui::vec2(8., 6.), c + egui::vec2(-8., 6.)], + AMBER, + Stroke::NONE, + )); + p.line_segment([c + egui::vec2(0., -3.), c + egui::vec2(0., 1.5)], Stroke::new(1.8, BACKGROUND)); + p.circle_filled(c + egui::vec2(0., 3.8), 1., BACKGROUND); } + p.galley(r.min + egui::vec2(14. + icon, 9.), galley, text_color); } fn edit_context_bar(&mut self, ui: &mut egui::Ui) { let colors = Palette::for_ui(ui); diff --git a/crates/benchup-app/src/app_tests.rs b/crates/benchup-app/src/app_tests.rs index c756c1c..916dd39 100644 --- a/crates/benchup-app/src/app_tests.rs +++ b/crates/benchup-app/src/app_tests.rs @@ -5662,6 +5662,7 @@ fn dimensions_locked_during_selection_or_placement_keep_three_lines_and_a_label( axis: Some(axis), plane: None, vertex: None, + fixed: false, }; let layout = dimension.layout(&h.app.doc.model).map(|point| h.at(point)); let lines = [ @@ -7681,3 +7682,220 @@ fn focus_picker_highlights_like_pointer_without_selecting() { #[path = "follow_me_ui_tests.rs"] mod follow_me_ui_tests; + +#[test] +fn push_pull_still_works_after_resizing_from_a_dimension_and_erasing_it() { + let mut h = Harness::new(); + modeling_rectangle(&mut h); + let face = *h.app.doc.model.faces.keys().next().unwrap(); + h.app.doc.model.push_pull_along(face, DVec3::Z).unwrap(); + let dimension = h + .app + .doc + .model + .add_dimension(DVec3::ZERO, DVec3::new(4., 0., 0.), -DVec3::Y) + .unwrap(); + h.app.selected = BTreeSet::from([dimension]); + h.frame(vec![], egui::Modifiers::NONE); + h.app.dimension_length_input.text = "5".into(); + h.app.apply_dimension_length(dimension, &h.ctx); + h.frame(vec![], egui::Modifiers::NONE); + let xs = || h.app.doc.model.vertices.values().map(|v| v.position.x).fold(0., f64::max); + assert!((xs() - 5.).abs() < 1e-7); + + h.app.selected = BTreeSet::from([dimension]); + h.key(Key::Delete); + assert!(h.app.doc.model.dimensions.is_empty(), "the dimension is erased"); + h.frame(vec![], egui::Modifiers::NONE); + + h.key(Key::P); + assert_eq!(h.app.tool, Tool::PushPull); + let top = DVec3::new(2.5, 2., 1.); + h.click(h.at(top)); + assert!(h.app.modeling.is_some(), "push/pull starts on the resized top face"); + modeling_number(&mut h, "1"); + let top_z = h.app.doc.model.vertices.values().map(|v| v.position.z).fold(0., f64::max); + assert!((top_z - 2.).abs() < 1e-7, "top at {top_z}"); +} + +#[test] +fn push_pull_after_drawing_and_driving_a_dimension_with_the_tools() { + for (resize, erase) in [(false, false), (true, false), (true, true)] { + let mut h = Harness::new(); + modeling_rectangle(&mut h); + let face = *h.app.doc.model.faces.keys().next().unwrap(); + h.app.doc.model.push_pull_along(face, DVec3::Z).unwrap(); + h.key(Key::I); + h.click(h.at(DVec3::ZERO)); + h.click(h.at(DVec3::X * 4.)); + h.click(h.at(DVec3::new(2., -1.5, 0.))); + let id = *h.app.doc.model.dimensions.keys().next().unwrap(); + h.key(Key::Space); + let [_, _, a, b] = h.app.doc.model.dimensions[&id].layout(&h.app.doc.model); + h.click(h.at((a + b) * 0.5)); + assert_eq!(h.app.selected, BTreeSet::from([id])); + if resize { + h.app.dimension_length_input.text = "5".into(); + h.app.apply_dimension_length(id, &h.ctx); + h.frame(vec![], egui::Modifiers::NONE); + } + if erase { + h.key(Key::Delete); + assert!(h.app.doc.model.dimensions.is_empty()); + } + h.key(Key::P); + assert_eq!(h.app.tool, Tool::PushPull, "resize={resize} erase={erase}"); + h.click(h.at(DVec3::new(2., 2., 1.))); + assert!(h.app.modeling.is_some(), "resize={resize} erase={erase}: no push/pull; notice {:?}", h.app.notice); + modeling_number(&mut h, "1"); + let top = h.app.doc.model.vertices.values().map(|v| v.position.z).fold(0., f64::max); + assert!((top - 2.).abs() < 1e-7, "resize={resize} erase={erase}: top {top}"); + } +} + +#[test] +fn typing_in_the_dimension_field_returns_shortcuts_to_the_viewport() { + for erase in [false, true] { + let mut h = Harness::new(); + modeling_rectangle(&mut h); + let face = *h.app.doc.model.faces.keys().next().unwrap(); + h.app.doc.model.push_pull_along(face, DVec3::Z).unwrap(); + let id = h + .app + .doc + .model + .add_dimension(DVec3::ZERO, DVec3::X * 4., -DVec3::Y * 1.5) + .unwrap(); + h.app.selected = BTreeSet::from([id]); + h.frame(vec![], egui::Modifiers::NONE); + let field = dimension_length::field_id(); + h.ctx.memory_mut(|m| m.request_focus(field)); + h.frame(vec![], egui::Modifiers::NONE); + assert!(h.ctx.memory(|m| m.has_focus(field)), "the field is shown and focusable"); + h.frame(vec![egui::Event::Key { + key: Key::A, physical_key: None, pressed: true, repeat: false, + modifiers: egui::Modifiers::COMMAND, + }], egui::Modifiers::COMMAND); + h.frame(vec![egui::Event::Text("5".into())], egui::Modifiers::NONE); + h.key(Key::Enter); + let right = h.app.doc.model.vertices.values().map(|v| v.position.x).fold(0., f64::max); + assert!((right - 5.).abs() < 1e-7, "typed value applied: {right}; notice {:?}", h.app.notice); + assert!(!h.ctx.memory(|m| m.has_focus(field)), "Enter releases the keyboard"); + if erase { + h.key(Key::Delete); + assert!(h.app.doc.model.dimensions.is_empty(), "Delete erases the dimension"); + } + h.key(Key::P); + assert_eq!(h.app.tool, Tool::PushPull, "erase={erase}"); + h.click(h.at(DVec3::new(2., 2., 1.))); + assert!(h.app.modeling.is_some(), "erase={erase}: notice {:?}", h.app.notice); + modeling_number(&mut h, "1"); + let top = h.app.doc.model.vertices.values().map(|v| v.position.z).fold(0., f64::max); + assert!((top - 2.).abs() < 1e-7, "erase={erase}: top {top}"); + } +} + +#[test] +fn fixed_dimensions_refuse_size_changes_with_a_notice_until_freed_or_erased() { + let mut h = Harness::new(); + modeling_rectangle(&mut h); + let face = *h.app.doc.model.faces.keys().next().unwrap(); + h.app.doc.model.push_pull_along(face, DVec3::Z).unwrap(); + // Place an X dimension with the Dimensions tool: it starts fixed. + h.key(Key::I); + h.click(h.at(DVec3::ZERO)); + h.click(h.at(DVec3::X * 4.)); + h.click(h.at(DVec3::new(2., -1.5, 0.))); + let id = *h.app.doc.model.dimensions.keys().next().unwrap(); + assert!(h.app.doc.model.dimensions[&id].fixed); + let face_at = |model: &Model, test: &dyn Fn(DVec3) -> bool| { + *model.faces.iter() + .find(|(_, f)| f.vertices.iter().all(|v| test(model.vertices[v].position))) + .unwrap().0 + }; + let pull = |h: &mut Harness, test: &dyn Fn(DVec3) -> bool| -> bool { + let before = h.app.doc.model.clone(); + let face = face_at(&h.app.doc.model, test); + h.app.doc.model.push_pull(face, 0.5).unwrap(); + h.app.notice = None; + h.app.finish_edit("Push/Pull", before.clone(), &h.ctx); + h.app.doc.model != before + }; + let end_face = |p: DVec3| (p.x - 4.).abs() < 1e-7; + let history = h.app.doc.history.position(); + assert!(!pull(&mut h, &end_face), "pulling the measured face is refused"); + assert_eq!(h.app.doc.history.position(), history); + let notice = h.app.notice.as_ref().map(|(text, _)| text.clone()).unwrap_or_default(); + assert!(notice.contains(&h.app.doc.display.units.format_length(4.)), "{notice}"); + assert!(h.app.notice_warning, "refusals are shown as warnings"); + // The warning line paints at the bottom of the viewport. + h.frame(vec![], egui::Modifiers::NONE); + assert!(pull(&mut h, &|p: DVec3| (p.z - 1.).abs() < 1e-7), "other sizes stay editable"); + + // Freeing the dimension from Properties allows the change. + h.app.selected = BTreeSet::from([id]); + h.app.set_dimension_fixed(id, false, &h.ctx); + assert!(!h.app.doc.model.dimensions[&id].fixed); + assert!(pull(&mut h, &|p: DVec3| (p.x - 4.).abs() < 1e-7)); + h.app.undo(&h.ctx, false); + h.app.undo(&h.ctx, false); + assert!(h.app.doc.model.dimensions[&id].fixed, "undo restores the fixed state"); + + // Erasing the dimension removes the constraint. + h.app.selected = BTreeSet::from([id]); + h.key(Key::Delete); + assert!(h.app.doc.model.dimensions.is_empty()); + assert!(pull(&mut h, &end_face)); +} + +#[test] +fn a_placed_dimension_is_ready_to_edit_without_reselecting() { + let mut h = Harness::new(); + modeling_rectangle(&mut h); + let face = *h.app.doc.model.faces.keys().next().unwrap(); + h.app.doc.model.push_pull_along(face, DVec3::Z).unwrap(); + h.key(Key::I); + h.click(h.at(DVec3::ZERO)); + h.click(h.at(DVec3::X * 4.)); + h.click(h.at(DVec3::new(2., -1.5, 0.))); + let id = *h.app.doc.model.dimensions.keys().next().unwrap(); + assert_eq!(h.app.tool, Tool::Dimensions); + assert_eq!(h.app.selected_length_dimension(), Some(id)); + h.frame(vec![], egui::Modifiers::NONE); + assert_eq!(h.app.dimension_length_input.dimension, Some(id), "Properties shows the field"); + assert_eq!(h.app.dimension_length_input.text, h.app.doc.display.units.format_length(4.)); +} + +#[test] +fn push_pull_on_a_fixed_dimension_builds_a_new_part_instead_of_stretching() { + let mut h = Harness::new(); + modeling_rectangle(&mut h); + let face = *h.app.doc.model.faces.keys().next().unwrap(); + h.app.doc.model.push_pull_along(face, DVec3::Z).unwrap(); + // A fixed thickness dimension on the cube's vertical edge. + let id = h + .app + .doc + .model + .add_dimension(DVec3::ZERO, DVec3::Z, -DVec3::Y) + .unwrap(); + h.app.doc.model.set_dimension_fixed(id, true).unwrap(); + let faces = h.app.doc.model.faces.len(); + h.key(Key::P); + h.click(h.at(DVec3::new(2., 2., 1.))); + assert!(h.app.modeling.is_some()); + modeling_number(&mut h, "1"); + let model = &h.app.doc.model; + let top = model.vertices.values().map(|v| v.position.z).fold(0., f64::max); + assert!((top - 2.).abs() < 1e-7, "the new part reaches {top}"); + assert!((model.dimensions[&id].length(model) - 1.).abs() < 1e-7, "the fixed size is kept"); + assert!(model.faces.len() > faces, "the measured part keeps its top face"); + assert_eq!( + h.app.notice.as_ref().map(|(text, _)| text.as_str()), + Some(tr!("dimension_length.new_part_keeps_the_fixed_dimension")) + ); + assert!(!h.app.notice_warning, "building a new part is information, not a refusal"); + model.validate().unwrap(); + h.app.undo(&h.ctx, false); + assert_eq!(h.app.doc.model.faces.len(), faces); +} diff --git a/crates/benchup-app/src/dimension_length.rs b/crates/benchup-app/src/dimension_length.rs new file mode 100644 index 0000000..1346cff --- /dev/null +++ b/crates/benchup-app/src/dimension_length.rs @@ -0,0 +1,278 @@ +//! Properties field that drives the geometry measured by a selected dimension. +use benchup_core::tr; +use super::*; +use benchup_core::DimensionFixedPoint; + +/// The value being typed for one dimension. It follows the model while the +/// field is not being edited, so undo and other edits refresh it. +#[derive(Clone, Debug, Default)] +pub(super) struct DimensionLengthInput { + pub(super) dimension: Option, + pub(super) shown: String, + pub(super) text: String, +} + +pub(super) fn fixed_point_label(fixed: DimensionFixedPoint) -> &'static str { + match fixed { + DimensionFixedPoint::Start => tr!("dimension_length.start_point"), + DimensionFixedPoint::End => tr!("dimension_length.end_point"), + DimensionFixedPoint::Center => tr!("dimension_length.center"), + } +} + +/// One Properties field exists at a time; a fixed ID lets shortcuts and tests +/// address its keyboard focus. +pub(super) fn field_id() -> egui::Id { + egui::Id::unique("dimension_length/value") +} + +impl BenchUpApp { + /// The single selected linear dimension, when it can drive geometry. The + /// Dimensions tool selects each dimension it places, so the field is ready + /// right away; other measuring tools and unfinished placements hide it. + pub(super) fn selected_length_dimension(&self) -> Option { + let placing = self.measurement.as_ref().is_some_and(|m| !m.points.is_empty()); + let measuring = self.tool.is_measuring() && (self.tool != Tool::Dimensions || placing); + if measuring || self.selected.len() != 1 { + return None; + } + let id = *self.selected.first()?; + self.doc + .model + .dimensions + .get(&id) + .filter(|dimension| dimension.vertex.is_none()) + .map(|dimension| dimension.id) + } + + pub(super) fn dimension_length_inspector(&mut self, ui: &mut egui::Ui) { + let Some(id) = self.selected_length_dimension() else { + self.dimension_length_input = Default::default(); + return; + }; + let current = self.doc.model.dimensions[&id].length(&self.doc.model); + let formatted = self.doc.display.units.format_length(current); + let field_id = field_id(); + let focused = ui.memory(|memory| memory.has_focus(field_id)); + let input = &mut self.dimension_length_input; + if input.dimension != Some(id) || (!focused && input.shown != formatted) { + *input = DimensionLengthInput { + dimension: Some(id), + shown: formatted.clone(), + text: formatted.clone(), + }; + } + let locked = self.doc.model.selection_locked(&self.selected); + let mut submit = false; + let response = crate::inspector_table::inspector_field( + ui, + "dimension_length/value", + tr!("app.length"), + |ui| { + ui.add_enabled( + !locked, + egui::TextEdit::singleline(&mut self.dimension_length_input.text) + .id(field_id) + .desired_width(f32::INFINITY), + ) + }, + ); + if response.lost_focus() && ui.input(|input| input.key_pressed(Key::Enter)) { + submit = true; + } + crate::inspector_table::inspector_field( + ui, + "dimension_length/fixed_point", + tr!("dimension_length.keep_fixed"), + |ui| { + egui::ComboBox::from_id_salt("dimension_length/fixed_point") + .width(ui.available_width()) + .selected_text(fixed_point_label(self.dimension_fixed_point)) + .show_ui(ui, |ui| { + for fixed in DimensionFixedPoint::ALL { + ui.selectable_value( + &mut self.dimension_fixed_point, + fixed, + fixed_point_label(fixed), + ); + } + }) + .response + .on_hover_text(tr!("dimension_length.keep_fixed_hint")) + }, + ); + let changed = self.dimension_length_input.text.trim() != formatted; + if ui + .add_enabled( + !locked && changed, + egui::Button::new(tr!("dimension_length.apply")) + .min_size(egui::vec2(ui.available_width(), ui.spacing().interact_size.y)), + ) + .clicked() + { + submit = true; + } + ui.text_weak(tr!("dimension_length.resize_hint")); + if submit && changed && !locked { + self.apply_dimension_length(id, ui.ctx()); + } + let mut fixed = self.doc.model.dimensions.get(&id).is_some_and(|d| d.fixed); + if ui + .add_enabled(!locked, egui::Checkbox::new(&mut fixed, tr!("dimension_length.fix_length"))) + .on_hover_text(tr!("dimension_length.fix_length_hint")) + .changed() + { + self.set_dimension_fixed(id, fixed, ui.ctx()); + } + ui.add_space(8.); + } + + pub(super) fn set_dimension_fixed(&mut self, id: u64, fixed: bool, ctx: &egui::Context) { + let before = self.doc.model.clone(); + match self.doc.model.set_dimension_fixed(id, fixed) { + Ok(()) => self.finish_edit( + if fixed { tr!("dimension_length.fix_dimension") } else { tr!("dimension_length.free_dimension") }, + before, + ctx, + ), + Err(message) => { + self.doc.model = before; + self.warn(ctx, message); + } + } + } + + /// Why an edit from `before` to the current model must be refused: it + /// changes a fixed dimension other than the one being typed into. + pub(super) fn fixed_dimension_block(&self, before: &Model) -> Option { + let id = self.doc.model.changed_fixed_dimension(before, self.driving_dimension)?; + let length = before.dimensions[&id].length(before); + Some(tr!( + "dimension_length.a_fixed_dimension_holds_this_size", + length = self.doc.display.units.format_length(length) + )) + } + + pub(super) fn apply_dimension_length(&mut self, id: u64, ctx: &egui::Context) { + let text = self.dimension_length_input.text.clone(); + let length = match precision::positive_length(&text, self.doc.display.units.length) { + Ok(length) => length, + Err(message) => { + self.warn(ctx, message); + return; + } + }; + let before = self.doc.model.clone(); + match self + .doc + .model + .set_dimension_length(id, length, self.dimension_fixed_point) + { + Ok(()) => { + // The typed dimension may change its own length; others stay fixed. + self.driving_dimension = Some(id); + self.finish_edit(tr!("dimension_length.resize_from_dimension"), before, ctx); + self.driving_dimension = None; + // Show the value the model reached, in display units. + self.dimension_length_input.dimension = None; + } + Err(message) => { + self.doc.model = before; + self.warn(ctx, message); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_ui::ContextExt as _; + + fn board_with_length_dimension(app: &mut BenchUpApp) -> u64 { + let model = &mut app.doc.model; + let points = [DVec3::ZERO, DVec3::X * 0.6, DVec3::new(0.6, 0.3, 0.), DVec3::Y * 0.3]; + for i in 0..4 { + model.add_edge(points[i], points[(i + 1) % 4]).unwrap(); + } + let face = *model.faces.keys().next_back().unwrap(); + model.push_pull_along(face, DVec3::Z * 0.018).unwrap(); + model.add_dimension(DVec3::ZERO, DVec3::X * 0.6, -DVec3::Y * 0.05).unwrap() + } + + fn x_extent(model: &Model) -> f64 { + let xs: Vec<_> = model.vertices.values().map(|v| v.position.x).collect(); + xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max) + - xs.iter().cloned().fold(f64::INFINITY, f64::min) + } + + #[test] + fn typed_length_resizes_the_board_as_one_undoable_edit() { + let ctx = egui::Context::default(); + let mut app = BenchUpApp::with_document(Document::default(), None, true); + let id = board_with_length_dimension(&mut app); + app.selected = BTreeSet::from([id]); + assert_eq!(app.selected_length_dimension(), Some(id)); + let _ = ctx.run_test_ui(egui::RawInput::default(), |ui| app.dimension_length_inspector(ui)); + assert_eq!(app.dimension_length_input.dimension, Some(id)); + let original = app.doc.model.clone(); + + app.dimension_length_input.text = "800mm".into(); + app.apply_dimension_length(id, &ctx); + + assert!((x_extent(&app.doc.model) - 0.8).abs() < 1e-7); + assert!(!app.doc.history.is_empty()); + assert_eq!(app.selected, BTreeSet::from([id])); + // The field shows the reached value again on the next frame. + let _ = ctx.run_test_ui(egui::RawInput::default(), |ui| app.dimension_length_inspector(ui)); + assert_eq!( + app.dimension_length_input.text, + app.doc.display.units.format_length(0.8) + ); + app.undo(&ctx, false); + assert!((x_extent(&app.doc.model) - 0.6).abs() < 1e-7); + assert!(app.doc.model.same_scene_geometry(&original)); + } + + #[test] + fn invalid_lengths_report_errors_without_editing() { + let ctx = egui::Context::default(); + let mut app = BenchUpApp::with_document(Document::default(), None, true); + let id = board_with_length_dimension(&mut app); + app.selected = BTreeSet::from([id]); + let before = app.doc.model.clone(); + for text in ["", "abc", "-5mm", "0"] { + app.dimension_length_input.text = text.into(); + app.apply_dimension_length(id, &ctx); + assert_eq!(app.doc.model, before, "{text}"); + } + assert!(app.doc.history.is_empty()); + } + + #[test] + fn measuring_tools_and_angle_dimensions_do_not_offer_the_field() { + let mut app = BenchUpApp::with_document(Document::default(), None, true); + let id = board_with_length_dimension(&mut app); + let angle = app + .doc + .model + .add_angular_dimension(DVec3::ZERO, DVec3::X * 0.6, DVec3::Y * 0.3) + .unwrap(); + app.selected = BTreeSet::from([angle]); + assert_eq!(app.selected_length_dimension(), None); + app.selected = BTreeSet::from([id]); + // The Dimensions tool keeps the field available between placements… + app.set_tool(Tool::Dimensions); + app.selected = BTreeSet::from([id]); + assert_eq!(app.selected_length_dimension(), Some(id)); + // …but not while a new dimension is being placed. + app.measurement = Some(measurement_tools::Measurement { + points: vec![DVec3::ZERO], + ..Default::default() + }); + assert_eq!(app.selected_length_dimension(), None); + app.set_tool(Tool::TapeMeasure); + app.selected = BTreeSet::from([id]); + assert_eq!(app.selected_length_dimension(), None); + } +} diff --git a/crates/benchup-app/src/measurement_tools.rs b/crates/benchup-app/src/measurement_tools.rs index a6a0f21..c24a53c 100644 --- a/crates/benchup-app/src/measurement_tools.rs +++ b/crates/benchup-app/src/measurement_tools.rs @@ -299,6 +299,9 @@ impl BenchUpApp { self.plane_lock(), ) { Ok(id) => { + // A dimension placed with the tool holds its size, like a + // CAD constraint. Properties can free it. + let _ = self.doc.model.set_dimension_fixed(id, true); self.measurement = None; self.snap = None; self.selected = BTreeSet::from([id]); @@ -415,6 +418,7 @@ impl BenchUpApp { axis: self.single_axis_lock(), plane: self.plane_lock(), vertex: None, + fixed: false, }) } pub(super) fn measurement_value(&self) -> Option { diff --git a/crates/benchup-app/src/sidebar.rs b/crates/benchup-app/src/sidebar.rs index a65db6e..50f7da9 100644 --- a/crates/benchup-app/src/sidebar.rs +++ b/crates/benchup-app/src/sidebar.rs @@ -164,6 +164,7 @@ struct ToolPreferences { walk_sitting: bool, axis_lock: Option, second_axis_lock: Option, + dimension_fixed_point: benchup_core::DimensionFixedPoint, } #[cfg(test)] @@ -201,6 +202,29 @@ mod guide_preference_tests { } } + #[test] + fn dimension_fixed_point_defaults_and_saves_without_a_model_edit() { + use benchup_core::DimensionFixedPoint; + let legacy: InspectorPreferences = + serde_json::from_str(r#"{"tools":{"active":"select"}}"#).unwrap(); + assert_eq!(legacy.tools.dimension_fixed_point, DimensionFixedPoint::Start); + let ctx = egui::Context::default(); + let mut app = BenchUpApp::with_document(Document::default(), None, true); + let mut storage = Storage::default(); + for fixed in [DimensionFixedPoint::Center, DimensionFixedPoint::End, DimensionFixedPoint::Start] { + storage.flushed = false; + app.dimension_fixed_point = fixed; + app.persist_inspector_changes(&ctx, Some(&mut storage), false); + assert!(storage.flushed); + assert!(!app.project.modified); + assert!(app.dirty_since.is_none()); + assert!(app.doc.history.is_empty()); + let mut restored = BenchUpApp::with_document(Document::default(), None, true); + restored.restore_inspector_preferences(&egui::Context::default(), Some(&storage)); + assert_eq!(restored.dimension_fixed_point, fixed); + } + } + #[test] fn tool_rail_separators_default_and_restore_without_model_edits() { let legacy: InspectorPreferences = serde_json::from_str("{}").unwrap(); @@ -600,6 +624,7 @@ impl Default for ToolPreferences { walk_sitting: false, axis_lock: None, second_axis_lock: None, + dimension_fixed_point: Default::default(), } } } @@ -618,6 +643,7 @@ impl ToolPreferences { walk_sitting: app.walk.sitting, axis_lock: app.lock, second_axis_lock: app.second_lock, + dimension_fixed_point: app.dimension_fixed_point, } } @@ -649,6 +675,7 @@ impl ToolPreferences { app.move_copy = self.move_copy; app.create_guides = self.create_guides; app.walk.sitting = self.walk_sitting; + app.dimension_fixed_point = self.dimension_fixed_point; app.lock = self.axis_lock; app.second_lock = self.second_axis_lock .filter(|axis| self.axis_lock.is_some_and(|first| first != *axis)); diff --git a/crates/benchup-core/src/dimension_stretch.rs b/crates/benchup-core/src/dimension_stretch.rs new file mode 100644 index 0000000..147c7dc --- /dev/null +++ b/crates/benchup-core/src/dimension_stretch.rs @@ -0,0 +1,331 @@ +//! Driving dimensions: typing a new value into a linear dimension resizes or +//! moves the geometry it measures. +//! +//! When both ends are attached to the same connected piece, the piece is +//! stretched: vertices beyond the plane halfway between the two ends move +//! along the dimension, so a board gets longer without changing its thickness. +//! When the ends belong to different pieces, the moving piece is translated. +use crate::{DVec3, Model, document::EPS}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +/// The point of a linear dimension that stays in place when its value changes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DimensionFixedPoint { + /// The first endpoint chosen when the dimension was created. + #[default] + Start, + /// The second endpoint chosen when the dimension was created. + End, + /// Both ends move by half of the change. + Center, +} + +impl DimensionFixedPoint { + pub const ALL: [Self; 3] = [Self::Start, Self::End, Self::Center]; +} + +/// Geometry that one end of the dimension is attached to. +struct Side { + /// The object whose direct geometry contains the anchor, or `None` for + /// loose geometry at the model root. + owner: Option, + /// Vertices connected to the anchor through edges of the same owner. + piece: BTreeSet, +} + +impl Model { + /// Set a linear dimension to `length` by stretching or moving the geometry + /// it is attached to. The change is atomic: on error the model is unchanged. + pub fn set_dimension_length( + &mut self, + id: u64, + length: f64, + fixed: DimensionFixedPoint, + ) -> Result<(), &'static str> { + let dimension = self + .dimensions + .get(&id) + .ok_or(tr!("core.dimension_stretch.the_dimension_no_longer_exists"))? + .clone(); + if dimension.vertex.is_some() { + return Err(tr!("core.dimension_stretch.angle_dimensions_cannot_resize_geometry")); + } + if !length.is_finite() || length < EPS || length > 1e7 { + return Err(tr!("core.dimension_stretch.enter_a_positive_length")); + } + let current = dimension.length(self); + let change = length - current; + if change.abs() < EPS { + return Ok(()); + } + let (a, b) = dimension.points(self); + let direction = dimension.line_direction(self); + // Unit vector pointing from the start toward the end of the dimension. + let toward_end = if (b - a).dot(direction) < 0. { -direction } else { direction }; + let (start_shift, end_shift) = match fixed { + DimensionFixedPoint::Start => (0., change), + DimensionFixedPoint::End => (-change, 0.), + DimensionFixedPoint::Center => (-change * 0.5, change * 0.5), + }; + + let parents = self.parent_map(); + let side = |anchor: &crate::DimensionAnchor| -> Option { + let vertex = anchor.weights.first()?.0; + let owner = self.vertex_owner(vertex, &parents)?; + let mut piece = self.connected_vertices( + anchor.weights.iter().map(|(id, _)| *id), + owner, + &parents, + ); + piece.extend(anchor.weights.iter().map(|(id, _)| *id)); + Some(Side { owner: owner.copied(), piece }) + }; + let start = side(&dimension.start); + let end = side(&dimension.end); + let detached = tr!("core.dimension_stretch.attach_the_moving_end_to_geometry"); + if start_shift != 0. && start.is_none() || end_shift != 0. && end.is_none() { + return Err(detached); + } + + let mut next = self.clone(); + match (&start, &end) { + (Some(s), Some(e)) if s.owner == e.owner && !s.piece.is_disjoint(&e.piece) => { + // Both ends on one piece: stretch it about the midpoint. + let middle = (a + b) * 0.5; + let moves = stretch_moves( + self, + &e.piece, + middle, + toward_end, + start_shift, + end_shift, + )?; + next.in_scope(e.owner, |model| model.shift_vertices(&moves))?; + } + _ => { + for (side, shift) in [(&start, start_shift), (&end, end_shift)] { + let Some(side) = side.as_ref().filter(|_| shift != 0.) else { + continue; + }; + next.move_piece(side, &start, &end, toward_end * shift)?; + } + } + } + let reached = next + .dimensions + .get(&id) + .map(|d| d.length(&next)) + .is_some_and(|value| (value - length).abs() <= 1e-6_f64.max(length * 1e-9)); + if !reached { + return Err(tr!("core.dimension_stretch.this_dimension_cannot_resize_its_geometry")); + } + if next.changed_fixed_dimension(self, Some(id)).is_some() { + return Err(tr!("core.dimension_stretch.another_fixed_dimension_holds_this_size")); + } + next.edit_context = self.edit_context; + *self = next; + Ok(()) + } + + /// The first fixed linear dimension, other than `except`, whose length + /// differs from the one it had in `before`. A dimension with an end that + /// is not attached to geometry in either model holds nothing. + pub fn changed_fixed_dimension(&self, before: &Model, except: Option) -> Option { + let holds = |d: &crate::Dimension| { + d.fixed && d.vertex.is_none() && !d.start.weights.is_empty() && !d.end.weights.is_empty() + }; + self.dimensions + .values() + .filter(|d| Some(d.id) != except && holds(d)) + .find(|d| { + before.dimensions.get(&d.id).is_some_and(|old| { + holds(old) && (old.length(before) - d.length(self)).abs() > 1e-6 + }) + }) + .map(|d| d.id) + } + + /// Fix or free a linear dimension's length. + pub fn set_dimension_fixed(&mut self, id: u64, fixed: bool) -> Result<(), &'static str> { + if self.edit_context.is_some() && self.parent(id).is_some() { + return self.edit_in_context(|model| model.set_dimension_fixed(id, fixed)); + } + let dimension = self + .dimensions + .get_mut(&id) + .ok_or(tr!("core.dimension_stretch.the_dimension_no_longer_exists"))?; + if dimension.vertex.is_some() { + return Err(tr!("core.dimension_stretch.angle_dimensions_cannot_resize_geometry")); + } + dimension.fixed = fixed; + Ok(()) + } + + /// Translate the piece on one side of a dimension whose ends belong to + /// different pieces. A whole object moves when it is the anchor's owner and + /// does not also contain the other end. + fn move_piece( + &mut self, + side: &Side, + start: &Option, + end: &Option, + delta: DVec3, + ) -> Result<(), &'static str> { + let other_owners: Vec<_> = [start, end] + .into_iter() + .flatten() + .filter(|other| !std::ptr::eq(*other, side)) + .map(|other| other.owner) + .collect(); + if let Some(object) = side.owner + && other_owners + .iter() + .all(|owner| owner.is_none_or(|owner| !self.is_ancestor_or_self(object, owner))) + { + let scope = self.parent(object); + let selection = BTreeSet::from([object]); + return self.in_scope(scope, |model| model.move_selection(&selection, delta)); + } + let moves = side.piece.iter().map(|id| (*id, delta)).collect(); + self.in_scope(side.owner, |model| model.shift_vertices(&moves)) + } + + /// Run `operation` with `scope` as the editing context, so edits inside a + /// component instance also update its linked peers. + fn in_scope( + &mut self, + scope: Option, + operation: impl FnOnce(&mut Model) -> Result, + ) -> Result { + let saved = self.edit_context; + let mut next = self.clone(); + next.edit_context = scope; + let result = match scope { + Some(_) => next.edit_in_context(operation), + None => operation(&mut next), + }?; + next.edit_context = saved; + *self = next; + Ok(result) + } + + /// Displace individual vertices in the current scope, then validate. + fn shift_vertices(&mut self, moves: &BTreeMap) -> Result<(), &'static str> { + if moves.is_empty() { + return Ok(()); + } + let touches_locked = self.edges.values().any(|edge| { + (moves.contains_key(&edge.a) || moves.contains_key(&edge.b)) && self.is_locked(edge.id) + }); + if touches_locked { + return Err(tr!("core.modeling.unlock_the_connected_geometry_before_editing_it")); + } + let mut next = self.clone(); + for (id, delta) in moves { + let vertex = next + .vertices + .get_mut(id) + .ok_or(tr!("core.dimension_stretch.this_dimension_cannot_resize_its_geometry"))?; + vertex.position += *delta; + } + next.sync_dimensions(); + next.validate() + .map_err(|_| tr!("core.modeling.this_change_would_collapse_an_edge_or_bend"))?; + *self = next; + Ok(()) + } + + fn parent_map(&self) -> BTreeMap { + self.objects + .values() + .flat_map(|object| object.entities.iter().map(|id| (*id, object.id))) + .collect() + } + + /// The owner of a vertex's edges: `Some(None)` for root geometry. + fn vertex_owner<'a>( + &self, + vertex: u64, + parents: &'a BTreeMap, + ) -> Option> { + self.edges + .values() + .find(|edge| edge.a == vertex || edge.b == vertex) + .map(|edge| parents.get(&edge.id)) + } + + /// Vertices reachable from `seeds` through edges directly owned by `owner`. + fn connected_vertices( + &self, + seeds: impl IntoIterator, + owner: Option<&u64>, + parents: &BTreeMap, + ) -> BTreeSet { + let mut neighbors: BTreeMap> = BTreeMap::new(); + for edge in self.edges.values().filter(|edge| parents.get(&edge.id) == owner) { + neighbors.entry(edge.a).or_default().push(edge.b); + neighbors.entry(edge.b).or_default().push(edge.a); + } + let mut found = BTreeSet::new(); + let mut pending: Vec<_> = seeds.into_iter().collect(); + while let Some(id) = pending.pop() { + if found.insert(id) { + pending.extend(neighbors.get(&id).into_iter().flatten().copied()); + } + } + found + } + + fn is_ancestor_or_self(&self, ancestor: u64, mut id: u64) -> bool { + loop { + if id == ancestor { + return true; + } + match self.parent(id) { + Some(parent) => id = parent, + None => return false, + } + } + } +} + +/// Vertex displacements that stretch one piece about a plane through `middle`. +/// Rejects shortening that would push vertices past ones that stay behind. +fn stretch_moves( + model: &Model, + piece: &BTreeSet, + middle: DVec3, + toward_end: DVec3, + start_shift: f64, + end_shift: f64, +) -> Result, &'static str> { + let mut moves = BTreeMap::new(); + // Furthest extents after the change, per group: (start side, middle, end side). + let mut start_max = f64::NEG_INFINITY; + let mut end_min = f64::INFINITY; + let mut middle_range = (f64::INFINITY, f64::NEG_INFINITY); + for id in piece { + let t = (model.vertices[id].position - middle).dot(toward_end); + if t > EPS { + end_min = end_min.min(t + end_shift); + if end_shift != 0. { + moves.insert(*id, toward_end * end_shift); + } + } else if t < -EPS { + start_max = start_max.max(t + start_shift); + if start_shift != 0. { + moves.insert(*id, toward_end * start_shift); + } + } else { + middle_range = (middle_range.0.min(t), middle_range.1.max(t)); + } + } + let lowest_after_start = middle_range.0.min(end_min); + let highest_before_end = middle_range.1.max(start_max); + if end_min <= highest_before_end + EPS || start_max >= lowest_after_start - EPS { + return Err(tr!("core.dimension_stretch.that_length_would_fold_the_geometry")); + } + Ok(moves) +} diff --git a/crates/benchup-core/src/dimension_stretch_tests.rs b/crates/benchup-core/src/dimension_stretch_tests.rs new file mode 100644 index 0000000..318dcbf --- /dev/null +++ b/crates/benchup-core/src/dimension_stretch_tests.rs @@ -0,0 +1,359 @@ +use crate::{DVec3, DimensionFixedPoint, Model}; +use std::collections::BTreeSet; + +const LENGTH: f64 = 0.6; +const WIDTH: f64 = 0.3; +const THICKNESS: f64 = 0.018; + +/// A 600 × 300 × 18 mm board as loose geometry starting at `origin`. +fn board(model: &mut Model, origin: DVec3) { + let points = [ + origin, + origin + DVec3::X * LENGTH, + origin + DVec3::new(LENGTH, WIDTH, 0.), + origin + DVec3::Y * WIDTH, + ]; + for i in 0..4 { + model.add_edge(points[i], points[(i + 1) % 4]).unwrap(); + } + let face = *model.faces.keys().next_back().unwrap(); + model.push_pull_along(face, DVec3::Z * THICKNESS).unwrap(); +} + +fn x_range(model: &Model) -> (f64, f64) { + model.vertices.values().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| { + (lo.min(v.position.x), hi.max(v.position.x)) + }) +} + +fn extent(model: &Model, axis: fn(DVec3) -> f64) -> f64 { + let values: Vec<_> = model.vertices.values().map(|v| axis(v.position)).collect(); + values.iter().cloned().fold(f64::NEG_INFINITY, f64::max) + - values.iter().cloned().fold(f64::INFINITY, f64::min) +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-7 +} + +#[test] +fn length_dimension_stretches_a_board_from_each_fixed_point() { + for (fixed, expected) in [ + (DimensionFixedPoint::Start, (0., 0.8)), + (DimensionFixedPoint::End, (-0.2, 0.6)), + (DimensionFixedPoint::Center, (-0.1, 0.7)), + ] { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let dimension = model + .add_dimension(DVec3::ZERO, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + let topology = (model.vertices.len(), model.edges.len(), model.faces.len()); + + model.set_dimension_length(dimension, 0.8, fixed).unwrap(); + + let (lo, hi) = x_range(&model); + assert!(close(lo, expected.0) && close(hi, expected.1), "{fixed:?}: {lo} {hi}"); + assert!(close(model.dimensions[&dimension].length(&model), 0.8)); + // Stretching keeps the thickness and width and adds no topology. + assert!(close(extent(&model, |p| p.z), THICKNESS)); + assert!(close(extent(&model, |p| p.y), WIDTH)); + assert_eq!(topology, (model.vertices.len(), model.edges.len(), model.faces.len())); + model.validate().unwrap(); + } +} + +#[test] +fn shortening_a_board_keeps_it_valid_until_it_would_fold() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let dimension = model + .add_dimension(DVec3::ZERO, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + model + .set_dimension_length(dimension, 0.1, DimensionFixedPoint::Start) + .unwrap(); + let (lo, hi) = x_range(&model); + assert!(close(lo, 0.) && close(hi, 0.1)); + model.validate().unwrap(); + + // A dimension spanning part of the board cannot be shortened past the + // vertices that stay behind. + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let partial = model + .add_dimension(DVec3::X * 0.1, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + let before = model.clone(); + assert!(model + .set_dimension_length(partial, 0.01, DimensionFixedPoint::Start) + .is_err()); + assert_eq!(model, before); +} + +#[test] +fn width_and_thickness_dimensions_drive_their_own_axes() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let width = model + .add_dimension(DVec3::ZERO, DVec3::Y * WIDTH, -DVec3::X * 0.05) + .unwrap(); + let thickness = model + .add_dimension(DVec3::ZERO, DVec3::Z * THICKNESS, -DVec3::X * 0.05) + .unwrap(); + model.set_dimension_length(width, 0.4, DimensionFixedPoint::Start).unwrap(); + model.set_dimension_length(thickness, 0.019, DimensionFixedPoint::Start).unwrap(); + assert!(close(extent(&model, |p| p.x), LENGTH)); + assert!(close(extent(&model, |p| p.y), 0.4)); + assert!(close(extent(&model, |p| p.z), 0.019)); + model.validate().unwrap(); +} + +#[test] +fn stretching_a_component_instance_updates_its_linked_peers() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let component = model + .make_object(&model.selectable_entities(), true, "Board") + .unwrap(); + let clipboard = model.copy_entities(&BTreeSet::from([component])); + let peer = *model.paste_entities(&clipboard, DVec3::Y * 2.).first().unwrap(); + let dimension = model + .add_dimension(DVec3::ZERO, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + + model + .set_dimension_length(dimension, 0.75, DimensionFixedPoint::Start) + .unwrap(); + + for id in [component, peer] { + let contents = model.object_contents(id).unwrap(); + assert!(close(extent(&contents, |p| p.x), 0.75), "object {id}"); + assert!(close(extent(&contents, |p| p.z), THICKNESS)); + } + assert!(close(model.dimensions[&dimension].length(&model), 0.75)); + assert_eq!(model.edit_context, None); + model.validate().unwrap(); +} + +#[test] +fn dimension_between_two_groups_moves_the_free_group() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let first = model + .make_object(&model.selectable_entities(), false, "Left") + .unwrap(); + board(&mut model, DVec3::X * 1.); + let loose = model.selectable_entities(); + let loose: BTreeSet<_> = loose.into_iter().filter(|id| *id != first).collect(); + let second = model.make_object(&loose, false, "Right").unwrap(); + // From the left board's right end to the right board's left end. + let gap = model + .add_dimension(DVec3::X * LENGTH, DVec3::X * 1., -DVec3::Y * 0.05) + .unwrap(); + let left_before = model.object_contents(first).unwrap(); + + model + .set_dimension_length(gap, 0.5, DimensionFixedPoint::Start) + .unwrap(); + + assert_eq!(model.object_contents(first).unwrap().vertices, left_before.vertices); + let right = model.object_contents(second).unwrap(); + assert!(close(x_range(&right).0, 1.1)); + assert!(close(extent(&right, |p| p.x), LENGTH)); + assert!(close(model.dimensions[&gap].length(&model), 0.5)); + model.validate().unwrap(); +} + +#[test] +fn invalid_requests_leave_the_model_unchanged() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let dimension = model + .add_dimension(DVec3::ZERO, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + let floating = model + .add_dimension(DVec3::new(5., 5., 5.), DVec3::new(6., 5., 5.), DVec3::Y) + .unwrap(); + let angle = model + .add_angular_dimension(DVec3::ZERO, DVec3::X * LENGTH, DVec3::Y * WIDTH) + .unwrap(); + let before = model.clone(); + for (id, length) in [ + (dimension, 0.), + (dimension, -1.), + (dimension, f64::NAN), + (floating, 2.), + (angle, 1.), + (u64::MAX, 1.), + ] { + assert!(model + .set_dimension_length(id, length, DimensionFixedPoint::Start) + .is_err()); + assert_eq!(model, before); + } + // Unchanged values are accepted without editing the model. + model + .set_dimension_length(dimension, LENGTH, DimensionFixedPoint::Center) + .unwrap(); + assert_eq!(model, before); +} + +#[test] +fn locked_geometry_cannot_be_stretched() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let group = model + .make_object(&model.selectable_entities(), false, "Board") + .unwrap(); + model.locked.insert(group); + let dimension = model + .add_dimension(DVec3::ZERO, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + let before = model.clone(); + assert!(model + .set_dimension_length(dimension, 0.8, DimensionFixedPoint::Start) + .is_err()); + assert_eq!(model, before); +} + +#[test] +fn stretched_geometry_stays_editable_after_the_dimension_is_erased() { + // Loose board, then a board inside a group (edited in context). + for grouped in [false, true] { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let group = grouped.then(|| { + model.make_object(&model.selectable_entities(), false, "Board").unwrap() + }); + let dimension = model + .add_dimension(DVec3::ZERO, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + model + .set_dimension_length(dimension, 0.8, DimensionFixedPoint::Start) + .unwrap(); + model.erase(&BTreeSet::from([dimension])); + assert!(model.dimensions.is_empty()); + if let Some(group) = group { + assert!(model.enter_object(group)); + } + let top = model + .faces + .values() + .find(|face| { + face.vertices + .iter() + .all(|id| (model.vertices[id].position.z - THICKNESS).abs() < 1e-7) + }) + .unwrap() + .id; + let result = model.push_pull(top, 0.01); + assert!(result.is_ok(), "grouped={grouped}: {result:?}"); + assert!(close(extent(&model, |p| p.z), THICKNESS + 0.01)); + model.validate().unwrap(); + } +} + +#[test] +fn every_face_of_a_stretched_cube_can_be_pushed_and_pulled() { + use crate::Axis; + for axis in [None, Some(Axis::X)] { + for erase in [false, true] { + for side in 0..6 { + let mut model = Model::default(); + let points = [DVec3::ZERO, DVec3::X, DVec3::new(1., 1., 0.), DVec3::Y]; + for i in 0..4 { + model.add_edge(points[i], points[(i + 1) % 4]).unwrap(); + } + let face = *model.faces.keys().next_back().unwrap(); + model.push_pull_along(face, DVec3::Z).unwrap(); + let dimension = model + .add_dimension_with_axis(DVec3::ZERO, DVec3::X, -DVec3::Y, axis) + .unwrap(); + model + .set_dimension_length(dimension, 2., DimensionFixedPoint::Start) + .unwrap(); + if erase { + model.erase(&BTreeSet::from([dimension])); + } + let mut faces: Vec<_> = model.faces.keys().copied().collect(); + faces.sort(); + let face = faces[side]; + let before = model.clone(); + let result = model.push_pull(face, 0.25); + assert!( + result.is_ok(), + "axis={axis:?} erase={erase} face#{side}: {result:?}" + ); + model.validate().unwrap(); + let _ = before; + } + } + } +} + +#[test] +fn fixed_dimensions_report_changes_and_survive_serialization() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + let length = model + .add_dimension(DVec3::ZERO, DVec3::X * LENGTH, -DVec3::Y * 0.05) + .unwrap(); + assert!(!model.dimensions[&length].fixed, "dimensions start free"); + model.set_dimension_fixed(length, true).unwrap(); + // Older documents without the field load as free dimensions. + let json = serde_json::to_string(&model.dimensions[&length]).unwrap(); + assert!(json.contains("\"fixed\":true")); + let legacy: crate::Dimension = serde_json::from_str(&json.replace(",\"fixed\":true", "")).unwrap(); + assert!(!legacy.fixed); + + let before = model.clone(); + let mut pulled = model.clone(); + let end = *pulled + .faces + .iter() + .find(|(_, f)| f.vertices.iter().all(|id| (pulled.vertices[id].position.x - LENGTH).abs() < 1e-7)) + .unwrap() + .0; + pulled.push_pull(end, 0.1).unwrap(); + assert_eq!(pulled.changed_fixed_dimension(&before, None), Some(length)); + assert_eq!(pulled.changed_fixed_dimension(&before, Some(length)), None); + + let mut top = model.clone(); + let face = *top + .faces + .iter() + .find(|(_, f)| f.vertices.iter().all(|id| (top.vertices[id].position.z - THICKNESS).abs() < 1e-7)) + .unwrap() + .0; + top.push_pull(face, 0.01).unwrap(); + assert_eq!(top.changed_fixed_dimension(&before, None), None, "other sizes stay editable"); + + model.set_dimension_fixed(length, false).unwrap(); + assert_eq!(pulled.changed_fixed_dimension(&model, None), None); +} + +#[test] +fn driving_one_dimension_respects_other_fixed_dimensions() { + let mut model = Model::default(); + board(&mut model, DVec3::ZERO); + board(&mut model, DVec3::X); + // A fixed gap between the boards, and the right board's length. + let gap = model + .add_dimension(DVec3::X * LENGTH, DVec3::X, -DVec3::Y * 0.1) + .unwrap(); + let length = model + .add_dimension(DVec3::X, DVec3::X * (1. + LENGTH), -DVec3::Y * 0.05) + .unwrap(); + model.set_dimension_fixed(gap, true).unwrap(); + model.set_dimension_fixed(length, true).unwrap(); + // Moving the far end leaves the gap unchanged… + model.set_dimension_length(length, 0.8, DimensionFixedPoint::Start).unwrap(); + assert!(close(model.dimensions[&gap].length(&model), 0.4)); + // …while moving the near end would close the gap, so it is refused atomically. + let before = model.clone(); + assert!(model + .set_dimension_length(length, 0.9, DimensionFixedPoint::End) + .is_err()); + assert_eq!(model, before); +} diff --git a/crates/benchup-core/src/lib.rs b/crates/benchup-core/src/lib.rs index 578405e..6462a55 100644 --- a/crates/benchup-core/src/lib.rs +++ b/crates/benchup-core/src/lib.rs @@ -11,6 +11,7 @@ mod cleanup; pub mod annotations; pub mod camera; mod csg; +pub mod dimension_stretch; pub mod display; pub mod document; pub mod edit_context; @@ -33,6 +34,7 @@ pub mod units; pub use annotations::TextAnnotation; pub use guides::ConstructionGuide; pub use camera::{Camera, CameraView, Projection, Ray, StandardView}; +pub use dimension_stretch::DimensionFixedPoint; pub use display::{DisplaySettings, FaceStyle}; pub use document::{Document, DocumentCheckpoint, Edge, Face, History, Model, Vertex}; pub use edit_context::InstanceTransform; @@ -50,6 +52,8 @@ pub use units::{AngleUnit, AreaUnit, LengthUnit, UnitPrecision, UnitSettings, Vo #[cfg(test)] mod annotation_tests; #[cfg(test)] +mod dimension_stretch_tests; +#[cfg(test)] mod edit_context_tests; #[cfg(test)] mod measurement_tests; diff --git a/crates/benchup-core/src/measurements.rs b/crates/benchup-core/src/measurements.rs index 6781499..e62f760 100644 --- a/crates/benchup-core/src/measurements.rs +++ b/crates/benchup-core/src/measurements.rs @@ -71,6 +71,10 @@ pub struct Dimension { /// Measure the separation projected onto this world plane. #[serde(default, skip_serializing_if = "Option::is_none")] pub plane: Option, + /// A fixed linear dimension holds its length: edits that would change it + /// are refused. Absent (free) in older documents. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub fixed: bool, } impl Dimension { pub fn anchors(&self) -> impl Iterator { @@ -341,6 +345,7 @@ impl Model { axis, plane, vertex: None, + fixed: false, }; if dimension.layout(self).iter().any(|p| !valid_point(*p)) { return Err(tr!( @@ -436,6 +441,7 @@ impl Model { * 0.3, axis: None, plane: None, + fixed: false, }; if dimension .annotation_points(self)