fix(blocks): preserve UCS transformations

Bake BEDIT frames into block-local geometry while keeping model and viewport UCS isolated. Normalize legacy nonzero block origins during load.
This commit is contained in:
Hakan Seven committed 2026-07-30 19:50:33 +03:00
1 parent 02d15f5d23
commit 2c64888048
22 files changed
+693 -41

No files matched your search

+9 -1
View File
@@ -932,9 +932,17 @@ impl OpenCADStudio {
base,
} => {
self.push_undo_snapshot(i, "BLOCK");
let ucs = self.tabs[i].ucs_xform();
let world_to_block = ucs.to_ucs_transform_at(base);
let block_to_world = ucs.to_wcs_transform_at(base);
match self.tabs[i]
.scene
.create_block_from_entities(&handles, &name, base)
.create_block_from_entities(
&handles,
&name,
&world_to_block,
&block_to_world,
)
{
Ok(insert_handle) => {
self.tabs[i].dirty = true;
+51 -11
View File
@@ -406,8 +406,8 @@ impl OpenCADStudio {
)));
}
// Snapshot the block's block-local entities so Discard can restore
// them (skip structural Block/BlockEnd/AttDef, mirroring REFEDIT).
// Snapshot the complete block definition so Discard can restore
// structural markers, ATTDEFs and geometry with exact handles.
let snapshot: Vec<_> = {
let br = self.tabs[i]
.scene
@@ -418,26 +418,45 @@ impl OpenCADStudio {
br.entity_handles
.iter()
.filter_map(|h| self.tabs[i].scene.document.get_entity(*h).cloned())
.filter(|e| {
!matches!(
e,
acadrust::EntityType::Block(_)
| acadrust::EntityType::BlockEnd(_)
| acadrust::EntityType::AttributeDefinition(_)
)
})
.collect()
};
let dependent_snapshot: Vec<_> = self.tabs[i]
.scene
.block_definition_dependent_handles(br_handle)
.into_iter()
.filter_map(|handle| {
self.tabs[i].scene.document.get_entity_arc(handle)
})
.collect();
let reference_attributes: Vec<_> = self.tabs[i]
.scene
.document
.entities()
.filter_map(|entity| match entity {
acadrust::EntityType::Insert(reference)
if reference.block_name.eq_ignore_ascii_case(&insert.block_name)
&& !reference.attributes.is_empty() =>
{
Some((
reference.common.handle,
reference.attributes.clone(),
))
}
_ => None,
})
.collect();
self.push_undo_snapshot(i, "BEDIT");
// Capture the camera before the editor reframes it, so leaving
// the block editor returns the view exactly where it was (#425).
let current_camera = self.tabs[i].scene.camera.borrow().clone();
let current_ucs = self.tabs[i].active_ucs.clone();
let (return_layout, return_block, return_camera) =
if let Some(parent_index) = self.tabs[i].active_block_edit {
let parent = &mut self.tabs[i].block_edits[parent_index];
parent.editor_camera = current_camera.clone();
parent.editor_ucs = current_ucs;
(
parent.return_layout.clone(),
Some(parent.block_name.clone()),
@@ -463,10 +482,16 @@ impl OpenCADStudio {
return_layout,
return_block,
snapshot,
dependent_snapshot,
reference_attributes,
return_camera,
editor_camera: current_camera,
editor_ucs: None,
});
self.tabs[i].active_block_edit = Some(self.tabs[i].block_edits.len() - 1);
// Every BEDIT tab owns an isolated local UCS. Never inherit or
// overwrite the drawing's model-space UCS.
self.tabs[i].refresh_active_ucs();
self.tabs[i].scene.deselect_all();
// The first click of a double-click selects the model-space
@@ -574,10 +599,25 @@ impl OpenCADStudio {
let return_layout = session.return_layout.clone();
let return_camera = session.return_camera.clone();
for mut entity in session.snapshot {
entity.common_mut().handle = acadrust::Handle::NULL;
// Preserve the original handle so ATTDEF references and
// other handle-based relationships survive Discard.
entity.common_mut().owner_handle = session.br_handle;
let _ = self.tabs[i].scene.document.add_entity(entity);
}
for (handle, attributes) in session.reference_attributes {
if let Some(acadrust::EntityType::Insert(reference)) =
self.tabs[i].scene.document.get_entity_mut(handle)
{
reference.attributes = attributes;
}
}
for entity in session.dependent_snapshot {
let handle = entity.common().handle;
let _ = self.tabs[i]
.scene
.document
.replace_entity_arc(handle, entity);
}
self.restore_after_block_edit_close(
i,
return_block.as_deref(),
+10 -5
View File
@@ -186,6 +186,7 @@ impl OpenCADStudio {
use acadrust::types::Vector3;
let parts: Vec<&str> = cmd.splitn(4, ' ').collect();
let sub = parts.get(1).map(|s| s.to_uppercase()).unwrap_or_default();
let mut active_changed = false;
match sub.as_str() {
"" | "LIST" | "?" => {
let active_name = self.tabs[i]
@@ -248,6 +249,7 @@ impl OpenCADStudio {
}
"W" | "WORLD" => {
self.tabs[i].active_ucs = None;
active_changed = true;
self.command_line
.push_output("UCS reset to World Coordinate System.");
}
@@ -271,6 +273,7 @@ impl OpenCADStudio {
wcs_origin.y as f64,
wcs_origin.z as f64,
);
active_changed = true;
self.command_line.push_output(&format!(
"UCS origin set to ({:.4}, {:.4}, {:.4}).",
wcs_origin.x, wcs_origin.y, wcs_origin.z
@@ -313,6 +316,7 @@ impl OpenCADStudio {
Vector3::new(ny.x as f64, ny.y as f64, ny.z as f64);
}
self.tabs[i].active_ucs = Some(new_ucs);
active_changed = true;
self.command_line
.push_output(&format!("UCS rotated {:.2}° around Z.", angle_deg));
} else {
@@ -340,6 +344,7 @@ impl OpenCADStudio {
let rot = glam::Quat::from_axis_angle(x_ax, rad);
let ny = rot * old_y;
ucs.y_axis = Vector3::new(ny.x as f64, ny.y as f64, ny.z as f64);
active_changed = true;
self.command_line
.push_output(&format!("UCS rotated {:.2}° around X.", angle_deg));
} else {
@@ -367,6 +372,7 @@ impl OpenCADStudio {
let rot = glam::Quat::from_axis_angle(y_ax, rad);
let nx = rot * old_x;
ucs.x_axis = Vector3::new(nx.x as f64, nx.y as f64, nx.z as f64);
active_changed = true;
self.command_line
.push_output(&format!("UCS rotated {:.2}° around Y.", angle_deg));
} else {
@@ -378,6 +384,7 @@ impl OpenCADStudio {
let name = sub.clone();
if let Some(named) = self.tabs[i].scene.document.ucss.get(&name).cloned() {
self.tabs[i].active_ucs = Some(named);
active_changed = true;
self.command_line
.push_output(&format!("UCS '{}' activated.", name));
} else {
@@ -388,11 +395,9 @@ impl OpenCADStudio {
}
}
}
// Keep the scene's ViewCube UCS in lock-step with active_ucs and
// persist it to the active pane (per-viewport UCS inside a
// viewport, header model UCS in the Model tab) so it round-trips.
self.tabs[i].sync_ucs_to_scene();
self.tabs[i].persist_active_ucs();
if active_changed {
self.commit_active_ucs_change(i, "UCS");
}
}
// ── Named Views (VIEW command) ────────────────────────────────
+22 -6
View File
@@ -241,7 +241,7 @@ impl DocumentTab {
/// The document's saved model-space UCS (header), as a `Ucs`. `None` when it
/// is identity (plain WCS).
fn model_ucs_from_header(&self) -> Option<Ucs> {
pub(super) fn model_ucs_from_header(&self) -> Option<Ucs> {
let h = &self.scene.document.header;
let mut u = Ucs::new(h.model_space_ucs_name.clone());
u.origin = h.model_space_ucs_origin;
@@ -281,7 +281,9 @@ impl DocumentTab {
/// change (enter/exit viewport, layout / tab switch, load) so one field
/// drives all UCS-aware systems regardless of where editing happens.
pub(super) fn refresh_active_ucs(&mut self) {
self.active_ucs = if let Some(h) = self.scene.active_viewport {
self.active_ucs = if let Some(session) = self.active_block_edit_session() {
session.editor_ucs.clone()
} else if let Some(h) = self.scene.active_viewport {
self.ucs_from_viewport(h)
} else if self.scene.current_layout == "Model" {
self.model_ucs_from_header()
@@ -297,16 +299,28 @@ impl DocumentTab {
/// any UCS change.
pub(super) fn persist_active_ucs(&mut self) {
use acadrust::types::Vector3;
if let Some(h) = self.scene.active_viewport {
let (o, x, y, per) = match &self.active_ucs {
Some(u) => (u.origin, u.x_axis, u.y_axis, true),
None => (Vector3::ZERO, Vector3::UNIT_X, Vector3::UNIT_Y, false),
if let Some(index) = self.active_block_edit {
let active_ucs = self.active_ucs.clone();
if let Some(session) = self.block_edits.get_mut(index) {
session.editor_ucs = active_ucs;
}
} else if let Some(h) = self.scene.active_viewport {
let (o, x, y, handle, per) = match &self.active_ucs {
Some(u) => (u.origin, u.x_axis, u.y_axis, u.handle, true),
None => (
Vector3::ZERO,
Vector3::UNIT_X,
Vector3::UNIT_Y,
Handle::NULL,
false,
),
};
if let Some(acadrust::EntityType::Viewport(vp)) = self.scene.document.get_entity_mut(h)
{
vp.ucs_origin = o;
vp.ucs_x_axis = x;
vp.ucs_y_axis = y;
vp.ucs_handle = handle;
vp.ucs_per_viewport = per;
}
} else if self.scene.current_layout == "Model" {
@@ -316,11 +330,13 @@ impl DocumentTab {
h.model_space_ucs_origin = u.origin;
h.model_space_ucs_x_axis = u.x_axis;
h.model_space_ucs_y_axis = u.y_axis;
h.model_space_ucs_name = u.name.clone();
}
None => {
h.model_space_ucs_origin = Vector3::ZERO;
h.model_space_ucs_x_axis = Vector3::UNIT_X;
h.model_space_ucs_y_axis = Vector3::UNIT_Y;
h.model_space_ucs_name.clear();
}
}
}
+46 -2
View File
@@ -73,8 +73,14 @@ impl UcsXform {
pub(super) fn from_ucs(ucs: &Ucs) -> Self {
let v = |a: acadrust::types::Vector3| glam::DVec3::new(a.x, a.y, a.z);
let x = v(ucs.x_axis).normalize_or(glam::DVec3::X);
let y = v(ucs.y_axis).normalize_or(glam::DVec3::Y);
let z = x.cross(y).normalize_or(glam::DVec3::Z);
let raw_y = v(ucs.y_axis).normalize_or(glam::DVec3::Y);
let fallback_z = if x.dot(glam::DVec3::Z).abs() < 0.999 {
glam::DVec3::Z
} else {
glam::DVec3::Y
};
let z = x.cross(raw_y).normalize_or(x.cross(fallback_z).normalize());
let y = z.cross(x).normalize();
Self { origin: v(ucs.origin), x, y, z }
}
@@ -127,6 +133,44 @@ impl UcsXform {
glam::Vec4::W,
)
}
/// Full UCS-local → WCS transform, using `origin` as local zero while
/// retaining this UCS's orthonormal axes.
pub(super) fn to_wcs_transform_at(
&self,
origin: glam::DVec3,
) -> acadrust::types::Transform {
use acadrust::types::{Matrix4, Transform};
Transform::from_matrix(Matrix4 {
m: [
[self.x.x, self.y.x, self.z.x, origin.x],
[self.x.y, self.y.y, self.z.y, origin.y],
[self.x.z, self.y.z, self.z.z, origin.z],
[0.0, 0.0, 0.0, 1.0],
],
})
}
/// Full WCS → UCS-local transform, using `origin` as the local zero.
pub(super) fn to_ucs_transform_at(
&self,
origin: glam::DVec3,
) -> acadrust::types::Transform {
use acadrust::types::{Matrix4, Transform};
Transform::from_matrix(Matrix4 {
m: [
[self.x.x, self.x.y, self.x.z, -origin.dot(self.x)],
[self.y.x, self.y.y, self.y.z, -origin.dot(self.y)],
[self.z.x, self.z.y, self.z.z, -origin.dot(self.z)],
[0.0, 0.0, 0.0, 1.0],
],
})
}
/// Convert from the represented UCS into its canonical local frame.
pub(super) fn to_ucs_transform(&self) -> acadrust::types::Transform {
self.to_ucs_transform_at(self.origin)
}
}
// ── UCS ↔ WCS transforms (thin wrappers over `UcsXform`) ────────────────────
+13 -1
View File
@@ -969,11 +969,23 @@ impl OpenCADStudio {
scene.reseed_derived_caches(handle);
}
if !final_changes.is_empty() {
scene.bump_entities(&final_changes);
if scene.changes_touch_block_definition(&final_changes) {
// A block-local delta changes the assembled definition
// consumed by every INSERT (including nested blocks).
// Replaying only the child handle leaves those cached
// references visually stale after BEDIT closes.
scene.bump_geometry();
} else {
scene.bump_entities(&final_changes);
}
}
}
scene.clear_preview_wire();
}
// UCS state is cached separately from its persisted header/viewport
// fields. History may just have restored those fields, so adopt them
// before drawing the icon/grid or accepting the next coordinate.
self.tabs[i].refresh_active_ucs();
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
self.tabs[i].active_grip = None;
+7 -1
View File
@@ -493,7 +493,12 @@ pub(super) fn on_tab_close(&mut self, idx: usize) -> Task<Message> {
&& (self.ucs_grip_drag.is_some() || self.ucs_icon_selected)
{
let i = self.active_tab;
self.ucs_grip_drag = None;
// A UCS grip drag is live-only until mouse release. Reload
// the persisted pane UCS so Escape really cancels it.
if self.ucs_grip_drag.take().is_some() {
self.tabs[i].refresh_active_ucs();
self.tabs[i].scene.camera_generation += 1;
}
self.ucs_icon_selected = false;
self.ucs_icon_hover = false;
self.tabs[i].snap_result = None;
@@ -1319,6 +1324,7 @@ pub(super) fn on_tab_close(&mut self, idx: usize) -> Task<Message> {
vp.ucs_origin = ucs.origin.clone();
vp.ucs_x_axis = ucs.x_axis.clone();
vp.ucs_y_axis = ucs.y_axis.clone();
vp.ucs_per_viewport = true;
}
}
}
+7 -3
View File
@@ -2344,16 +2344,20 @@ impl OpenCADStudio {
Message::SetViewcubeUcs(name) => {
let i = self.active_tab;
let mut changed = false;
if name.is_empty() || name == "WCS" {
self.tabs[i].active_ucs = None;
self.command_line.push_output("UCS: World");
changed = true;
} else if let Some(named) = self.tabs[i].scene.document.ucss.get(&name).cloned() {
self.tabs[i].active_ucs = Some(named);
self.command_line.push_output(&format!("UCS: {}", name));
changed = true;
}
if changed {
self.commit_active_ucs_change(i, "UCS");
self.tabs[i].scene.camera_generation += 1;
}
self.tabs[i].sync_ucs_to_scene();
self.tabs[i].scene.camera_generation += 1;
self.tabs[i].dirty = true;
Task::none()
}
+79 -3
View File
@@ -1752,10 +1752,81 @@ impl OpenCADStudio {
}
}
self.tabs[i].sync_ucs_to_scene();
self.tabs[i].dirty = true;
self.tabs[i].scene.camera_generation += 1;
}
/// Commit the live UCS to its owning space. Model/viewport panes persist
/// their normal UCS fields. A BEDIT pane has no persistent UCS of its own:
/// its transient origin and axes are baked into the block definition, then
/// the editor returns to canonical local coordinates.
pub(in crate::app) fn commit_active_ucs_change(&mut self, i: usize, label: &'static str) {
if let Some((session_index, block_record)) = self.tabs[i]
.active_block_edit
.and_then(|index| {
self.tabs[i]
.block_edits
.get(index)
.map(|session| (index, session.br_handle))
})
{
let frame = self.tabs[i].ucs_xform();
if !frame.is_identity() {
self.push_undo_snapshot(i, label);
let local_from_old = frame.to_ucs_transform();
let changed = self.tabs[i]
.scene
.reframe_block_definition(block_record, &local_from_old);
if changed > 0 {
// Carry the editor camera through the same rigid transform
// so changing the block coordinate frame does not make its
// contents jump on screen.
self.tabs[i]
.scene
.camera
.borrow_mut()
.apply_rigid_transform(&local_from_old);
self.tabs[i].scene.camera_generation += 1;
self.tabs[i].dirty = true;
}
}
// Blocks do not own a saved UCS. The chosen frame has now become
// their identity coordinates.
self.tabs[i].active_ucs = None;
let editor_camera = self.tabs[i].scene.camera.borrow().clone();
if let Some(session) = self.tabs[i].block_edits.get_mut(session_index) {
session.editor_ucs = None;
session.editor_camera = editor_camera;
}
self.tabs[i].sync_ucs_to_scene();
return;
}
let persisted = if let Some(handle) = self.tabs[i].scene.active_viewport {
self.tabs[i].ucs_from_viewport(handle)
} else if self.tabs[i].scene.current_layout == "Model" {
self.tabs[i].model_ucs_from_header()
} else {
None
};
let same_basis = |a: Option<&acadrust::tables::Ucs>,
b: Option<&acadrust::tables::Ucs>| {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => {
a.origin == b.origin && a.x_axis == b.x_axis && a.y_axis == b.y_axis
}
_ => false,
}
};
if !same_basis(self.tabs[i].active_ucs.as_ref(), persisted.as_ref()) {
self.push_undo_snapshot(i, label);
self.tabs[i].persist_active_ucs();
self.tabs[i].dirty = true;
}
self.tabs[i].sync_ucs_to_scene();
}
// ── Per-pane Model viewport (pane_grid) ───────────────────────────────
/// Focus Model pane `idx` (cursor entered it): swap in its camera, sync the
@@ -2033,9 +2104,10 @@ impl OpenCADStudio {
}
// Commit a UCS icon grip drag: persist the new UCS so it
// round-trips, and clear the lingering press state.
// round-trips, and clear the lingering press state. In BEDIT this
// rebases only the block; elsewhere it writes the model/viewport UCS.
if self.ucs_grip_drag.take().is_some() {
self.tabs[i].persist_active_ucs();
self.commit_active_ucs_change(i, "UCS");
self.tabs[i].snap_result = None;
self.snapper.from_point = None;
let mut sel = self.tabs[i].scene.selection.borrow_mut();
@@ -3819,9 +3891,11 @@ impl OpenCADStudio {
let cancel_task = self.cancel_active_command_for_space_change();
let current_camera = self.tabs[i].scene.camera.borrow().clone();
let current_ucs = self.tabs[i].active_ucs.clone();
if let Some(active_index) = self.tabs[i].active_block_edit {
if let Some(session) = self.tabs[i].block_edits.get_mut(active_index) {
session.editor_camera = current_camera;
session.editor_ucs = current_ucs;
}
} else {
self.tabs[i].scene.sync_camera_to_document();
@@ -3902,9 +3976,11 @@ impl OpenCADStudio {
};
if let Some(active_index) = self.tabs[i].active_block_edit.take() {
let camera = self.tabs[i].scene.camera.borrow().clone();
let editor_ucs = self.tabs[i].active_ucs.clone();
let (return_layout, return_camera) = {
let session = &mut self.tabs[i].block_edits[active_index];
session.editor_camera = camera;
session.editor_ucs = editor_ucs;
(session.return_layout.clone(), session.return_camera.clone())
};
let return_layout = if self.tabs[i].scene.layout_names().contains(&return_layout) {