Compare commits

..
31 Commits
Author SHA1 Message Date
Tanish Manku e1a048ba42 Stack d1: #2152: -ATTEDIT Position keeps aligned and fit text's baseline
Position set both points of a justified attribute to the pick, which left
aligned and fit text no direction or length. Both points now move by the
same offset, from the point the text is placed by.
2026-11-19 15:14:28 -07:00
Tanish Manku b713869cec Stack d1: #2368: put first_center's doc comment back on it 2026-11-19 15:14:28 -07:00
Tanish Manku bdc0c7b2a7 Stack d1: #2368: ARRAYEDIT puts a center given with a new base point where asked
center was read in the array's placement from before base or keyPoint moved
its insertion point, so the centre landed off by that move.
2026-11-19 15:14:28 -07:00
Tanish Manku bd7d94c8ea Stack d1: #2368: refuse a key point search over more than 10,000 objects
The search took the first 10,000 objects and could miss a nearer key point
on a later one; now it says so and asks for a point.
2026-11-19 15:14:28 -07:00
Tanish Manku c6e80bea8f Stack d1: #2368: refuse a keyPoint that isn't a point
A keyPoint that couldn't be read was taken as none, so ARRAYRECT,
ARRAYPOLAR and ARRAYEDIT went on with another base point.
2026-11-19 15:14:28 -07:00
Alex Ortiz 22226a08ad -ATTEDIT: Position, Height, Angle and Style one at a time (#2152)
The -ATTEDIT part of 6a86919f from #2152; its -RENAME VPort part is left
out for #2907.
2026-11-19 14:48:28 -07:00
Tanish Manku 7060a86ea6 Merge #2368: Array base points: the Key point option in ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (F5) 2026-11-19 14:47:28 -07:00
Tanish Manku c4fd42bc0b Merge #2915: -LAYER stAte: save, restore, edit, rename, delete and list layer states 2026-11-19 14:46:56 -07:00
Tanish Manku 75e737e2f3 Merge #2907: -RENAME: viewport configurations, and AutoCAD's messages 2026-11-19 14:46:17 -07:00
2ez4gcxandClaude Opus 5.5 685e364381 Prompt: declare NO_OR as a slice; test the states prompt's text
This PR and #2726 each add a prompt to NO_OR and raise its array length
from 28 to 29, so with both merged the array holds 30 entries under a
length of 29 (E0308), whichever lands first. A slice has no length to
keep in step; both PRs make the same change to this line.

No test noticed "Enter states to change" missing from NO_OR, so the Esc
test now checks the toggles prompt as AutoCAD 2024 writes it, without
"or" before the keywords.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:29:04 +07:00
2ez4gcxandClaude Opus 5.5 2f3368f400 Merge feat/acad-layer-states, now with main fbb08380
Brings in #2910's merge of main fbb08380, which also changes that branch's
layer state reader and writer to import Tag from craft_dxf (main #3040
replaced cadcraft-dxf with craft-dxf). This merge is clean: the tree is
#2910's plus exactly this branch's own changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:34:01 +07:00
2ez4gcxandClaude Opus 5.5 1a918ff740 Merge main into feat/acad-layer-states
Brings the branch up to main fbb08380. The merge has no conflicts, but
since #3040 the DXF tag crate is craft-dxf from craft-libs, so the layer
state reader and writer this branch adds imports Tag from craft_dxf
instead of the removed cadcraft_dxf. Without that the merged crate doesn't
compile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:08:27 +07:00
2ez4gcxandClaude Opus 5.5 7616ff63ea Merge main into fix/rename-vport-messages
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting, so the gate runs on a main that passes.
No conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:06:45 +07:00
2ez4gcxandClaude Opus 5.5 9def40d174 Merge feat/acad-layer-states, now with main
Brings in #2910's merge of main 6d744887 (with #2954's fix for
mtext::tests::strips_formatting), whose dxf_raw.rs conflict is resolved
there. This merge is clean: the tree is #2910's plus exactly this branch's
own changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:58:51 +07:00
2ez4gcxandClaude Opus 5.5 8f039dc3fa Merge main into feat/acad-layer-states
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting. The one conflict is in
crates/io/src/dxf_raw.rs: main moved the extension-dictionary liveness test
inside its hard-owner settle passes, and this branch keeps a merged LAYER
extension dictionary's objects live there. The check now sits inside main's
closure, unchanged otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:22:48 +07:00
2ez4gcxandClaude Opus 5.5 2206a861f2 Merge #2910's case-folded layer state entries; fix a test comment
Brings in feat/acad-layer-states: entries of AutoCAD's dictionary whose
names differ only in case are read as one state, as AutoCAD 2024 opens them.
The JSON lookup test's comment now says where two such names can come from:
CADCraft's own record keeps the second, which AutoCAD doesn't see.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:31:28 +07:00
2ez4gcxandClaude Opus 5.5 cd9f8b1dd3 Layer states: entries in another case are one state, as in AutoCAD 2024
AutoCAD 2024 opens the entries S and s of one ACAD_LAYERSTATES dictionary as
a single state, named as the first entry in the dictionary and holding the
last entry's record (measured with both dictionary orders). The reader kept
two states, so a save moved the second to CADCraft's record and AutoCAD then
restored the other record than before. It now reads them as AutoCAD does;
CADCraft's own record still keeps a second spelling it wrote itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:20:19 +07:00
2ez4gcxandClaude Opus 5.5 b3fbfa0a3c Merge #2910's layer state reader bound; layerstate.save checks names
Brings in feat/acad-layer-states (b9d74f8f): a state holds each layer once,
a repeated entry applying over the earlier one, and copies of layers into
states share a per-file budget.

After review: the JSON layerstate.save refuses a name valid_name refuses
(empty, over 255 characters, a control character or one AutoCAD refuses),
as -LAYER stAte Save and layerstate.rename already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 04:32:56 +07:00
2ez4gcxandClaude Opus 5.5 10aa4e18f7 -RENAME VPort tests: *Invalid*, Enter, and the JSON form's refusals
After review: the viewport configuration test checks that "*Invalid*"
follows only a name already used, that Enter as the new name is refused,
the measured cfg1 typed for CFG1 to cfg1 row (it was run without an
assertion), and the JSON form's refusal of a name already used or invalid
and its case-only rename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 03:53:36 +07:00
2ez4gcxandClaude Opus 5.5 b9d74f8feb Layer states: each layer once per state, and a bound on copied layers
Each entry of a state copied the drawing's layer, so a small file naming one
layer with a long description in many entries could take gigabytes. A state
now holds each LAYER handle once; a repeated entry applies over the earlier
one, which gives what restoring both in turn did, and AutoCAD 2024 restores
the later of two full entries (measured). New copies are charged to one
per-file budget of 256 MiB, as image-definition strings are; past it the
remaining entries are left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 03:53:09 +07:00
2ez4gcxandClaude Opus 5.5 2cb1fcd060 Layer states: layerstate.save replaces only the state the lookups reach
f8be7d83 replaced every state whose name matched without regard to case,
so in a file holding both M2 and m2 (one AutoCAD 2024 opens), saving m2
dropped M2 too. Save now replaces the state Restore and Delete reach (the
same spelling, else another case) and leaves the other one, as AutoCAD,
which refuses the save, leaves both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 00:14:05 +07:00
2ez4gcxandClaude Opus 5.5 f8be7d8339 Layer states: layerstate.save replaces a state named in another case
This PR makes layerstate.restore, rename and delete find a state's name
without regard to case, as AutoCAD 2024 does, but layerstate.save still
replaced only a state of the same spelling, so saving s1 next to S1 made
a second state that the lookups then had to choose between. AutoCAD
keeps one state per name in any case: its -LAYER stAte Save and
layerstate-save refuse s1 after S1 and keep S1 (measured; layerstate-has
"s1" is T). -LAYER stAte Save here already refuses; the JSON command now
replaces a state whose name differs only in case, as it replaces one of
the same spelling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 22:47:03 +07:00
2ez4gcxandClaude Opus 5.5 60fc6e7b40 Merge feat/acad-layer-states: a frozen current layer without an entry stays frozen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:43:25 +07:00
2ez4gcxandClaude Opus 5.5 38cab40e46 Layer state restore: a frozen current layer without an entry stays frozen
A state whose current layer (302) is frozen in the drawing made it current
whenever the mask had Frozen, even with no entry of its own to thaw it,
leaving a frozen current layer. AutoCAD 2024 keeps the current layer then
(measured: 302 = frozen B, mask 2047, no entry for B, A current -> A stays
current, B stays frozen, the other entries are restored; with an entry B
becomes current and thaws). It now takes Frozen in the mask and an entry
for that layer, matched without case as the per-layer restore matches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 12:09:52 +07:00
2ez4gcxandClaude Opus 5.5 7997db2fd0 Merge feat/acad-layer-states: the layer state tests added for review on #2910
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 11:07:04 +07:00
2ez4gcxandClaude Opus 5.5 bcb6d6ac51 Layer states: tests for each mask bit, old records, the limit and dangling entries
- Restore: one state per remaining mask bit (Plot, VP freeze new, Linetype,
  Lineweight, Plot style, Transparency) restores only its property.
- A state of CADCraft's own record from before masks (JSON with only the
  name and the layers) reads as mask 2047, no current layer, no description.
- 100 001 states in AutoCAD's dictionary: the last one in the file is left
  out and the others come in file order.
- The LAYER table's kept extension dictionary with entries pointing at a
  handle of nothing and at 0: neither is written.
- States named "" and " " stay in CADCraft's record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:36:45 +07:00
2ez4gcxandClaude Opus 5.5 50555a9110 -LAYER stAte: save, restore, edit, rename, delete and list layer states
-LAYER stAte printed "not available yet". It now runs the layer state
options with AutoCAD 2024's prompts and messages (measured with
accoreconsole): Save lists the ten "Enter states to change" toggles and
remembers them for the next Save; Edit sets a state's own mask and keeps
bits no toggle reaches; Name and Save refuse names a state has in any
case and the characters layer names refuse; unknown names re-prompt;
`?` lists names without regard to case. Import and EXport stay "not
available yet".

The layerstate.* commands find names as spelled, else in another case,
and layerstate.save takes an optional mask.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 04:03:26 +07:00
2ez4gcxandClaude Opus 5.5 5420dea6c1 -RENAME: compare the new name with the stored one; refuse layer 0 and Continuous
The old name is now kept as the drawing spells it, so a new name in another
case than that is a rename even when it is the old name as typed: AutoCAD 2024
renames viewport configuration CFG1 typed cfg1 to cfg1, and leaves it for
cfg1 to CFG1 (measured; the same for layers).

At the old-name prompt AutoCAD 2024 ends the command on names it won't
rename (measured): layer 0 and linetype Continuous ("Cannot rename ..." and
*Invalid*), linetypes ByLayer and ByBlock and block names starting with "*"
such as *Model_Space or an anonymous *U0 ("Invalid ... name.").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:13:16 +07:00
2ez4gcxandClaude Opus 5.5 9ed3607b72 DXF/DWG: layer states in AutoCAD's form, restored by mask and current layer
CADCraft kept saved layer states only in its own CADCRAFT_LAYERSTATES record,
so AutoCAD 2024 listed none of them ("Unknown layer state name.") and
CADCraft read none of AutoCAD's ACAD_LAYERSTATES ("No saved layer states.").

States now go into the LAYER table's extension dictionary, ACAD_LAYERSTATES,
one XRECORD each, in the layout AutoCAD 2024 writes (measured): mask, current
layer, and per layer its handle, flags, colour (92 for a true colour),
lineweight, linetype, plot style (Color_N, or the placeholder handle with
named plot styles), transparency, and 93 on an xref's layer. View layer
snapshots and names repeated in another case stay in CADCraft's record.
Reading takes AutoCAD's states, then CADCraft's own. A kept LAYER table
dictionary (layer filters) joins the one written for the states.

layerstate.restore now does what AutoCAD does: the state's current layer
first (unless left frozen), only the masked properties, never freezing the
current layer; layerstate.save records the current layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 23:47:19 +07:00
2ez4gcxandClaude Opus 5.5 38f51899fc -RENAME: viewport configurations, and AutoCAD's messages
-RENAME's VPort option printed "not available yet". It now renames a saved
viewport configuration, every tile of it (never *Active), as AutoCAD 2024
does; the JSON form takes table "vport".

-RENAME also answers a name it can't take as AutoCAD 2024 does (measured
for blocks, dimension styles, layers, linetypes, text styles, UCSs, views
and viewport configurations), ending the command instead of asking again:
"Cannot find layer "X".", "A layer named "X" already exists." then
"*Invalid*", "Invalid layer name." (also for no name at all). A UCS is
"ucs" in the prompts and in "A ucs named", "UCS" in the other two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 21:38:04 +07:00
Francesco BVandClaude Opus 5.5 b600293cfa arrays: the Key point option of a base point (F5)
ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and REPlace) offered Key
point but only said it was not available. It now asks for a key point on
the source (or replacement) objects and takes their key point nearest the
pick (an end point, midpoint, centre, quadrant, vertex or insertion point)
as the base point; in ARRAYEDIT the source objects are searched as placed
at the item picked. The JSON forms take `keyPoint`.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 22:42:36 +01:00
81 changed files with 2741 additions and 4060 deletions
+1
View File
@@ -44,6 +44,7 @@ fn snapshot(ui: &UiState) -> Result<Value, String> {
"showStatusBar": ui.show_status_bar,
"showCommandLine": ui.show_command_line,
"showViewcube": ui.show_viewcube,
"showUcsIcon": ui.show_ucs_icon,
"showLayerList": ui.show_layer_list,
"toolsetTab": ui.toolset_tab,
"collapsedGroups": ui.collapsed_groups,
-5
View File
@@ -130,10 +130,6 @@ pub struct Drawing {
/// Objects hidden for this session by ISOLATEOBJECTS / HIDEOBJECTS. Never written to a file:
/// a drawing opens with everything shown again.
pub hidden_objects: BTreeSet<Handle>,
/// Model space's earlier UCSs for UCS Previous, oldest first (each layout keeps its own,
/// [`Layout::ucs_previous`]). Part of the drawing so undo restores them with the UCS. Never
/// written to a file.
pub ucs_previous: Vec<Ucs>,
/// What reading the file left out (a DWG's object records the reader couldn't decode), told
/// to the user when the drawing opens. Never written to a file.
pub read_notes: Vec<String>,
@@ -205,7 +201,6 @@ impl Drawing {
scales: imperial_scales(),
handseed: 0x100,
hidden_objects: BTreeSet::new(),
ucs_previous: Vec::new(),
read_notes: Vec::new(),
refedit: None,
skipped_records: BTreeMap::new(),
+40 -19
View File
@@ -857,14 +857,6 @@ pub struct Layout {
/// Saved paper-space view (centre, height).
#[serde(default)]
pub view: Option<(Vec2, f64)>,
/// The layout's current paper-space UCS (the LAYOUT object's groups 13, 16, 17 and 345);
/// `None`: the World UCS. Its name is empty when it isn't a named UCS.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ucs: Option<Ucs>,
/// The layout's earlier UCSs for UCS Previous, oldest first: they go with the layout when it
/// is renamed and with it when it is deleted. Never written to a file.
#[serde(skip)]
pub ucs_previous: Vec<Ucs>,
/// The layout's limits (LAYOUT groups 10/11, lower left and upper right) as the file had
/// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109).
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -873,16 +865,7 @@ pub struct Layout {
impl Layout {
pub fn new(name: &str, tab_order: u32) -> Self {
Layout {
name: name.into(),
tab_order,
page: PageSetup::default(),
entities: EntityStore::new(),
view: None,
ucs: None,
ucs_previous: Vec::new(),
limits: None,
}
Layout { name: name.into(), tab_order, page: PageSetup::default(), entities: EntityStore::new(), view: None, limits: None }
}
}
@@ -948,11 +931,49 @@ pub struct Ucs {
pub y_axis: Vec3,
}
/// A saved layer state (LAYERSTATE).
/// A saved layer state (LAYERSTATE), as AutoCAD keeps one in the LAYER table's
/// `ACAD_LAYERSTATES` dictionary.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct LayerState {
pub name: String,
pub layers: Vec<Layer>,
/// The properties restoring sets ([`LayerState::ON`] …): AutoCAD's mask (group 91 of the
/// state's XRECORD). Bits CADCraft doesn't use are kept as read.
pub mask: u32,
/// The layer restoring makes current; empty, or a layer the drawing doesn't have, leaves the
/// current layer as it is (AutoCAD 2024, measured).
pub current: String,
/// Group 301 of the state's XRECORD: empty as AutoCAD 2024's -LAYER saves a state; a text a
/// file holds there is kept.
pub description: String,
}
impl Default for LayerState {
fn default() -> Self {
LayerState { name: String::new(), layers: Vec::new(), mask: LayerState::ALL, current: String::new(), description: String::new() }
}
}
impl LayerState {
pub const ON: u32 = 1;
pub const FROZEN: u32 = 2;
pub const LOCKED: u32 = 4;
pub const PLOT: u32 = 8;
pub const VP_FREEZE_NEW: u32 = 16;
pub const COLOR: u32 = 32;
pub const LINETYPE: u32 = 64;
pub const LINEWEIGHT: u32 = 128;
pub const PLOT_STYLE: u32 = 256;
pub const TRANSPARENCY: u32 = 1024;
/// Every property: the mask of AutoCAD 2024's -LAYER stAte Save with its defaults (2047; bit
/// 512, which no property toggles, is always set).
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
}
}
/// A named group of entities (GROUP).
-2
View File
@@ -51,7 +51,6 @@ mod tolerance;
mod trimextend;
mod txt2mtxt;
pub use txt2mtxt::Txt2MtxtOptions;
mod ucs;
mod utility;
mod view;
@@ -188,7 +187,6 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(qselect::specs());
v.extend(selecttools::specs());
v.extend(view::specs());
v.extend(ucs::specs());
v.extend(draw::specs());
v.extend(draw2::specs());
v.extend(annotate::specs());
+2 -9
View File
@@ -35,15 +35,8 @@ fn auto_rotation(p1: Vec2, p2: Vec2, at: Vec2) -> f64 {
if outside_x && !outside_y { std::f64::consts::FRAC_PI_2 } else { 0.0 }
}
/// A linear or aligned dimension's kind; without a rotation, horizontal or vertical along axes turned
/// `ucs` radians (the current UCS's at the command line; the world's for JSON).
pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option<f64>, aligned: bool, ucs: f64) -> DimKind {
if aligned {
return DimKind::Aligned;
}
let ucs = if ucs.is_finite() { ucs } else { 0.0 };
let auto = || auto_rotation(p1.rotate(-ucs), p2.rotate(-ucs), at.rotate(-ucs)) + ucs;
DimKind::Linear { rotation: rotation.unwrap_or_else(auto) }
pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option<f64>, aligned: bool) -> DimKind {
if aligned { DimKind::Aligned } else { DimKind::Linear { rotation: rotation.unwrap_or_else(|| auto_rotation(p1, p2, at)) } }
}
/// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints,
+5 -14
View File
@@ -11,7 +11,7 @@ pub(super) fn run_linear(s: &mut Session, p: &Value) -> Result<Value> {
};
let at = point_req("dimlinear", p, "at")?;
let rot = p.get("rotation").and_then(Value::as_f64).map(f64::to_radians);
let k = dim(s, linear_kind(a, b, at, rot, false, 0.0), at, a, b, Vec2::ZERO, str_param(p, "text").unwrap_or(""));
let k = dim(s, linear_kind(a, b, at, rot, false), at, a, b, Vec2::ZERO, str_param(p, "text").unwrap_or(""));
Ok(json!({ "handle": add_dim(s, k)?.hex() }))
}
@@ -216,8 +216,7 @@ impl Interactive for LinearM {
}
(_, Input::Point(at)) => {
let (Some(&a), Some(&b)) = (self.pts.first(), self.pts.get(1)) else { return Ok(Step::Continue) };
let k =
self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), at, a, b, Vec2::ZERO, ""));
let k = self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned), at, a, b, Vec2::ZERO, ""));
add_dim(s, k)?;
if let Some(EntityKind::Dimension(d)) = s.last_dim.and_then(|h| s.doc().ok()?.entity(h).map(|e| e.kind.clone())) {
let st = s.doc()?.dim_style(&d.style).cloned().unwrap_or_default();
@@ -228,8 +227,8 @@ impl Interactive for LinearM {
}
(_, Input::Keyword(k)) => {
match k.as_str() {
"Horizontal" => self.rotation = Some(s.input_ucs().rotation()),
"Vertical" => self.rotation = Some(s.input_ucs().rotation() + std::f64::consts::FRAC_PI_2),
"Horizontal" => self.rotation = Some(0.0),
"Vertical" => self.rotation = Some(std::f64::consts::FRAC_PI_2),
"Rotated" => self.rotating = true,
other => {
self.text.keyword(other);
@@ -244,15 +243,7 @@ impl Interactive for LinearM {
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
match self.pts.as_slice() {
[a] => vec![crate::cmd::helpers::line(*a, c)],
[a, b] => vec![self.text.apply(dim(
s,
linear_kind(*a, *b, c, self.rotation, self.aligned, s.input_ucs().rotation()),
c,
*a,
*b,
Vec2::ZERO,
"",
))],
[a, b] => vec![self.text.apply(dim(s, linear_kind(*a, *b, c, self.rotation, self.aligned), c, *a, *b, Vec2::ZERO, ""))],
_ => Vec::new(),
}
}
+72 -12
View File
@@ -27,6 +27,10 @@ mod edit;
/// Most preview entities drawn while the array is edited.
const PREVIEW_LIMIT: usize = 2000;
/// Most objects whose key points are searched for a Key point base point.
const MAX_KEY_OBJECTS: usize = 10_000;
/// The prompt after the Key point option of a base point.
const KEY_POINT_PROMPT: &str = "Specify key point on source objects to use as base point";
/// Keyword-only prompts: each typed token is matched on its own (no free text).
const KEYWORDS: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
@@ -41,13 +45,13 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrayrect", "Rectangular Array", run_arrayrect)
.menu(&["Modify", "Array", "Rectangular Array"])
.params(
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
)
.interactive(|_| Ok(Box::new(RectM::default()))),
CommandSpec::new("arraypolar", "Polar Array", run_arraypolar)
.menu(&["Modify", "Array", "Polar Array"])
.params(
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
)
.interactive(|_| Ok(Box::new(PolarM::default()))),
CommandSpec::new("-array", "Array", classic::run_classic)
@@ -246,6 +250,45 @@ fn bounds(d: &Drawing, hs: &[Handle]) -> Bounds2 {
hs.iter().filter_map(|h| d.entity(*h).map(|e| cadcraft_doc::entity_bounds(d, e, 0))).fold(Bounds2::EMPTY, |a, b| a.union(&b))
}
/// The key point of `ents`, placed by `m`, nearest `at`: one of their grips (end points,
/// midpoints, centres, vertices, insertion points). `None` when they have none. More than
/// [`MAX_KEY_OBJECTS`] objects are refused: searching only some could miss the nearest one.
pub(crate) fn nearest_key_point<'a>(ents: impl Iterator<Item = &'a Entity>, m: &Mat3, at: Vec2) -> Result<Option<Vec2>> {
if !at.is_finite() {
return Ok(None);
}
let mut best: Option<(Vec2, f64)> = None;
for (n, e) in ents.enumerate() {
if n >= MAX_KEY_OBJECTS {
return Err(other(format!("Too many objects to search for a key point (at most {MAX_KEY_OBJECTS}); specify a point.")));
}
let mut k = e.kind.clone();
k.transform(m);
for g in k.grips().into_iter().filter(|g| g.is_finite()) {
let d = g.dist(at);
if best.is_none_or(|(_, bd)| d < bd) {
best = Some((g, d));
}
}
}
Ok(best.map(|b| b.0))
}
/// `keyPoint` of a JSON form: absent or null is none; anything else must be a point, rather than
/// be taken as none and the base point found another way.
pub(crate) fn key_point_param(cmd: &str, p: &Value) -> Result<Option<Vec2>> {
match p.get("keyPoint") {
None | Some(Value::Null) => Ok(None),
Some(_) => point_param(p, "keyPoint").map(Some).ok_or_else(|| bad(cmd, "`keyPoint` must be a point [x, y]")),
}
}
/// The key point of objects `hs` in the drawing nearest `at`.
pub(crate) fn key_point_of(d: &Drawing, hs: &[Handle], at: Vec2) -> Result<Vec2> {
nearest_key_point(hs.iter().filter_map(|h| d.entity(*h)).map(|e| &**e), &Mat3::IDENTITY, at)?
.ok_or_else(|| other("The objects have no key point; specify a point."))
}
/// The centre of the first object (the point a non-rotated polar copy is moved by).
fn first_center(d: &Drawing, hs: &[Handle]) -> Option<Vec2> {
hs.first().and_then(|h| d.entity(*h)).map(|e| cadcraft_doc::entity_bounds(d, e, 0).center()).filter(|c| c.is_finite())
@@ -386,9 +429,10 @@ fn run_arrayrect(s: &mut Session, p: &Value) -> Result<Value> {
row_elevation: f64_or(p, "rowElevation", 0.0),
});
let rs = f64_or(p, "rowSpacing", 1.0);
let base = match point_param(p, "base") {
Some(b) => b,
None => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
let base = match (key_point_param("arrayrect", p)?, point_param(p, "base")) {
(Some(k), _) => key_point_of(s.doc()?, &hs, k)?,
(None, Some(b)) => b,
(None, None) => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
};
let p2 = params(kind, levels, f64_or(p, "levelSpacing", rs));
let associative = bool_or(p, "associative", assoc_default(s));
@@ -402,7 +446,10 @@ fn run_arraypolar(s: &mut Session, p: &Value) -> Result<Value> {
let rows = count_or("arraypolar", p, "rows", 1)?;
let levels = count_or("arraypolar", p, "levels", 1)?;
check_size(s, n.saturating_mul(rows).saturating_mul(levels), hs.len())?;
let base = point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c);
let base = match key_point_param("arraypolar", p)? {
Some(k) => key_point_of(s.doc()?, &hs, k)?,
None => point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c),
};
let row_spacing = f64_or(p, "rowSpacing", 1.0);
let fill = f64_or(p, "angle", 360.0);
if !(fill.abs() >= 1e-9 && fill.abs() <= 360.0 + 1e-9) {
@@ -503,6 +550,8 @@ enum RStage {
Main,
Assoc,
Base,
/// Base point: Key point (a grip of the source objects).
BaseKey,
/// COUnt: columns, then rows.
CountCols,
CountRows,
@@ -663,6 +712,7 @@ impl Interactive for RectM {
.default("eXit"),
Assoc => assoc_prompt(self.assoc),
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
CountCols | ColsCount => cols(),
CountRows | RowsCount => rows(),
SpaceCols => dist("Specify the distance between columns", self.cs).kw(&["Unit cell"]),
@@ -712,10 +762,12 @@ impl Interactive for RectM {
self.base = self.centroid;
Main
}
(Base, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
Base
(Base, Input::Keyword(_)) => BaseKey,
(BaseKey, Input::Point(p)) => {
self.base = key_point_of(s.doc()?, &self.objs, *p)?;
Main
}
(BaseKey, Input::Enter) => Base,
(CountCols | ColsCount, _) => match count(&i, self.cols, max_count(s, self.rows.saturating_mul(self.levels), n))? {
Some(c) => {
self.cols = c;
@@ -858,6 +910,9 @@ enum PStage {
Main,
Assoc,
Base,
/// Key point of the base point asked from the center prompt, or from the main prompt.
CenterBaseKey,
BaseKey,
Items,
Between,
Fill,
@@ -1034,6 +1089,7 @@ impl Interactive for PolarM {
match self.stage {
Center => Prompt::new("Specify center point of array", Accept::POINT).kw(&["Base point", "Axis of rotation"]),
CenterBase | Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
CenterBaseKey | BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
Main => Prompt::new("Select grip to edit array", Accept::POINT)
.kw(&["ASsociative", "Base point", "Items", "Angle between", "Fill angle", "ROWs", "Levels", "ROTate items", "eXit"])
.default("eXit"),
@@ -1092,10 +1148,14 @@ impl Interactive for PolarM {
self.base = None;
if stage == CenterBase { Center } else { Main }
}
(CenterBase | Base, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
stage
(CenterBase, Input::Keyword(_)) => CenterBaseKey,
(Base, Input::Keyword(_)) => BaseKey,
(CenterBaseKey | BaseKey, Input::Point(p)) => {
self.base = Some(key_point_of(s.doc()?, &self.objs, *p)?);
if stage == CenterBaseKey { Center } else { Main }
}
(CenterBaseKey, Input::Enter) => CenterBase,
(BaseKey, Input::Enter) => Base,
(Items, _) => match count(&i, self.items, max_count(s, self.rows.saturating_mul(self.levels), n))? {
Some(c) => {
self.items = c;
+49 -10
View File
@@ -18,7 +18,9 @@ use super::super::helpers::v3;
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::super::{CommandSpec, bad, bool_or, point_param, targets};
use super::{KEYWORDS, angle, check_size, count, fmt, nesting, other, yes, yes_no};
use super::{
KEY_POINT_PROMPT, KEYWORDS, angle, check_size, count, fmt, key_point_of, key_point_param, nearest_key_point, nesting, other, yes, yes_no,
};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(super) fn specs() -> Vec<CommandSpec> {
@@ -26,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrayedit", "Edit Array", run_arrayedit)
.menu(&["Modify", "Object", "Array"])
.params(
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, keyPoint? ([x, y]: the new base point is the source objects' key point nearest it, on the item there), replace?.keyPoint? ([x, y]: the replacement objects' key point nearest it is their base point), source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
)
.interactive(|_| Ok(Box::new(EditM::default()))),
CommandSpec::new("arrayclose", "Close Array Editing", run_arrayclose)
@@ -215,6 +217,16 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32)
best.map(|b| b.0)
}
/// ARRAYEDIT Key point: the key point of the source objects nearest `at`, with the objects as
/// placed at the item under `at` (within `tol`).
fn source_key_point(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Result<Vec2> {
let item = item_at(d, h, at, tol).ok_or_else(|| other("No array item there; specify a point on an item of the array."))?;
let (ins, blk, p) = array_of(d, h)?;
let src = d.block(&p.source).ok_or_else(|| other("The array's source block is missing."))?;
let m = ins.transform(blk.base.xy()).then_before(item_place(&p, item)?).then_before(Mat3::translate(-src.base.xy()));
nearest_key_point(src.entities.iter().map(|e| e.as_ref()), &m, at)?.ok_or_else(|| other("The source objects have no key point; specify a point."))
}
/// Move the base point of array `h` to world point `base` without moving the items.
fn rebase(s: &mut Session, h: Handle, base: Vec2) -> Result<()> {
let d = s.doc()?;
@@ -343,6 +355,9 @@ fn close_source(s: &mut Session, save: bool) -> Result<Value> {
// ---------------- JSON ----------------
/// How far outside an item's extents a JSON `keyPoint` may be.
const KEY_POINT_TOLERANCE: f64 = 1e-6;
fn item_param(v: &Value) -> Option<(u32, u32, u32)> {
let a = v.as_array()?;
let n = |k: usize| a.get(k).and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok());
@@ -449,9 +464,7 @@ fn fill_from_between(b: f64, items: u32) -> Result<f64> {
fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
let h = super::super::curves::handle_param(p, "handle").ok_or_else(|| bad("arrayedit", "`handle` (the array) is required"))?;
refuse_while_editing(s)?;
let (ins, blk, _) = array_of(s.doc()?, h)?;
let w = ins.transform(blk.base.xy());
let to_local = w.inverse().ok_or_else(|| other("The array's scale is zero."))?;
array_of(s.doc()?, h)?;
if bool_or(p, "reset", false) {
let (_, _, mut a) = array_of(s.doc()?, h)?;
a.replaced.clear();
@@ -459,7 +472,10 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(r) = p.get("replace").filter(|v| !v.is_null()) {
let hs = targets(s, r)?;
let base = point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default());
let base = match key_point_param("arrayedit", r)? {
Some(k) => key_point_of(s.doc()?, &hs, k)?,
None => point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()),
};
let name = block_from(s, h, &hs, base)?;
let (_, _, mut a) = array_of(s.doc()?, h)?;
match r.get("items") {
@@ -477,7 +493,13 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(b) = point_param(p, "base") {
rebase(s, h, b)?;
}
let (_, _, mut a) = array_of(s.doc()?, h)?;
if let Some(k) = key_point_param("arrayedit", p)? {
let at = source_key_point(s.doc()?, h, k, KEY_POINT_TOLERANCE)?;
rebase(s, h, at)?;
}
// A new base point moves the array's insertion point: read `center` in its placement after.
let (ins, blk, mut a) = array_of(s.doc()?, h)?;
let to_local = ins.transform(blk.base.xy()).inverse().ok_or_else(|| other("The array's scale is zero."))?;
let before = a.clone();
apply_params(&mut a, p, &to_local)?;
if a != before {
@@ -507,6 +529,8 @@ enum Stage {
Select,
Main,
Base,
/// Base point: Key point (of the source objects).
BaseKey,
ColsCount,
ColsSpace,
ColsTotal,
@@ -524,6 +548,8 @@ enum Stage {
/// REPlace: objects, their base point, then the items to replace.
RepSelect,
RepBase,
/// REPlace base point: Key point (of the replacement objects).
RepKey,
RepItems,
/// Source: the item whose objects are placed for editing.
SourceItem,
@@ -659,6 +685,7 @@ impl Interactive for EditM {
.kw(&["Source", "REPlace", "Base point", "Rows", "Columns", "Levels", "RESet", "eXit"])
.default("eXit"),
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
ColsCount => Prompt::new("Enter the number of columns", Accept::NUMBER).default(cols.to_string()),
ColsSpace => dist("Specify the distance between columns", cs).kw(&["Total"]),
ColsTotal => dist("Specify the distance between the first and last column", total(cols, cs)),
@@ -687,6 +714,7 @@ impl Interactive for EditM {
Rotate => Prompt::new("Rotate arrayed items?", KEYWORDS).kw(&["Yes", "No"]).default(yes(polar.as_ref().is_none_or(|k| k.rotate))),
RepSelect => Prompt::new("Select replacement objects", Accept::SELECT),
RepBase => Prompt::new("Select base point of replacement objects", Accept::POINT).kw(&["Key point"]).default("centroid"),
RepKey => Prompt::new("Specify key point on replacement objects to use as base point", Accept::POINT),
RepItems => Prompt::new("Select an item in array to replace", Accept::POINT).kw(&["Source objects"]),
SourceItem => Prompt::new("Select item in array", Accept::POINT),
}
@@ -746,10 +774,21 @@ impl Interactive for EditM {
}
Main
}
(Base | RepBase, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
stage
(Base, Input::Keyword(_)) => BaseKey,
(RepBase, Input::Keyword(_)) => RepKey,
(BaseKey, Input::Point(p)) => {
let tol = s.pixel_size() * s.settings.pickbox;
let at = source_key_point(s.doc()?, h, *p, tol)?;
rebase(s, h, at)?;
Main
}
(BaseKey, Input::Enter) => Base,
(RepKey, Input::Point(p)) => {
let base = key_point_of(s.doc()?, &self.rep_objs, *p)?;
self.rep_block = Some(block_from(s, h, &self.rep_objs.clone(), base)?);
RepItems
}
(RepKey, Input::Enter) => RepBase,
(ColsCount | Items, _) => match count(&i, c64, self.max_for(s, r64.saturating_mul(l64)))? {
Some(n) => {
let n = super::count32(n);
+164 -6
View File
@@ -4,6 +4,7 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
use cadcraft_geom::Vec3;
use serde_json::{Map, Value, json};
use crate::cmd::curves::KW;
@@ -153,6 +154,19 @@ fn set_value(text: &mut Text, value: String) {
}
}
/// Move `text` so the point it is placed by lands on `to`: the alignment point of justified text,
/// else the insertion point. Both points move by the same offset, so aligned and fit text keep the
/// baseline between them.
fn move_text(text: &mut Text, to: cadcraft_geom::Vec2) {
let anchor = match text.align_pt {
Some(ap) if !matches!((text.halign, text.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)) => ap,
_ => text.insert,
};
let d = Vec3::new(to.x - anchor.x, to.y - anchor.y, 0.0);
text.insert = text.insert + d;
text.align_pt = text.align_pt.map(|ap| ap + d);
}
/// Change the properties set on attribute `k` of block reference `h`.
fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut AttribProps)) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
@@ -165,6 +179,18 @@ fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut Attri
Ok(())
}
/// Modify the attribute `k` of block reference `h`.
fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut cadcraft_doc::Attrib)) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind
&& let Some(a) = ins.attribs.get_mut(k)
{
f(a);
}
})?;
Ok(())
}
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
/// definition's (layer 0 is the reference's layer).
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
@@ -180,6 +206,14 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)
Some((layer, c.color))
}
/// The current text properties of attribute `k` of block reference `h`.
fn current_text(s: &Session, (h, k): (Handle, usize)) -> Option<cadcraft_doc::Text> {
let d = s.doc().ok()?;
let e = d.entity(h)?;
let EntityKind::Insert(ins) = &e.kind else { return None };
ins.attribs.get(k).map(|a| a.text.clone())
}
/// Replace every `find` in `value` with `with`, unless the result would be too long.
fn replaced(value: &str, find: &str, with: &str) -> Option<String> {
if find.is_empty() || !value.contains(find) {
@@ -292,6 +326,10 @@ enum Stage {
Select,
/// One at a time: what to do with the current attribute.
Option,
Position,
Height,
Angle,
Style,
ValueKind,
NewValue,
Layer,
@@ -365,6 +403,7 @@ impl Interactive for DashAtteditM {
}
fn prompt(&self, s: &Session) -> Prompt {
let cur = self.items.get(self.cur).and_then(|it| current_props(s, *it));
let cur_text = self.items.get(self.cur).and_then(|it| current_text(s, *it));
match self.stage {
Stage::OneAtATime => Prompt::new("Edit attributes one at a time?", KW).kw(&["Yes", "No"]).default("Y"),
Stage::VisibleOnly => Prompt::new("Edit only attributes visible on screen?", KW).kw(&["Yes", "No"]).default("Y"),
@@ -372,7 +411,31 @@ impl Interactive for DashAtteditM {
Stage::TagSpec => Prompt::new("Enter attribute tag specification", Accept::TEXT).default("*"),
Stage::ValueSpec => Prompt::new("Enter attribute value specification", Accept::TEXT).default("*"),
Stage::Select => Prompt::new("Select attributes", Accept::SELECT),
Stage::Option => Prompt::new("Enter an option", KW).kw(&["Value", "Layer", "Color", "Next"]).default("N"),
Stage::Option => {
Prompt::new("Enter an option", KW).kw(&["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"]).default("N")
}
Stage::Position => Prompt::new("Enter new text insertion point", Accept::POINT),
Stage::Height => {
let p = Prompt::new("Enter new text height", Accept::POINT_OR_NUMBER);
match cur_text {
Some(t) => p.default(format!("{:.4}", t.height)),
None => p,
}
}
Stage::Angle => {
let p = Prompt::new("Enter new text rotation angle", Accept::POINT_OR_NUMBER);
match cur_text {
Some(t) => p.default(format!("{:.4}", t.rotation.to_degrees())),
None => p,
}
}
Stage::Style => {
let p = Prompt::new("Enter new text style", Accept::TEXT);
match cur_text {
Some(t) => p.default(t.style),
None => p,
}
}
Stage::ValueKind => Prompt::new("Enter type of value modification", KW).kw(&["Change", "Replace"]).default("R"),
Stage::NewValue => Prompt::new("Enter new attribute value", Accept::TEXT),
Stage::Layer => {
@@ -446,6 +509,10 @@ impl Interactive for DashAtteditM {
}
Stage::Option => match &i {
Input::Keyword(k) if k == "Value" => self.stage = Stage::ValueKind,
Input::Keyword(k) if k == "Position" => self.stage = Stage::Position,
Input::Keyword(k) if k == "Height" => self.stage = Stage::Height,
Input::Keyword(k) if k == "Angle" => self.stage = Stage::Angle,
Input::Keyword(k) if k == "Style" => self.stage = Stage::Style,
Input::Keyword(k) if k == "Layer" => self.stage = Stage::Layer,
Input::Keyword(k) if k == "Color" => self.stage = Stage::Color,
Input::Keyword(_) | Input::Enter => {
@@ -457,14 +524,105 @@ impl Interactive for DashAtteditM {
}
Input::Text(t) => {
let tl = t.trim().to_ascii_lowercase();
let later = ["Position", "Height", "Angle", "Style"];
return match later.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
Some(k) => Err(EngineError::Other(format!("{k} is not available yet."))),
None => Err(invalid_keyword()),
};
let opts = ["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"];
match opts.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
Some(&"Value") => self.stage = Stage::ValueKind,
Some(&"Position") => self.stage = Stage::Position,
Some(&"Height") => self.stage = Stage::Height,
Some(&"Angle") => self.stage = Stage::Angle,
Some(&"Style") => self.stage = Stage::Style,
Some(&"Layer") => self.stage = Stage::Layer,
Some(&"Color") => self.stage = Stage::Color,
Some(&"Next") => {
self.cur += 1;
if self.cur >= self.items.len() {
return Ok(Step::Done);
}
self.show_current(s);
}
_ => return Err(invalid_keyword()),
}
}
_ => {}
},
Stage::Position => {
let p = match i {
Input::Point(p) => p,
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| move_text(&mut a.text, p))?;
}
self.stage = Stage::Option;
}
Stage::Height => {
let h = match &i {
Input::Point(p) => {
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
match cur_pt {
Some(base) => base.dist(*p).max(1e-9),
None => p.len().max(1e-9),
}
}
Input::Text(t) if !t.trim().is_empty() => crate::units::parse_distance(t.trim())
.filter(|v| *v > 0.0)
.ok_or_else(|| EngineError::Other("Requires a positive number.".into()))?,
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.height = h;
})?;
}
self.stage = Stage::Option;
}
Stage::Angle => {
let ang = match &i {
Input::Point(p) => {
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
match cur_pt {
Some(base) => base.angle_to(*p),
None => p.y.atan2(p.x),
}
}
Input::Text(t) if !t.trim().is_empty() => {
s.angle_settings().direction(t.trim()).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?
}
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.rotation = ang;
})?;
}
self.stage = Stage::Option;
}
Stage::Style => {
let Some(t) = text else { return Ok(Step::Continue) };
let t = t.trim();
if !t.is_empty() {
let st =
s.doc()?.text_style(t).map(|st| st.name.clone()).ok_or_else(|| EngineError::Other(format!("Cannot find style \"{t}\".")))?;
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.style = st;
})?;
}
}
self.stage = Stage::Option;
}
Stage::ValueKind => match &i {
Input::Keyword(k) if k == "Change" => self.stage = Stage::Find,
Input::Keyword(_) | Input::Enter => self.stage = Stage::NewValue,
+8 -27
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("dist", "Distance", run_dist)
.menu(&["Tools", "Inquiry", "Distance"])
.alias(&["di"])
.params("{p1, p2} -> {distance, angle, angleFromXY, dx, dy, dz (world), ucs: {angle, angleFromXY, dx, dy, dz} (in the frame typed points are read in: the current UCS, or the World UCS while the UCS is tilted; as the message), message}")
.params("{p1, p2}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(DistM::default()))),
@@ -192,18 +192,11 @@ fn angle_from_xy(d: Vec3) -> f64 {
d.z.atan2(d.xy().len())
}
/// The delta from `a` to `b` along the axes of the current UCS (the World UCS while that is
/// tilted): what DIST's report shows.
fn dist_delta(s: &Session, a: Vec3, b: Vec3) -> Vec3 {
let u = s.input_ucs();
u.to_ucs3(b) - u.to_ucs3(a)
}
/// DIST's report: the distance, the angles and the deltas `d`, measured in the current UCS.
fn dist_text(s: &Session, dist: f64, d: Vec3) -> String {
fn dist_text(s: &Session, a: Vec3, b: Vec3) -> String {
let d = b - a;
format!(
"Distance = {}, Angle in XY Plane = {}, Angle from XY Plane = {}\nDelta X = {}, Delta Y = {}, Delta Z = {}",
fmt_d(s, dist),
fmt_d(s, (b - a).len()),
fmt_a(s, d.xy().angle()),
fmt_a(s, angle_from_xy(d)),
fmt_d(s, d.x),
@@ -229,8 +222,6 @@ fn run_dist(s: &mut Session, p: &Value) -> Result<Value> {
}
s.distance = d.len();
s.last_point = a.xy();
// Top level: the world values, as ID's x, y, z are; `ucs` has what the message shows.
let du = dist_delta(s, a, b);
Ok(json!({
"distance": d.len(),
"angle": d.xy().angle().to_degrees(),
@@ -238,28 +229,18 @@ fn run_dist(s: &mut Session, p: &Value) -> Result<Value> {
"dx": d.x,
"dy": d.y,
"dz": d.z,
"ucs": {
"angle": du.xy().angle().to_degrees(),
"angleFromXY": angle_from_xy(du).to_degrees(),
"dx": du.x,
"dy": du.y,
"dz": du.z,
},
"message": dist_text(s, d.len(), du),
"message": dist_text(s, a, b),
}))
}
/// ID's report: the point in the current UCS.
fn id_text(s: &Session, a: Vec3) -> String {
let u = s.input_ucs().to_ucs3(a);
format!("X = {} Y = {} Z = {}", fmt_d(s, u.x), fmt_d(s, u.y), fmt_d(s, u.z))
format!("X = {} Y = {} Z = {}", fmt_d(s, a.x), fmt_d(s, a.y), fmt_d(s, a.z))
}
fn run_id(s: &mut Session, p: &Value) -> Result<Value> {
let a = point3_req(s, "id", p, "at")?;
s.last_point = a.xy();
let u = s.input_ucs().to_ucs3(a);
Ok(json!({ "x": a.x, "y": a.y, "z": a.z, "ucs": [u.x, u.y, u.z], "message": id_text(s, a) }))
Ok(json!({ "x": a.x, "y": a.y, "z": a.z, "message": id_text(s, a) }))
}
/// The Z of what is drawn at `p`: the object a pick finds there, at that point, or the current
@@ -919,7 +900,7 @@ impl Interactive for DistM {
s.last_point = first;
return Err(bad("dist", "the distance is too large"));
}
let t = dist_text(s, (b - a).len(), dist_delta(s, a, b));
let t = dist_text(s, a, b);
for l in t.lines() {
s.echo(l.to_string());
}
+246 -16
View File
@@ -1,6 +1,7 @@
//! Layers: LAYER (programmatic sub-ids, -LAYER prompts), layer tools (LAYMCUR, LAYISO, LAYOFF, LAYFRZ…).
mod prompts;
mod state_prompts;
use cadcraft_color::Color;
use cadcraft_doc::{Layer, Lineweight};
@@ -55,7 +56,9 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("layon", "Turn All Layers On", |s, _| all_layers(s, |l| l.on = true)),
CommandSpec::new("laythw", "Thaw All Layers", |s, _| all_layers(s, |l| l.frozen = false)),
CommandSpec::new("layerp", "Previous Layer", run_layerp).menu(&["Format", "Layer Tools", "Previous Layer"]),
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save).menu(&["Format", "Layer States Manager..."]).params("{name}"),
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save)
.menu(&["Format", "Layer States Manager..."])
.params("{name, mask? (properties restoring sets: 1 on, 2 frozen, 4 locked, 8 plot, 16 new viewport freeze, 32 color, 64 linetype, 128 lineweight, 256 plot style, 1024 transparency; default all)}"),
CommandSpec::new("layerstate.restore", "Restore Layer State", run_state_restore).params("{name}"),
CommandSpec::new("layerstate.list", "List Layer States", run_state_list).params("{} → states").noundo(),
CommandSpec::new("layerstate.delete", "Delete Layer State", run_state_delete).params("{name}"),
@@ -400,31 +403,108 @@ fn all_layers(s: &mut Session, f: fn(&mut Layer)) -> Result<Value> {
}
fn run_state_save(s: &mut Session, p: &Value) -> Result<Value> {
use cadcraft_doc::LayerState as S;
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.save", "`name` is required"))?.to_string();
// As -LAYER stAte Save and layerstate.rename take names: none empty, over 255 characters, with a
// control character or with one AutoCAD 2024 refuses (measured for Save).
if !valid_name(&name) {
return Err(bad("layerstate.save", "invalid name"));
}
// The properties restoring sets; bit 512, which no property toggles, is always set, as AutoCAD
// 2024 saves it (measured: On alone is 513).
let mask = match p.get("mask") {
None | Some(Value::Null) => S::ALL,
Some(v) => {
let m = v.as_u64().filter(|m| m & !u64::from(S::ALL) == 0);
m.and_then(|m| u32::try_from(m).ok()).ok_or_else(|| bad("layerstate.save", "`mask` must be a sum of layer state bits (0 to 2047)"))? | 512
}
};
let d = s.doc_mut()?;
let layers = d.layers.clone();
d.layer_states.retain(|st| st.name != name);
d.layer_states.push(cadcraft_doc::LayerState { name, layers });
let current = d.header.str("CLAYER", "0");
// Replace the state Restore and Delete reach (the same spelling, else another case), so a
// drawing keeps one state per name: AutoCAD 2024 finds states without regard to case. Its
// -LAYER stAte Save and layerstate-save refuse `s1` after `S1` (measured), as the command line
// here does; this command replaces, as it does a state of the same spelling. When a file holds
// both `S1` and `s1`, only the one spelled so is replaced.
if let Some(i) = state_index(d, &name) {
d.layer_states.remove(i);
}
d.layer_states.push(S { mask, ..S::new(name, layers, current) });
ok()
}
/// The saved state called `name`: the one spelled so, else the first whose name differs only in
/// case. AutoCAD 2024 finds layer states without regard to case (measured: Restore, Edit, Name
/// and Delete of `s1` reach `S1`); case is compared as for layers and view snapshots.
pub(super) fn state_index(d: &cadcraft_doc::Drawing, name: &str) -> Option<usize> {
d.layer_states.iter().position(|st| st.name == name).or_else(|| d.layer_states.iter().position(|st| st.name.eq_ignore_ascii_case(name)))
}
fn run_state_restore(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.restore", "`name` is required"))?;
let d = s.doc_mut()?;
let st = d.layer_states.iter().find(|st| st.name == name).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
restore_layers(d, st.layers);
let st = state_index(d, name).and_then(|i| d.layer_states.get(i)).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
restore_state(d, &st);
ok()
}
/// Restore a saved layer state as AutoCAD 2024 does (measured): first the current layer it
/// names, when the drawing has it and the restore doesn't leave it frozen, then on each drawing
/// layer the state names (without regard to case) the properties its mask covers. The current
/// layer is never frozen; other properties (descriptions, names) stay as they are.
pub(crate) fn restore_state(d: &mut cadcraft_doc::Drawing, st: &cadcraft_doc::LayerState) {
use cadcraft_doc::LayerState as S;
// A frozen layer only thaws with Frozen in the mask and an entry of its own: without one
// AutoCAD 2024 keeps the current layer (measured).
let thaws = |l: &Layer| st.mask & S::FROZEN != 0 && st.layers.iter().any(|saved| saved.name.eq_ignore_ascii_case(&l.name));
if let Some(l) = d.layer(&st.current).filter(|l| !l.frozen || thaws(l)) {
let name = l.name.clone();
d.header.set_str("CLAYER", &name);
}
let current = d.header.str("CLAYER", "0");
let index = layer_index(d);
let has = |bit: u32| st.mask & bit != 0;
for saved in &st.layers {
let Some(l) = index.get(&saved.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) else { continue };
if has(S::ON) {
l.on = saved.on;
}
if has(S::FROZEN) {
l.frozen = saved.frozen && !l.name.eq_ignore_ascii_case(&current);
}
if has(S::LOCKED) {
l.locked = saved.locked;
}
if has(S::PLOT) {
l.plot = saved.plot;
}
if has(S::VP_FREEZE_NEW) {
l.vp_freeze_new = saved.vp_freeze_new;
}
if has(S::COLOR) {
l.color = saved.color;
}
if has(S::LINETYPE) {
l.linetype.clone_from(&saved.linetype);
}
if has(S::LINEWEIGHT) {
l.lineweight = saved.lineweight;
}
if has(S::PLOT_STYLE) {
l.plot_style.clone_from(&saved.plot_style);
}
if has(S::TRANSPARENCY) {
l.transparency = saved.transparency;
}
}
}
/// Put the saved layers back over the drawing's layers of the same name (without regard to case);
/// saved layers the drawing no longer has are skipped. Both lists can come from a file, so the
/// drawing's layers are looked up in an index rather than scanned per saved layer.
pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::with_capacity(d.layers.len());
for (i, l) in d.layers.iter().enumerate() {
// The first of names that differ only in case, as `Drawing::layer_mut` finds it.
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
}
let index = layer_index(d);
for layer in saved {
if let Some(l) = index.get(&layer.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) {
*l = layer;
@@ -432,6 +512,16 @@ pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
}
}
/// The drawing's layers by lower-case name: the first of names that differ only in case, as
/// `Drawing::layer_mut` finds it.
fn layer_index(d: &cadcraft_doc::Drawing) -> std::collections::HashMap<String, usize> {
let mut index = std::collections::HashMap::with_capacity(d.layers.len());
for (i, l) in d.layers.iter().enumerate() {
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
}
index
}
fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc()?;
let states: Vec<Value> = d.layer_states.iter().map(|st| json!({ "name": st.name, "layers": st.layers.len() })).collect();
@@ -446,10 +536,8 @@ fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
fn run_state_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.delete", "`name` is required"))?;
let d = s.doc_mut()?;
if !d.layer_states.iter().any(|st| st.name == name) {
return Err(bad("layerstate.delete", "no such layer state"));
}
d.layer_states.retain(|st| st.name != name);
let i = state_index(d, name).ok_or_else(|| bad("layerstate.delete", "no such layer state"))?;
d.layer_states.remove(i);
ok()
}
@@ -460,10 +548,12 @@ fn run_state_rename(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("layerstate.rename", "invalid name"));
}
let d = s.doc_mut()?;
if d.layer_states.iter().any(|st| st.name == to) {
// A name in another case counts, the state's own too (AutoCAD 2024 refuses `S1` to `s1`,
// measured).
if d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(&to)) {
return Err(bad("layerstate.rename", format!("layer state `{to}` already exists")));
}
let st = d.layer_states.iter_mut().find(|st| st.name == from).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
let st = state_index(d, from).and_then(|i| d.layer_states.get_mut(i)).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
st.name = to;
ok()
}
@@ -516,6 +606,146 @@ mod tests {
assert!(used.contains(&true) && used.contains(&false));
}
/// Restoring follows AutoCAD 2024 (measured with -LAYER stAte and states written into a DXF):
/// the current layer first, then only the properties the mask covers; the current layer stays
/// thawed; a current layer that is empty or gone leaves the current layer as it is.
#[test]
fn layer_state_restore_follows_the_mask_and_current_layer() {
use cadcraft_color::Color;
use cadcraft_doc::LayerState;
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "A", "color": 1, "current": true })).unwrap();
s.execute("layer.new", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
let saved = s.doc().unwrap().layer_states[0].clone();
assert_eq!((saved.mask, saved.current.as_str()), (LayerState::ALL, "A"));
// Only On: A's colour stays green, B comes back on (AutoCAD's S7, mask 513).
let d = s.doc_mut().unwrap();
d.layer_states.push(LayerState { name: "on".into(), mask: LayerState::ON | 512, ..saved.clone() });
s.execute("layer.set", &json!({ "name": "A", "color": 3 })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "on": false, "locked": true })).unwrap();
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "on" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
let (a, b) = (d.layer("A").unwrap(), d.layer("B").unwrap());
assert_eq!((a.color, b.on, b.locked), (Color::Index(3), true, true));
// Every property.
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.layer("B").unwrap().locked), (Color::Index(1), false));
// A state that freezes B with no current layer of its own (or one that is gone), restored
// with B current: B stays current and thawed; A is turned off.
for current in ["", "NOSUCH"] {
let mut frozen = s.doc().unwrap().layers.clone();
for l in &mut frozen {
l.frozen = l.name == "B";
l.on = l.name != "A";
}
s.doc_mut().unwrap().layer_states.push(LayerState::new(format!("f{current}"), frozen.clone(), current));
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": format!("f{current}") })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B", "{current:?}");
assert!(!d.layer("B").unwrap().frozen && !d.layer("A").unwrap().on, "{current:?}");
// Naming A current, it becomes current and B freezes.
s.doc_mut().unwrap().layer_states.push(LayerState::new("fA", frozen, "A"));
s.execute("layerstate.restore", &json!({ "name": "fA" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
s.doc_mut().unwrap().layer_states.retain(|st| st.name != "fA");
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
}
// A current layer the state's mask leaves frozen doesn't become current (AutoCAD's S9: On
// only, current B; restored with A current and B frozen).
let mut on_only = s.doc().unwrap().layer_states[0].clone();
(on_only.name, on_only.mask, on_only.current) = ("S9".into(), LayerState::ON | 512, "B".into());
s.doc_mut().unwrap().layer_states.push(on_only);
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "S9" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
// With Frozen in the mask B is thawed and made current.
let mut thaw = s.doc().unwrap().layer_states[0].clone();
(thaw.name, thaw.current) = ("thaw".into(), "B".into());
s.doc_mut().unwrap().layer_states.push(thaw);
s.execute("layerstate.restore", &json!({ "name": "thaw" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B");
assert!(!d.layer("B").unwrap().frozen);
// Frozen in the mask, but no entry for B (a state written elsewhere): nothing would thaw
// B, so A stays current and B frozen (AutoCAD 2024, measured).
let mut no_entry = s.doc().unwrap().layer_states[0].clone();
(no_entry.name, no_entry.current) = ("no entry".into(), "B".into());
no_entry.layers.retain(|l| l.name != "B");
s.doc_mut().unwrap().layer_states.push(no_entry);
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "no entry" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
// An entry spelled in another case is B's (layer names ignore case, as the restore of the
// properties does): B is thawed and made current.
let mut other_case = s.doc().unwrap().layer_states[0].clone();
(other_case.name, other_case.current) = ("other case".into(), "B".into());
for l in other_case.layers.iter_mut().filter(|l| l.name == "B") {
l.name = "b".into();
}
s.doc_mut().unwrap().layer_states.push(other_case);
s.execute("layerstate.restore", &json!({ "name": "other case" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B");
assert!(!d.layer("B").unwrap().frozen);
// What a state doesn't hold stays: the description.
s.execute("layer.set", &json!({ "name": "A", "description": "kept" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
assert_eq!(s.doc().unwrap().layer("A").unwrap().description, "kept");
}
/// Plotting, freezing in new viewports, linetype, lineweight, plot style and transparency each
/// come back under their own mask bit only: a state of one bit restores that property and
/// leaves the other five as they are.
#[test]
fn layer_state_restores_each_property_under_its_own_bit_only() {
use cadcraft_doc::{Drawing, LayerState as S, Lineweight};
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "A" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
let saved = s.doc().unwrap().layer_states[0].clone();
let props = |d: &Drawing| {
let l = d.layer("A").unwrap();
(l.plot, l.vp_freeze_new, l.linetype.clone(), l.lineweight, l.plot_style.clone(), l.transparency)
};
let change = |d: &mut Drawing| {
let l = d.layer_mut("A").unwrap();
(l.plot, l.vp_freeze_new, l.linetype, l.lineweight, l.plot_style, l.transparency) =
(false, true, "DASHED".into(), Lineweight::from_dxf(50), "Thick".into(), 40);
};
let before = props(s.doc().unwrap());
change(s.doc_mut().unwrap());
let after = props(s.doc().unwrap());
for bit in [S::PLOT, S::VP_FREEZE_NEW, S::LINETYPE, S::LINEWEIGHT, S::PLOT_STYLE, S::TRANSPARENCY] {
let name = format!("b{bit}");
s.doc_mut().unwrap().layer_states.push(S { name: name.clone(), mask: bit | 512, ..saved.clone() });
change(s.doc_mut().unwrap());
s.execute("layerstate.restore", &json!({ "name": name })).unwrap();
let mut want = after.clone();
match bit {
S::PLOT => want.0 = before.0,
S::VP_FREEZE_NEW => want.1 = before.1,
S::LINETYPE => want.2.clone_from(&before.2),
S::LINEWEIGHT => want.3 = before.3,
S::PLOT_STYLE => want.4.clone_from(&before.4),
_ => want.5 = before.5,
}
assert_eq!(props(s.doc().unwrap()), want, "mask {bit}");
}
}
#[test]
fn rejected_layer_set_changes_nothing() {
let mut s = Session::new();
+20 -7
View File
@@ -8,6 +8,7 @@ use serde_json::{Value, json};
use super::super::find_command;
use super::super::qselect::wildcard;
use super::state_prompts;
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
const OPTIONS: &[&str] = &[
@@ -34,9 +35,9 @@ const OPTIONS: &[&str] = &[
];
/// Keyword-only: spaces separate inputs.
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
pub(super) const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
/// A name or value: Space ends the input, as it does in AutoCAD scripts.
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
pub(super) const NAME: Accept = Accept { number: true, ..Accept::TEXT };
/// A per-layer change applied to a list of layer names.
#[derive(Clone, Debug)]
@@ -111,6 +112,8 @@ enum Stage {
Layers(Change),
/// Turning the current layer off asks first.
ConfirmOff(Vec<String>),
/// stAte and its options.
State(state_prompts::Stage),
}
#[derive(Default)]
@@ -123,19 +126,19 @@ fn current_layer(s: &Session) -> String {
}
/// Run a layer command's body directly: the running command records the single undo step.
fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
pub(super) fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
(spec.run)(s, p)
}
fn message(e: &EngineError) -> String {
pub(super) fn message(e: &EngineError) -> String {
match e {
EngineError::BadParams { msg, .. } => msg.clone(),
other => other.to_string(),
}
}
fn retry(msg: impl Into<String>) -> EngineError {
pub(super) fn retry(msg: impl Into<String>) -> EngineError {
EngineError::Other(msg.into())
}
@@ -188,8 +191,9 @@ impl LayerM {
"LOck" => Stage::Layers(Change::Lock),
"Unlock" => Stage::Layers(Change::Unlock),
"Description" => Stage::Description,
"stAte" => Stage::State(state_prompts::Stage::Option),
other => {
// MATerial, stAte, rEconcile: report and stay at the option prompt.
// MATerial, rEconcile: report and stay at the option prompt.
s.echo(format!("-LAYER {other} is not available yet."));
Stage::Option
}
@@ -262,7 +266,7 @@ impl LayerM {
Ok(Step::Continue)
};
match stage {
Stage::Option => Ok(Step::Continue),
Stage::Option | Stage::State(_) => Ok(Step::Continue),
Stage::List => {
self.list(s, text.as_deref().unwrap_or("*"));
Ok(Step::Continue)
@@ -434,9 +438,18 @@ impl Interactive for LayerM {
if enter_is_current { p.default(cur) } else { p }
}
Stage::ConfirmOff(_) => Prompt::new(format!("Really want layer \"{cur}\" (the CURRENT layer) off?"), KW).kw(&["Yes", "No"]).default("N"),
Stage::State(st) => st.prompt(),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Stage::State(st) = &mut self.stage
&& !matches!(i, Input::Cancel)
{
if !st.input(s, &i)? {
self.stage = Stage::Option;
}
return Ok(Step::Continue);
}
match (&self.stage, &i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(Stage::Option, Input::Enter) => Ok(Step::Done),
@@ -0,0 +1,256 @@
//! -LAYER stAte: save, restore, edit, rename, delete and list the drawing's layer states, with
//! AutoCAD 2024's prompts and messages (measured). Save, Restore, Name and Delete run the
//! `layerstate.*` commands; Edit changes the state's mask in place.
use cadcraft_doc::LayerState as LS;
use serde_json::{Value, json};
use super::prompts::{KW, NAME, call, message, retry};
use super::{state_index, valid_name};
use crate::{Input, Prompt, Result, Session};
/// The options after stAte. Import and EXport (layer state files) are not available yet.
const OPTIONS: &[&str] = &["?", "Save", "Restore", "Edit", "Name", "Delete", "Import", "EXport"];
/// "Enter states to change": each keyword, the name AutoCAD 2024 lists it by and its mask bit, in
/// AutoCAD's order.
const TOGGLES: [(&str, &str, u32); 10] = [
("On", "On", LS::ON),
("Frozen", "Frozen", LS::FROZEN),
("Lock", "Lock", LS::LOCKED),
("Plot", "Plot", LS::PLOT),
("Newvpfreeze", "Newvpfreeze", LS::VP_FREEZE_NEW),
("Color", "Color", LS::COLOR),
("lineType", "lineType", LS::LINETYPE),
("lineWeight", "lineWeight", LS::LINEWEIGHT),
("TRansparency", "Transparency", LS::TRANSPARENCY),
("plotStyle", "plotStyle", LS::PLOT_STYLE),
];
/// The options that ask for a saved state's name.
#[derive(Clone, Copy, Debug)]
pub(super) enum Pick {
Restore,
Edit,
Name,
Delete,
}
impl Pick {
fn verb(self) -> &'static str {
match self {
Pick::Restore => "restore",
Pick::Edit => "edit",
Pick::Name => "rename",
Pick::Delete => "delete",
}
}
}
#[derive(Clone, Debug, Default)]
pub(super) enum Stage {
#[default]
Option,
/// Save: the new state's name.
SaveName,
/// Restore, Edit, Name or Delete: the saved state's name.
Pick(Pick),
/// Name: the new name of the state called so.
RenameTo(String),
/// "Enter states to change" for the state `name`: one Save makes on Enter, or one Edit
/// changes (`edit`).
Toggles { name: String, mask: u32, edit: bool },
}
impl Stage {
pub(super) fn prompt(&self) -> Prompt {
match self {
Stage::Option => Prompt::new("Enter an option", KW).kw(OPTIONS),
Stage::SaveName | Stage::RenameTo(_) => Prompt::new("Enter new layer state name", NAME),
Stage::Pick(p) => Prompt::new(format!("Enter name of layer state to {}", p.verb()), NAME).kw(&["?"]),
Stage::Toggles { .. } => Prompt::new("Enter states to change", KW).kw(&TOGGLES.map(|t| t.0)),
}
}
/// One input. `Ok(false)`: back to -LAYER's options. An invalid input leaves the stage as it
/// is, so the prompt is asked again.
pub(super) fn input(&mut self, s: &mut Session, i: &Input) -> Result<bool> {
let text = match i {
Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()),
_ => None,
};
let next = match std::mem::take(self) {
Stage::Option => match i {
Input::Enter => return Ok(false),
Input::Keyword(k) => option(s, k),
_ => return Err(retry("Invalid option keyword.")),
},
Stage::SaveName => match text {
None => Stage::Option,
Some(n) => save_name(s, n),
},
Stage::Pick(p) => match (i, text) {
(Input::Keyword(k), _) if k == "?" => {
list(s);
Stage::Pick(p)
}
(_, None) => Stage::Option,
(_, Some(n)) => pick(s, p, &n),
},
Stage::RenameTo(from) => {
if let Some(to) = text {
rename(s, &from, &to);
}
Stage::Option
}
Stage::Toggles { name, mut mask, edit } => match i {
Input::Keyword(k) => {
if let Some(&(_, _, bit)) = TOGGLES.iter().find(|t| t.0 == k) {
mask ^= bit;
}
show(s, mask);
Stage::Toggles { name, mask, edit }
}
Input::Enter => {
finish(s, &name, mask, edit);
Stage::Option
}
_ => {
*self = Stage::Toggles { name, mask, edit };
return Err(retry("Invalid option keyword."));
}
},
};
*self = next;
Ok(true)
}
}
fn option(s: &mut Session, k: &str) -> Stage {
match k {
"?" => {
list(s);
Stage::Option
}
"Save" => Stage::SaveName,
"Restore" => Stage::Pick(Pick::Restore),
"Edit" => Stage::Pick(Pick::Edit),
"Name" => Stage::Pick(Pick::Name),
"Delete" => Stage::Pick(Pick::Delete),
other => {
s.echo(format!("-LAYER stAte {other} is not available yet."));
Stage::Option
}
}
}
/// Whether a saved state has the name `n` in any case.
fn taken(s: &Session, n: &str) -> bool {
s.doc().is_ok_and(|d| d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(n)))
}
/// Save's name: refused (asked again) when it has a character AutoCAD 2024 refuses (the layer
/// name ones, measured one by one), is longer than 255 characters (measured 256), or is a saved
/// state's name in any case (measured `s1` after `S1`).
fn save_name(s: &mut Session, n: String) -> Stage {
if !valid_name(&n) {
s.echo(format!("\"{n}\" is an invalid layer state name."));
return Stage::SaveName;
}
if taken(s, &n) {
s.echo(format!("Layer state \"{n}\" already exists."));
return Stage::SaveName;
}
let mask = s.settings.layer_state_mask;
show(s, mask);
Stage::Toggles { name: n, mask, edit: false }
}
fn pick(s: &mut Session, p: Pick, n: &str) -> Stage {
let found = s.doc().ok().and_then(|d| state_index(d, n).and_then(|i| d.layer_states.get(i)).map(|st| (st.name.clone(), st.mask)));
let Some((name, mask)) = found else {
s.echo("Unknown layer state name.");
return Stage::Pick(p);
};
match p {
Pick::Restore => {
run(s, "layerstate.restore", &json!({ "name": name }));
Stage::Option
}
Pick::Delete => {
run(s, "layerstate.delete", &json!({ "name": name }));
Stage::Option
}
Pick::Edit => {
show(s, mask);
Stage::Toggles { name, mask, edit: true }
}
Pick::Name => Stage::RenameTo(name),
}
}
/// Name's new name. A name some state has in any case, the state's own too, is refused with
/// AutoCAD 2024's two lines (measured `S2` onto `S2`, `S1` onto `s1`). A name with a character
/// AutoCAD refuses leaves the state as it is with no message, as AutoCAD does (measured `a,b`,
/// `a<b`); AutoCAD renames to a name starting with "*" as an anonymous `*A1`, and CADCraft leaves
/// that state as it is too.
fn rename(s: &mut Session, from: &str, to: &str) {
if taken(s, to) {
s.echo("Layer state could not be renamed.");
s.echo(format!("{to} already exists."));
} else if valid_name(to) {
run(s, "layerstate.rename", &json!({ "from": from, "to": to }));
}
}
/// Enter at "Enter states to change": Save makes the state with this mask and keeps the toggles
/// for the next Save; Edit sets the state's mask and keeps the bits no toggle reaches (AutoCAD's
/// 65536 after a restore). Edit leaves the next Save's toggles alone (measured).
fn finish(s: &mut Session, name: &str, mask: u32, edit: bool) {
if !edit {
if run(s, "layerstate.save", &json!({ "name": name, "mask": mask & LS::ALL })) {
s.settings.layer_state_mask = mask & LS::ALL;
}
return;
}
// Only a changed mask touches the drawing.
let Ok(d) = s.doc() else { return };
let Some(i) = state_index(d, name).filter(|&i| d.layer_states.get(i).is_some_and(|st| st.mask != mask)) else { return };
if let Ok(d) = s.doc_mut()
&& let Some(st) = d.layer_states.get_mut(i)
{
st.mask = mask;
}
}
/// Run a `layerstate.*` command, reporting a refusal; `true` when it ran.
fn run(s: &mut Session, id: &str, p: &Value) -> bool {
match call(s, id, p) {
Ok(_) => true,
Err(e) => {
s.echo(message(&e));
false
}
}
}
/// The toggles as AutoCAD 2024 lists them before "Enter states to change".
fn show(s: &mut Session, mask: u32) {
s.echo("States");
for (_, label, bit) in TOGGLES {
s.echo(format!("{label:<20}{}", if mask & bit != 0 { "Yes" } else { "No" }));
}
}
/// `?`: every saved state by name without regard to case, as AutoCAD 2024 lists them (measured:
/// `S2`, `b`, `S1` saved in that order list as `b`, `S1`, `S2`; a name starting with "*", its
/// `*A1`, is listed too).
fn list(s: &mut Session) {
let mut names: Vec<String> = s.doc().map(|d| d.layer_states.iter().map(|st| st.name.clone()).collect()).unwrap_or_default();
names.sort_by_cached_key(|n| n.to_ascii_lowercase());
s.echo("Layer state");
s.echo("-".repeat(29));
for n in names {
s.echo(n);
}
}
+1 -10
View File
@@ -313,16 +313,7 @@ fn run_copy(s: &mut Session, p: &Value) -> Result<Value> {
let h = d.new_handle();
store.push(Entity { handle: h, ..Entity::clone(e) });
}
d.layouts.push(Layout {
name: to.clone(),
tab_order: order,
page: src.page,
entities: store,
view: src.view,
ucs: src.ucs,
ucs_previous: Vec::new(),
limits: src.limits,
});
d.layouts.push(Layout { name: to.clone(), tab_order: order, page: src.page, entities: store, view: src.view, limits: src.limits });
Ok(json!({ "name": to }))
}
+2 -2
View File
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("rename", "Rename...", run_rename)
.menu(&["Format", "Rename..."])
.alias(&["ren", "-rename"])
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs, from, to}")
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs|vport, from, to}")
.interactive(|_| Ok(Box::new(rename::RenameM::default()))),
]
}
@@ -995,7 +995,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
"block" => rename::block(s, &from, &to)?,
"mleaderstyle" | "multileaderstyle" => rename::simple(s, "mleaderstyle", &from, &to)?,
"tablestyle" | "view" | "ucs" => rename::simple(s, &table, &from, &to)?,
"tablestyle" | "view" | "ucs" | "vport" => rename::simple(s, &table, &from, &to)?,
"style" | "textstyle" => {
run_style_rename(s, &json!({ "from": from, "to": to }))?;
}
+81 -16
View File
@@ -93,6 +93,8 @@ pub(super) fn simple(s: &mut Session, table: &str, from: &str, to: &str) -> Resu
"tablestyle" => d.table_styles.iter_mut().map(|t| &mut t.name).collect(),
"view" => d.views.iter_mut().map(|t| &mut t.name).collect(),
"ucs" => d.ucss.iter_mut().map(|t| &mut t.name).collect(),
// A saved viewport configuration, every tile of it; never the one shown (`*Active`).
"vport" => d.vports.iter_mut().filter(|v| !v.is_active()).map(|t| &mut t.name).collect(),
_ => return Err(bad("rename", "unsupported table")),
};
if !to.eq_ignore_ascii_case(from) && names.iter().any(|n| n.eq_ignore_ascii_case(&to)) {
@@ -134,35 +136,47 @@ const TYPES: &[(&str, Option<&str>, &str)] = &[
("Plotstyle", None, "plot style"),
("textStyle", Some("style"), "text style"),
("Tablestyle", Some("tablestyle"), "table style"),
("Ucs", Some("ucs"), "UCS"),
("Ucs", Some("ucs"), "ucs"),
("VIew", Some("view"), "view"),
("VPort", None, "viewport configuration"),
("VPort", Some("vport"), "viewport configuration"),
];
/// The noun in "Cannot find …" and "Invalid … name.": AutoCAD 2024 writes "UCS" there, "ucs" in
/// its prompts and in "A ucs named … already exists." (measured).
fn title(noun: &str) -> &str {
if noun == "ucs" { "UCS" } else { noun }
}
/// Keyword-only: spaces separate inputs.
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
/// A name: Space ends the input.
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> bool {
names.any(|n| n.eq_ignore_ascii_case(name))
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> Option<String> {
names.find(|n| n.eq_ignore_ascii_case(name)).cloned()
}
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
/// The name as the drawing spells it of the `table` entry named `name` (without regard to case).
fn stored(d: &Drawing, table: &str, name: &str) -> Option<String> {
match table {
"block" => d.block(name).is_some(),
"layer" => d.layer(name).is_some(),
"linetype" => d.linetype(name).is_some(),
"style" => d.text_style(name).is_some(),
"dimstyle" => d.dim_style(name).is_some(),
"block" => d.block(name).map(|t| t.name.clone()),
"layer" => d.layer(name).map(|t| t.name.clone()),
"linetype" => d.linetype(name).map(|t| t.name.clone()),
"style" => d.text_style(name).map(|t| t.name.clone()),
"dimstyle" => d.dim_style(name).map(|t| t.name.clone()),
"mleaderstyle" => any_named(d.mleader_styles.iter().map(|t| &t.name), name),
"tablestyle" => any_named(d.table_styles.iter().map(|t| &t.name), name),
"view" => any_named(d.views.iter().map(|t| &t.name), name),
"ucs" => any_named(d.ucss.iter().map(|t| &t.name), name),
_ => true,
"vport" => any_named(d.vports.iter().filter(|v| !v.is_active()).map(|t| &t.name), name),
_ => Some(name.to_string()),
}
}
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
stored(d, table, name).is_some()
}
#[derive(Default)]
enum Stage {
#[default]
@@ -199,6 +213,15 @@ impl Interactive for RenameM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
// No new name is an invalid one (AutoCAD 2024, measured for layers, blocks, views and
// viewport configurations).
if i == Input::Enter
&& let Stage::New(t, _) = &self.stage
&& let Some((_, Some(_), noun)) = TYPES.get(*t)
{
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
}
if matches!(i, Input::Cancel | Input::Enter) {
return Ok(if i == Input::Cancel { Step::Cancel } else { Step::Done });
}
@@ -217,12 +240,41 @@ impl Interactive for RenameM {
self.stage = Stage::Old(t);
return Ok(Step::Continue);
};
if let Some(table) = table
&& !exists(s.doc()?, table, &name)
{
self.stage = Stage::Old(t);
return Err(EngineError::Other(format!("No {noun} named \"{name}\".")));
// AutoCAD 2024 ends -RENAME on an old name it won't rename (measured): "Invalid … name."
// for a viewport configuration or block whose name starts with "*" (*Active,
// *Model_Space, an anonymous block's *U0) and for linetypes ByLayer and ByBlock;
// "Cannot rename …" and "*Invalid*" for layer 0 and linetype Continuous.
let invalid = match *table {
Some("vport" | "block") => name.starts_with('*'),
Some("linetype") => name.eq_ignore_ascii_case("bylayer") || name.eq_ignore_ascii_case("byblock"),
_ => false,
};
if invalid {
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
}
let fixed = match *table {
Some("layer") => name == "0",
Some("linetype") => name.eq_ignore_ascii_case("continuous"),
_ => false,
};
if fixed {
s.echo(format!("Cannot rename {} \"{name}\".", title(noun)));
s.echo("*Invalid*");
return Ok(Step::Done);
}
// The old name as the drawing spells it: a new name in another case than that is a
// rename, even when it is the old name as typed (AutoCAD 2024, measured).
let name = match table {
Some(table) => match stored(s.doc()?, table, &name) {
Some(n) => n,
None => {
s.echo(format!("Cannot find {} \"{name}\".", title(noun)));
return Ok(Step::Done);
}
},
None => name,
};
self.stage = Stage::New(t, name);
Ok(Step::Continue)
}
@@ -235,6 +287,19 @@ impl Interactive for RenameM {
s.echo(format!("Renaming a {noun} is not available yet."));
return Ok(Step::Done);
};
// AutoCAD 2024's messages, each ending the command (measured).
if !valid_name(&name) {
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
}
if !name.eq_ignore_ascii_case(&old) && exists(s.doc()?, table, &name) {
s.echo(format!("A {noun} named \"{name}\" already exists."));
s.echo("*Invalid*");
return Ok(Step::Done);
}
if name == old {
return Ok(Step::Done);
}
match super::run_rename(s, &json!({ "table": table, "from": old, "to": name })) {
Ok(_) => Ok(Step::Done),
Err(e) => {
-675
View File
@@ -1,675 +0,0 @@
//! UCS an UCSICON: the current user coordinate system ([`crate::ucs`]) and its icon.
//!
//! UCS sets the current UCS of the space commands act on: by an origin and points on the new X
//! axis and XY plane (the default option), World, Previous, NAmed (Restore, Save, Delete, `?`),
//! OBject (lined up with an object), View and Z (a turn about Z). X, Y, ZAxis and Face tilt the
//! UCS out of the XY plane, which CADCraft doesn't draw in yet; they say so. A UCS change is part
//! of the command's undo step, as an edit is.
use cadcraft_doc::{Drawing, EntityKind, Ucs};
use cadcraft_geom::{Vec2, Vec3};
use serde_json::{Value, json};
use super::utility::num_text;
use super::{CommandSpec, bad, str_param};
use crate::prompt::{Accept, Input, Interactive, Prompt, Step};
use crate::ucs::{UcsFrame, named};
use crate::{EngineError, Result, Session};
/// The UCS command's options, as typed.
const OPTIONS: &[&str] = &["Face", "NAmed", "OBject", "Previous", "View", "World", "X", "Y", "Z", "ZAxis"];
/// Characters a UCS name can't hold.
const BAD_NAME_CHARS: &[char] = &['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`'];
/// Longest UCS name.
const MAX_NAME: usize = 255;
/// Most UCS table records a drawing keeps (a hostile script can't grow it without bound).
const MAX_NAMED: usize = 10_000;
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("ucs", "UCS", run_ucs)
.params(
"{option?: origin|world|previous|named|object|view|z|x|y|zaxis|face (default origin), origin?: [x,y(,z)], xPoint?, xyPoint? \
(origin: the new origin, and points on its positive X axis and on the positive-Y side of its XY plane; without them \
the axes stay), angle? (z: degrees counterclockwise about Z, default UCSAXISANG), action?: restore|save|delete|list \
(named), name? (named; delete and list take wildcards and commas), replace?: bool (save over an existing name), \
handle?, at? (object: the object and the point it is picked at)} → {ucs: {name, origin, xAxis, yAxis}}. Points \
are world coordinates. x, y, zaxis and face tilt the UCS out of the XY plane and are not available yet.",
)
.interactive(|_| Ok(Box::new(UcsM::default()))),
CommandSpec::new("ucs.world", "World", |s, p| run_ucs(s, &with_option(p, "world")))
.menu(&["Tools", "New UCS", "World"])
.params("{} (the World UCS)"),
CommandSpec::new("ucs.origin", "Origin", |s, p| run_ucs(s, &with_option(p, "origin")))
.menu(&["Tools", "New UCS", "Origin"])
.params("{origin: [x,y(,z)]} (moves the UCS, keeping its axes)")
.interactive(|_| Ok(Box::new(UcsM::starting(Stage::OriginOnly)))),
CommandSpec::new("ucs.3point", "3 Point", |s, p| run_ucs(s, &with_option(p, "origin")))
.menu(&["Tools", "New UCS", "3 Point"])
.params("{origin, xPoint?, xyPoint?} (as `ucs` origin)")
.interactive(|_| Ok(Box::new(UcsM::starting(Stage::ThreePoint)))),
CommandSpec::new("ucs.view", "View", |s, p| run_ucs(s, &with_option(p, "view")))
.menu(&["Tools", "New UCS", "View"])
.params("{} (XY plane square to the view, X along the screen's horizontal so it follows the view twist, origin kept)"),
CommandSpec::new("ucs.z", "Z", |s, p| run_ucs(s, &with_option(p, "z")))
.menu(&["Tools", "New UCS", "Z"])
.params("{angle?} (degrees counterclockwise about Z, default UCSAXISANG)")
.interactive(|_| Ok(Box::new(UcsM::starting(Stage::ZAngle)))),
CommandSpec::new("ucsicon", "UCS Icon", run_ucsicon)
.params("{on?: bool, origin?: bool} (UCSICON: the icon shown, and at the UCS origin when that is on screen) → {on, origin}")
// Undoable like SETVAR: UCSICON lives in the drawing, so without a step of its own an
// undo of the edit before it would put the old value back.
.interactive(|_| Ok(Box::new(UcsIconM))),
]
}
fn with_option(p: &Value, option: &str) -> Value {
let mut p = if p.is_object() { p.clone() } else { json!({}) };
if let Some(o) = p.as_object_mut() {
o.insert("option".into(), json!(option));
}
p
}
/// A JSON point with an optional Z: `[x, y]`, `[x, y, z]` or `{x, y, z?}`.
fn point3(v: &Value) -> Option<Vec3> {
let p = if let Some(a) = v.as_array() {
Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2).and_then(Value::as_f64).unwrap_or(0.0))
} else {
Vec3::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?, v.get("z").and_then(Value::as_f64).unwrap_or(0.0))
};
p.is_finite().then_some(p)
}
fn point3_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Vec3>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => point3(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite point [x, y] or [x, y, z]"))),
}
}
/// `UCS` as JSON: the result is the new current UCS.
fn run_ucs(s: &mut Session, p: &Value) -> Result<Value> {
let option = str_param(p, "option").unwrap_or("origin").trim().to_ascii_lowercase();
match option.as_str() {
"origin" | "3point" => {
let origin = point3_param("ucs", p, "origin")?.ok_or_else(|| bad("ucs", "`origin` ([x, y] or [x, y, z]) is required"))?;
let x = point3_param("ucs", p, "xPoint")?;
let xy = point3_param("ucs", p, "xyPoint")?;
if xy.is_some() && x.is_none() {
return Err(bad("ucs", "`xyPoint` needs `xPoint`"));
}
set_by_points(s, origin, x, xy)?;
}
"world" | "w" => s.set_ucs(UcsFrame::WORLD, "")?,
"previous" | "p" => {
if !s.ucs_previous()? {
return Err(bad("ucs", "there is no previous UCS"));
}
}
"view" | "v" => s.set_ucs(view_ucs(s), "")?,
"z" => {
let deg = match p.get("angle") {
None | Some(Value::Null) => axis_angle(s),
Some(v) => v.as_f64().filter(|a| a.is_finite()).ok_or_else(|| bad("ucs", "`angle` must be a finite number of degrees"))?,
};
rotate_z(s, deg.to_radians())?;
}
"object" | "ob" => {
let h = super::targets(s, p)?.first().copied().ok_or_else(|| bad("ucs", "`handle` (the object) is required"))?;
let at = p.get("at").and_then(super::point_value);
set_by_object(s, h, at)?;
}
"named" | "na" => {
let action = str_param(p, "action").unwrap_or("restore").trim().to_ascii_lowercase();
let name = str_param(p, "name").map(str::trim).unwrap_or_default().to_string();
match action.as_str() {
"restore" | "r" => restore(s, &name).map_err(|e| bad("ucs", e))?,
"save" | "s" => save(s, &name, p.get("replace").and_then(Value::as_bool).unwrap_or(false)).map_err(|e| bad("ucs", e))?,
"delete" | "d" => {
let n = delete(s, if name.is_empty() { "" } else { &name })?;
return Ok(json!({ "deleted": n, "ucs": ucs_json(s) }));
}
"list" | "?" => return Ok(json!({ "list": list(s, if name.is_empty() { "*" } else { &name }), "ucs": ucs_json(s) })),
other => return Err(bad("ucs", format!("unknown named action `{other}` (restore, save, delete or list)"))),
}
}
"x" | "y" | "zaxis" | "za" | "face" | "f" => return Err(bad("ucs", tilted_message(&option))),
other => return Err(bad("ucs", format!("unknown option `{other}`"))),
}
Ok(json!({ "ucs": ucs_json(s) }))
}
fn ucs_json(s: &Session) -> Value {
let (u, name) = s.ucs_named();
let p = |v: Vec3| json!([v.x, v.y, v.z]);
json!({ "name": name, "origin": p(u.origin), "xAxis": p(u.x), "yAxis": p(u.y), "world": u.is_world() })
}
fn tilted_message(option: &str) -> String {
let label = match option {
"x" => "UCS X",
"y" => "UCS Y",
"zaxis" | "za" => "UCS ZAxis",
_ => "UCS Face",
};
format!("{label} tilts the UCS out of the XY plane, which is not available yet.")
}
/// The UCSAXISANG default for Z, in degrees.
fn axis_angle(s: &Session) -> f64 {
s.doc().map(|d| d.header.i64("UCSAXISANG", 90)).unwrap_or(90) as f64
}
/// A 2D point of the current UCS's XY plane as a 3D world point.
fn on_plane(s: &Session, p: Vec2) -> Vec3 {
p.to3(s.ucs().origin.z)
}
/// The UCS through `origin`, with points on its X axis and in its XY plane (world points).
fn set_by_points(s: &mut Session, origin: Vec3, x: Option<Vec3>, xy: Option<Vec3>) -> Result<()> {
let f = s.ucs().from_points(origin, x, xy).ok_or_else(|| EngineError::Other("Those points don't define a UCS: they lie on one line.".into()))?;
if !f.is_planar() {
return Err(EngineError::Other("That UCS is tilted out of the XY plane (or turned over), which is not available yet.".into()));
}
s.set_ucs(f, "")
}
/// UCS View: the XY plane square to the view (a plan view), at the current origin, with X
/// along the screen's horizontal. The drawing appears turned by the view twist (the Model tab's,
/// or the active layout viewport's), so the screen's X is the world direction at -twist.
fn view_ucs(s: &Session) -> UcsFrame {
let twist = cadcraft_geom::norm_angle(s.state().map_or(0.0, |st| st.view().twist));
UcsFrame::WORLD.rotated_z(-twist).with_origin(s.ucs().origin)
}
fn rotate_z(s: &mut Session, angle: f64) -> Result<()> {
let f = s.ucs().rotated_z(angle);
s.set_ucs(f, "")
}
/// UCS OBject: the UCS lined up with object `h`, picked at `at` (world) when known.
fn set_by_object(s: &mut Session, h: cadcraft_doc::Handle, at: Option<Vec2>) -> Result<()> {
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| EngineError::Other("No such object.".into()))?;
let ext = e.common.extrusion;
if ext.is_finite() && (ext.x.abs() > 1e-9 || ext.y.abs() > 1e-9 || ext.z < 0.0) {
return Err(EngineError::Other("That object lies in a tilted plane; a UCS out of the XY plane is not available yet.".into()));
}
let f = object_frame(&s.ucs(), &e.kind, at)?;
s.set_ucs(f, "")
}
/// A frame at `o` whose X axis points along `dir` in the XY plane.
fn along(o: Vec3, dir: Vec2) -> Result<UcsFrame> {
UcsFrame::new(o, dir.to3(0.0), dir.perp().to3(0.0))
.ok_or_else(|| EngineError::Other("That object has no direction to line the UCS up with.".into()))
}
/// The UCS OBject rules: where each kind of object puts the origin and the X axis.
fn object_frame(cur: &UcsFrame, kind: &EntityKind, at: Option<Vec2>) -> Result<UcsFrame> {
let near = |a: Vec2, b: Vec2| at.is_none_or(|p| p.dist(a) <= p.dist(b));
match kind {
// The endpoint nearer the pick; X along the line.
EntityKind::Line(l) => {
let (o, other) = if near(l.a.xy(), l.b.xy()) { (l.a, l.b) } else { (l.b, l.a) };
along(o, other.xy() - o.xy())
}
// The centre; X through the endpoint nearer the pick.
EntityKind::Arc(a) => {
let (e0, e1) = (Vec2::polar(a.center.xy(), a.radius, a.start), Vec2::polar(a.center.xy(), a.radius, a.end));
let e = if near(e0, e1) { e0 } else { e1 };
along(a.center, e - a.center.xy())
}
// The centre; X through the pick.
EntityKind::Circle(c) => {
let d = at.map(|p| p - c.center.xy()).filter(|d| d.len() > 1e-12).unwrap_or(cur.x.xy());
along(c.center, d)
}
// The first vertex; X toward the next one.
EntityKind::LwPolyline(p) => {
let first = p.vertices.first().map(|v| v.p).ok_or_else(|| EngineError::Other("That polyline has no vertices.".into()))?;
let next = p.vertices.iter().map(|v| v.p).find(|q| q.dist(first) > 1e-12).ok_or_else(|| EngineError::Other("That polyline has no length.".into()))?;
along(first.to3(p.elevation), next - first)
}
// The point; the X axis stays as it is.
EntityKind::Point(p) => along(p.p, cur.x.xy()),
// The insertion point; X along the object's rotation.
EntityKind::Text(t) => along(t.insert, Vec2::from_angle(t.rotation)),
EntityKind::AttDef(a) => along(a.text.insert, Vec2::from_angle(a.text.rotation)),
EntityKind::Insert(i) => along(i.insert, Vec2::from_angle(i.rotation)),
// The first corner; X toward the second.
EntityKind::Solid(so) | EntityKind::Trace(so) => {
let [a, b, ..] = so.corners;
along(a, b.xy() - a.xy())
}
// The first corner; X toward the second, Y toward the fourth.
EntityKind::Face3d(f) => {
let [a, b, _, d] = f.corners;
let frame = UcsFrame::new(a, b - a, d - a).ok_or_else(|| EngineError::Other("That face has no area to line the UCS up with.".into()))?;
if frame.is_planar() {
Ok(frame)
} else {
Err(EngineError::Other("That face lies out of the XY plane; a UCS out of it is not available yet.".into()))
}
}
// The middle of the text; the X axis stays as it is.
EntityKind::Dimension(dm) => along(dm.text_mid, cur.x.xy()),
_ => Err(EngineError::Other("The UCS can't be lined up with that kind of object (lines, arcs, circles, polylines, points, text, blocks, 2D solids, 3D faces and dimensions can).".into())),
}
}
/// A usable UCS name, or why not.
fn check_name(name: &str) -> std::result::Result<String, String> {
let n = name.trim();
if n.is_empty() {
return Err("A UCS name is required.".into());
}
if n.chars().count() > MAX_NAME {
return Err(format!("A UCS name has at most {MAX_NAME} characters."));
}
if n.contains(BAD_NAME_CHARS) || n.chars().any(char::is_control) {
return Err(format!("\"{n}\" is not a valid UCS name."));
}
if n.eq_ignore_ascii_case("*WORLD*") || n.eq_ignore_ascii_case("WORLD") {
return Err("\"World\" is the World UCS; save under another name.".into());
}
Ok(n.to_string())
}
fn restore(s: &mut Session, name: &str) -> std::result::Result<(), String> {
let d = s.doc().map_err(|e| e.to_string())?;
let (f, n) = named(d, name).ok_or_else(|| format!("Cannot find UCS \"{}\".", name.trim()))?;
if !f.is_planar() {
// Kept and saved as read, but not current until tilted UCSs are available.
return Err(format!("UCS \"{n}\" is tilted out of the XY plane, which is not available yet."));
}
s.set_ucs(f, &n).map_err(|e| e.to_string())
}
fn exists(d: &Drawing, name: &str) -> bool {
d.ucss.iter().any(|u| u.name.eq_ignore_ascii_case(name))
}
/// Save the current UCS as `name` (replacing a UCS of that name only with `replace`); it is then
/// the current UCS's name.
fn save(s: &mut Session, name: &str, replace: bool) -> std::result::Result<(), String> {
let n = check_name(name)?;
let frame = s.ucs();
let d = s.doc_mut().map_err(|e| e.to_string())?;
match d.ucss.iter_mut().find(|u| u.name.eq_ignore_ascii_case(&n)) {
Some(_) if !replace => return Err(format!("UCS \"{n}\" already exists.")),
Some(u) => *u = frame.record(&u.name.clone()),
None => {
if d.ucss.len() >= MAX_NAMED {
return Err(format!("A drawing keeps at most {MAX_NAMED} named UCSs."));
}
d.ucss.push(frame.record(&n));
}
}
let kept = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(&n)).map(|u| u.name.clone()).unwrap_or(n);
s.set_ucs(frame, &kept).map_err(|e| e.to_string())
}
/// Whether `name` matches one of the comma-separated wildcard patterns.
fn matches(patterns: &str, name: &str) -> bool {
patterns
.split(',')
.map(str::trim)
.filter(|p| !p.is_empty())
.any(|p| super::qselect::wildcard(&p.to_ascii_uppercase(), &name.to_ascii_uppercase()))
}
/// Delete the named UCSs matching `patterns`; the current UCS keeps its axes but loses a deleted
/// name. Returns how many went.
fn delete(s: &mut Session, patterns: &str) -> Result<usize> {
let gone: Vec<String> = s.doc()?.ucss.iter().filter(|u| matches(patterns, &u.name)).map(|u| u.name.clone()).collect();
if gone.is_empty() {
return Ok(0);
}
s.doc_mut()?.ucss.retain(|u| !gone.iter().any(|g| g == &u.name));
// Wherever a deleted name is current (model space's UCSNAME, every layout's UCS) the UCS keeps
// its axes and loses the name; the UCS Previous histories keep their frames the same way.
let d = s.doc_mut()?;
let is_gone = |n: &str| gone.iter().any(|g| g.eq_ignore_ascii_case(n.trim()));
if is_gone(&d.header.str("UCSNAME", "")) {
d.header.set_str("UCSNAME", "");
}
let unname = |u: &mut Ucs| {
if is_gone(&u.name) {
u.name.clear();
}
};
d.ucs_previous.iter_mut().for_each(unname);
for l in &mut d.layouts {
l.ucs.iter_mut().for_each(unname);
// A layout whose UCS is the World UCS again holds none, as `set_current` leaves it.
if l.ucs.as_ref().is_some_and(|u| u.name.is_empty() && UcsFrame::of(u).is_some_and(|f| f.is_world())) {
l.ucs = None;
}
l.ucs_previous.iter_mut().for_each(unname);
}
Ok(gone.len())
}
/// How the current UCS is named in messages.
fn shown_name(s: &Session) -> String {
let (u, name) = s.ucs_named();
if !name.is_empty() {
name
} else if u.is_world() {
"*WORLD*".into()
} else {
"*NO NAME*".into()
}
}
/// `?`: the named UCSs matching `patterns`, their origins and axes relative to the current UCS.
fn list(s: &Session, patterns: &str) -> String {
let Ok(d) = s.doc() else { return String::new() };
let cur = s.input_ucs();
let (lu, lp) = (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4));
let f = |v: f64| crate::units::format_distance(v, lu, lp);
let pt = |v: Vec3| format!("<{},{},{}>", f(v.x), f(v.y), f(v.z));
let axis = |o: Vec3, a: Vec3| cur.to_ucs3(o + a) - cur.to_ucs3(o);
let mut out = format!("Current ucs name: {}\nSaved coordinate systems:", shown_name(s));
let mut any = false;
for u in d.ucss.iter().filter(|u| matches(patterns, &u.name)) {
any = true;
let Some(fr) = UcsFrame::of(u) else { continue };
out.push_str(&format!(
"\n\n{}\n Origin = {}, X Axis = {}\n Y Axis = {}, Z Axis = {}",
u.name,
pt(cur.to_ucs3(fr.origin)),
pt(axis(fr.origin, fr.x)),
pt(axis(fr.origin, fr.y)),
pt(axis(fr.origin, fr.z()))
));
}
if !any {
out.push_str("\n\n(none)");
}
out
}
/// Where the interactive UCS is.
#[derive(Clone, Debug, Default, PartialEq)]
enum Stage {
#[default]
Main,
/// Tools > New UCS > Origin: only the origin.
OriginOnly,
/// Tools > New UCS > 3 Point: the origin first, then the axes.
ThreePoint,
XPoint(Vec3),
XyPoint(Vec3, Vec3),
Named,
Restore,
Save,
Replace(String),
Delete,
List,
Object,
ZAngle,
}
#[derive(Default)]
struct UcsM {
stage: Stage,
}
impl UcsM {
fn starting(stage: Stage) -> Self {
UcsM { stage }
}
}
fn other(msg: impl Into<String>) -> EngineError {
EngineError::Other(msg.into())
}
impl Interactive for UcsM {
fn name(&self) -> &'static str {
"UCS"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
s.echo(format!("Current ucs name: {}", shown_name(s)));
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
match &self.stage {
Stage::Main => Prompt::new("Specify origin of UCS", Accept::POINT).kw(OPTIONS).default("World"),
Stage::OriginOnly | Stage::ThreePoint => {
// The origin as input is read: in the UCS where that is the current one (so 0,0,0),
// in the world while the current UCS is tilted out of the XY plane.
let o = s.ucs().origin;
let (p, z) = if s.ucs().is_planar() { (s.input_ucs().to_ucs(o.xy()), 0.0) } else { (o.xy(), o.z) };
Prompt::new("Specify new origin point", Accept::POINT).default(format!("{},{},{}", num_text(p.x), num_text(p.y), num_text(z)))
}
Stage::XPoint(o) => Prompt::new("Specify point on X-axis", Accept::POINT).default("Accept").base(o.xy()),
Stage::XyPoint(o, _) => Prompt::new("Specify point on the XY plane", Accept::POINT).default("Accept").base(o.xy()),
Stage::Named => Prompt::new("Enter an option", Accept::TEXT).kw(&["Restore", "Save", "Delete", "?"]),
Stage::Restore => Prompt::new("Enter name of UCS to restore", Accept::TEXT).kw(&["?"]),
Stage::Save => Prompt::new("Enter name to save current UCS", Accept::TEXT).kw(&["?"]),
Stage::Replace(n) => Prompt::new(format!("UCS \"{n}\" already exists. Replace it?"), Accept::TEXT).kw(&["Yes", "No"]).default("No"),
Stage::Delete => Prompt::new("Enter UCS name(s) to delete", Accept::TEXT).default("none"),
Stage::List => Prompt::new("Enter UCS name(s) to list", Accept::TEXT).default("*"),
Stage::Object => Prompt::new("Select object to align UCS", Accept::POINT),
Stage::ZAngle => Prompt::new("Specify rotation angle about Z axis", Accept::NUMBER).default(format!("{}", axis_angle(s))),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if i == Input::Cancel {
return Ok(Step::Cancel);
}
match (self.stage.clone(), i) {
(Stage::Main, Input::Enter) => {
s.set_ucs(UcsFrame::WORLD, "")?;
Ok(Step::Done)
}
(Stage::Main, Input::Keyword(k)) => match k.as_str() {
"World" => {
s.set_ucs(UcsFrame::WORLD, "")?;
Ok(Step::Done)
}
"Previous" => {
if !s.ucs_previous()? {
s.echo("There is no previous UCS.");
}
Ok(Step::Done)
}
"View" => {
let f = view_ucs(s);
s.set_ucs(f, "")?;
Ok(Step::Done)
}
"NAmed" => {
self.stage = Stage::Named;
Ok(Step::Continue)
}
"OBject" => {
self.stage = Stage::Object;
Ok(Step::Continue)
}
"Z" => {
self.stage = Stage::ZAngle;
Ok(Step::Continue)
}
"X" | "Y" | "ZAxis" | "Face" => {
s.echo(tilted_message(&k.to_ascii_lowercase()));
Ok(Step::Continue)
}
_ => Ok(Step::Continue),
},
(Stage::Main | Stage::ThreePoint, Input::Point(p)) => {
self.stage = Stage::XPoint(on_plane(s, p));
Ok(Step::Continue)
}
(Stage::OriginOnly, Input::Point(p)) => {
let f = s.ucs().with_origin(on_plane(s, p));
s.set_ucs(f, "")?;
Ok(Step::Done)
}
(Stage::OriginOnly, Input::Enter) => Ok(Step::Done),
// Enter keeps the origin and goes on to the axes, as a typed point would.
(Stage::ThreePoint, Input::Enter) => {
self.stage = Stage::XPoint(s.ucs().origin);
Ok(Step::Continue)
}
(Stage::XPoint(o), Input::Enter) => {
set_by_points(s, o, None, None)?;
Ok(Step::Done)
}
(Stage::XPoint(o), Input::Point(p)) => {
let x = on_plane(s, p);
if x.xy().dist(o.xy()) <= 1e-12 {
return Err(other("The point on the X axis must differ from the origin."));
}
self.stage = Stage::XyPoint(o, x);
Ok(Step::Continue)
}
(Stage::XyPoint(o, x), Input::Enter) => {
set_by_points(s, o, Some(x), None)?;
Ok(Step::Done)
}
(Stage::XyPoint(o, x), Input::Point(p)) => {
set_by_points(s, o, Some(x), Some(on_plane(s, p)))?;
Ok(Step::Done)
}
(Stage::Named, Input::Keyword(k)) => {
self.stage = match k.as_str() {
"Restore" => Stage::Restore,
"Save" => Stage::Save,
"Delete" => Stage::Delete,
_ => Stage::List,
};
Ok(Step::Continue)
}
(Stage::Named, Input::Enter) => Ok(Step::Done),
(Stage::Restore | Stage::Save, Input::Keyword(_)) => {
let l = list(s, "*");
s.echo(l);
Ok(Step::Continue)
}
(Stage::Restore, Input::Text(t)) => {
restore(s, &t).map_err(other)?;
Ok(Step::Done)
}
(Stage::Save, Input::Text(t)) => {
let n = check_name(&t).map_err(other)?;
if s.doc().is_ok_and(|d| exists(d, &n)) {
self.stage = Stage::Replace(n);
return Ok(Step::Continue);
}
save(s, &n, false).map_err(other)?;
Ok(Step::Done)
}
(Stage::Replace(n), Input::Keyword(k)) => {
if k == "Yes" {
save(s, &n, true).map_err(other)?;
}
Ok(Step::Done)
}
(Stage::Replace(_), Input::Enter) | (Stage::Restore | Stage::Save | Stage::Delete, Input::Enter) => Ok(Step::Done),
(Stage::Delete, Input::Text(t)) => {
let n = delete(s, &t)?;
s.echo(format!("{n} UCS name(s) deleted."));
Ok(Step::Done)
}
(Stage::List, Input::Enter) => {
let l = list(s, "*");
s.echo(l);
Ok(Step::Done)
}
(Stage::List, Input::Text(t)) => {
let l = list(s, &t);
s.echo(l);
Ok(Step::Done)
}
(Stage::Object, Input::Point(p)) => {
let h = super::curves::pick_at(s, p).ok_or_else(|| other("No object found there; select an object."))?;
set_by_object(s, h, Some(p))?;
Ok(Step::Done)
}
(Stage::Object, Input::Enter) => Ok(Step::Done),
(Stage::ZAngle, Input::Enter) => {
let a = axis_angle(s).to_radians();
rotate_z(s, a)?;
Ok(Step::Done)
}
(Stage::ZAngle, Input::Text(t)) => {
let a = s.angle_settings().amount(&t).filter(|a| a.is_finite()).ok_or_else(|| other("Requires a valid angle."))?;
rotate_z(s, a)?;
Ok(Step::Done)
}
(Stage::Main, Input::Text(_)) => Err(other("Requires a point or an option keyword.")),
_ => Err(other("Invalid input.")),
}
}
}
fn set_ucsicon(s: &mut Session, on: Option<bool>, origin: Option<bool>) -> Result<Value> {
let before = s.ucsicon_bits();
let mut bits = before;
if let Some(on) = on {
bits = if on { bits | 1 } else { bits & !1 };
}
if let Some(o) = origin {
bits = if o { bits | 2 } else { bits & !2 };
}
// Asking (or setting what is already set) leaves the drawing unmodified.
if bits != before {
s.doc_mut()?.header.set_i64("UCSICON", bits);
}
Ok(json!({ "on": bits & 1 != 0, "origin": bits & 2 != 0 }))
}
fn run_ucsicon(s: &mut Session, p: &Value) -> Result<Value> {
let flag = |k: &str| -> Result<Option<bool>> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(v) => Err(bad("ucsicon", format!("`{k}` must be true or false, got {v}"))),
}
};
let (on, origin) = (flag("on")?, flag("origin")?);
set_ucsicon(s, on, origin)
}
struct UcsIconM;
impl Interactive for UcsIconM {
fn name(&self) -> &'static str {
"UCSICON"
}
fn prompt(&self, s: &Session) -> Prompt {
let on = s.ucsicon_bits() & 1 != 0;
Prompt::new("Enter an option", Accept::TEXT).kw(&["ON", "OFF", "All", "Noorigin", "ORigin", "Selectable", "Properties"]).default(if on {
"ON"
} else {
"OFF"
})
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => {
match k.as_str() {
"ON" => set_ucsicon(s, Some(true), None).map(|_| ())?,
"OFF" => set_ucsicon(s, Some(false), None).map(|_| ())?,
"Noorigin" => set_ucsicon(s, None, Some(false)).map(|_| ())?,
"ORigin" => set_ucsicon(s, None, Some(true)).map(|_| ())?,
other => {
s.echo(format!("UCSICON {other} is not available yet."));
return Ok(Step::Continue);
}
}
Ok(Step::Done)
}
Input::Enter | Input::Cancel => Ok(Step::Done),
_ => Err(other("Requires an option keyword.")),
}
}
}
-1
View File
@@ -55,7 +55,6 @@ pub fn specs() -> Vec<CommandSpec> {
// ---------------- CAL ----------------
mod calc;
pub(super) use calc::num_text;
/// What QuickCalc's "get from the drawing" picks put on the command line before the value (the
/// palette reads it back from there).
+1 -1
View File
@@ -138,7 +138,7 @@ fn save(s: &mut Session, name: &str, window: Option<Bounds2>, snapshot: bool) ->
let layer_state = snapshot.then(|| {
let state = snapshot_name(name);
d.layer_states.retain(|l| !l.name.eq_ignore_ascii_case(&state));
d.layer_states.push(LayerState { name: state.clone(), layers: d.layers.clone() });
d.layer_states.push(LayerState::new(state.clone(), d.layers.clone(), ""));
state
});
if let Some(old) = &replaced {
-3
View File
@@ -41,8 +41,6 @@ pub struct DocState {
/// The Block Editor (BEDIT), when it is open: `doc` is then the editor's drawing, and the
/// drawing itself waits in it ([`DocState::drawing`]).
pub block_edit: Option<blockedit::BlockEdit>,
/// The user was told that the current UCS is tilted ([`Session::note_tilted_ucs`]).
pub ucs_tilted_noted: bool,
/// What the last erase removed, for OOPS.
pub(crate) erased: crate::cmd::Erased,
/// The fonts missing on Windows that a save last named: the next save names them again only
@@ -74,7 +72,6 @@ impl DocState {
uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
binary_dxf: false,
block_edit: None,
ucs_tilted_noted: false,
erased: Default::default(),
fonts_noted: String::new(),
}
-3
View File
@@ -36,7 +36,6 @@ pub mod settings_dir;
pub mod snap;
pub mod spatial;
pub mod sysvars;
pub mod ucs;
pub mod undoctl;
pub mod units;
@@ -240,8 +239,6 @@ impl Session {
settings.snapunit = d.header.snap_unit();
settings.gridunit = d.header.grid_unit();
}
let a = self.input_ucs().rotation();
settings.ucs_angle = if a.is_finite() { a } else { 0.0 };
settings
}
/// The space commands act on (model space while working inside a layout viewport).
+3 -10
View File
@@ -558,7 +558,7 @@ impl Session {
/// A routine waits for the user's answer to a `get…` function: its prompt.
pub(crate) fn lisp_prompt(&self) -> Option<Prompt> {
match self.lisp.run.as_ref()?.waiting.as_ref()? {
Need::Get(req) => Some(req.prompt(&self.input_ucs())),
Need::Get(req) => Some(req.prompt()),
_ => None,
}
}
@@ -569,15 +569,10 @@ impl Session {
let Need::Get(req) = self.lisp.run.as_ref()?.waiting.as_ref()? else { return None };
let line =
|a: cadcraft_geom::Vec2, b: cadcraft_geom::Vec2| cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: a.to3(0.0), b: b.to3(0.0) });
// The base is a UCS point (as the routine gave it); the preview is drawn in world space.
let ucs = self.input_ucs();
let Some(bu) = req.first.or(req.base).map(|p| cadcraft_geom::Vec2::new(p[0], p[1])) else { return Some(Vec::new()) };
let b = ucs.to_wcs(bu);
let Some(b) = req.first.or(req.base).map(|p| cadcraft_geom::Vec2::new(p[0], p[1])) else { return Some(Vec::new()) };
Some(match req.kind {
input::GetKind::Corner => {
// The rectangle runs along the UCS axes, as the corner it returns is measured.
let cu = ucs.to_ucs(cursor);
let (c1, c2) = (ucs.to_wcs(cadcraft_geom::Vec2::new(cu.x, bu.y)), ucs.to_wcs(cadcraft_geom::Vec2::new(bu.x, cu.y)));
let (c1, c2) = (cadcraft_geom::Vec2::new(cursor.x, b.y), cadcraft_geom::Vec2::new(b.x, cursor.y));
vec![line(b, c1), line(c1, cursor), line(cursor, c2), line(c2, b)]
}
input::GetKind::Point | input::GetKind::Dist | input::GetKind::Angle { .. } => vec![line(b, cursor)],
@@ -756,8 +751,6 @@ fn file_key(name: &str) -> String {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod ucs_tests;
#[cfg(test)]
mod block_tests;
+8 -74
View File
@@ -117,14 +117,10 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))),
Value::Cons(_) => {
if let Some(p) = arg.as_point() {
// A routine's points are in the current UCS, as typed ones are.
let w = ctx.s.input_ucs().to_wcs(Vec2::new(p[0], p[1]));
feed(ctx.s, Input::Point(w));
feed(ctx.s, Input::Point(Vec2::new(p[0], p[1])));
} else if let Value::Ename(h) = arg.car() {
// An `entsel` result: (ename point).
// The pick point is what `entsel` gave: a UCS point, like the ones above.
let frame = ctx.s.input_ucs();
named(ctx.s, h, arg.cdr().car().as_point().map(|p| frame.to_wcs(Vec2::new(p[0], p[1]))));
named(ctx.s, h, arg.cdr().car().as_point().map(|p| Vec2::new(p[0], p[1])));
} else {
return Err(LispError::bad_arg("command argument", arg));
}
@@ -718,13 +714,10 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
}
_ => (rest, None),
};
// The points are UCS points, as `getpoint` and `getcorner` give them: the selection runs in
// the world.
let frame = ctx.s.input_ucs();
let point = |i: usize| -> Result<Vec2, LispError> {
let v = pts.get(i).ok_or_else(|| args_err(true))?;
let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", v))?;
Ok(frame.to_wcs(Vec2::new(p[0], p[1])))
Ok(Vec2::new(p[0], p[1]))
};
let s = &mut *ctx.s;
let all = |s: &Session, all_spaces: bool| -> Vec<Handle> {
@@ -752,8 +745,6 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Some("P") => ctx.s.state().map(|st| st.drawn_in_viewport(&st.previous_selection)).unwrap_or_default(),
Some("I") => ctx.s.selection(),
Some("W") | Some("C") => {
// A selection window is the box around its corners in the world, like SELECT's: the
// same corners typed at either pick the same objects.
let (p1, p2) = (point(0)?, point(1)?);
let s = &*ctx.s;
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
@@ -762,7 +753,7 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
}
Some("F") | Some("WP") | Some("CP") => {
let poly: Vec<Vec2> =
pts.first().map(|l| l.iter().filter_map(|p| p.as_point().map(|q| frame.to_wcs(Vec2::new(q[0], q[1])))).collect()).unwrap_or_default();
pts.first().map(|l| l.iter().filter_map(|p| p.as_point().map(|q| Vec2::new(q[0], q[1]))).collect()).unwrap_or_default();
let s = &*ctx.s;
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
match mode.as_deref() {
@@ -1212,8 +1203,7 @@ pub fn distof(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
pub fn angtof(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 2)?;
let s = string(&a[0])?;
// A pure string-to-angle conversion: ANGBASE and ANGDIR apply, the UCS does not.
let mut settings = ctx.s.angle_settings().world();
let mut settings = ctx.s.angle_settings();
// AUNITS 0..=4; any other units argument is an error in AutoCAD, nil here.
match a.get(1) {
None | Some(Value::Nil) => {}
@@ -1223,67 +1213,11 @@ pub fn angtof(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Ok(Flow::Value(settings.direction(&s).map(Value::Real).unwrap_or_default()))
}
/// A coordinate system `trans` converts from or to: its origin and axes in world coordinates.
fn trans_system(ctx: &Ctx<'_>, v: &Value) -> Result<crate::ucs::UcsFrame, LispError> {
use crate::ucs::UcsFrame;
match v {
// 0 the WCS; 3 paper space's display system, which lines up with paper space's WCS.
Value::Int(0 | 3) => Ok(UcsFrame::WORLD),
// 2 the display system: in a plan view, the WCS turned back by the view's twist (X runs
// right across the screen).
Value::Int(2) => {
let twist = cadcraft_geom::norm_angle(ctx.s.state().map_or(0.0, |st| st.view().twist));
Ok(UcsFrame::WORLD.rotated_z(-twist))
}
Value::Int(1) => Ok(ctx.s.input_ucs()),
// An object: its OCS.
Value::Ename(h) => {
let d = ctx.s.doc().map_err(|e| LispError::new(e.to_string()))?;
let e = d.entity(*h).ok_or_else(|| LispError::bad_arg("lentityp", v))?;
ocs(e.common.extrusion).ok_or_else(|| LispError::bad_arg("lentityp", v))
}
// An extrusion direction: the OCS of objects with it.
Value::Cons(_) => {
let n = v.as_point().ok_or_else(|| LispError::bad_arg("coordinate system", v))?;
ocs(cadcraft_geom::Vec3::new(n[0], n[1], n[2])).ok_or_else(|| LispError::bad_arg("coordinate system", v))
}
other => Err(LispError::bad_arg("coordinate system", other)),
}
}
/// The object coordinate system of extrusion direction `n` (the arbitrary axis algorithm of the
/// DXF Reference): `None` for a direction with no length.
fn ocs(n: cadcraft_geom::Vec3) -> Option<crate::ucs::UcsFrame> {
use cadcraft_geom::Vec3;
let l = n.len();
if !(l > 1e-12 && l.is_finite()) {
return None;
}
let n = n * (1.0 / l);
let w = if n.x.abs() < 1.0 / 64.0 && n.y.abs() < 1.0 / 64.0 { Vec3::new(0.0, 1.0, 0.0) } else { Vec3::Z };
let ax = w.cross(n);
crate::ucs::UcsFrame::new(Vec3::ZERO, ax, n.cross(ax))
}
/// `(trans pt from to [disp])`: `pt` from coordinate system `from` to `to` (0 WCS, 1 UCS, 2 and 3
/// display, an entity name for its OCS, or an extrusion direction); with `disp` non-nil `pt` is a
/// displacement, which the systems' origins don't move.
pub fn trans(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
/// `(trans pt from to [disp])`: points are in the world system throughout (no UCS yet).
pub fn trans(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 3, 4)?;
let p = a[0].as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &a[0]))?;
let (from, to) = (trans_system(ctx, &a[1])?, trans_system(ctx, &a[2])?);
let disp = a.get(3).is_some_and(|v| !v.is_nil());
let p = cadcraft_geom::Vec3::new(p[0], p[1], p[2]);
let q = if disp {
let w = from.x * p.x + from.y * p.y + from.z() * p.z;
cadcraft_geom::Vec3::new(w.dot(to.x), w.dot(to.y), w.dot(to.z()))
} else {
to.to_ucs3(from.to_wcs3(p))
};
if !q.is_finite() {
return Err(LispError::bad_arg("2D/3D point", &a[0]));
}
Ok(Flow::Value(Value::point(&[q.x, q.y, q.z])))
Ok(Flow::Value(Value::point(&p)))
}
/// What `(load name)` reads: a file loaded through APPLOAD (the web), or one on disk, with
+7 -20
View File
@@ -49,8 +49,8 @@ pub struct GetRequest {
}
impl GetRequest {
/// The prompt the command line shows (`ucs`: the UCS the routine's points are in).
pub fn prompt(&self, ucs: &crate::ucs::UcsFrame) -> Prompt {
/// The prompt the command line shows.
pub fn prompt(&self) -> Prompt {
let any = self.initget.bits & 128 != 0 || !self.initget.keywords.is_empty();
let accept = match self.kind {
GetKind::Point | GetKind::Corner | GetKind::EntSel => Accept { text: any, ..Accept::POINT },
@@ -63,7 +63,7 @@ impl GetRequest {
(None, true) => default_message(self.kind).to_string(),
(None, false) => self.message.clone(),
};
let base = self.first.or(self.base).map(|p| ucs.to_wcs(Vec2::new(p[0], p[1])));
let base = self.first.or(self.base).map(|p| Vec2::new(p[0], p[1]));
let mut p = Prompt::new(message, accept).base_opt(base);
p.keywords = self.initget.keywords.clone();
p.raw = true;
@@ -106,21 +106,11 @@ impl GetRequest {
Ok(Value::Nil)
}
Input::Keyword(k) => Ok(Value::str(&k)),
// Points come back in the current UCS, on its XY plane.
Input::Point(p) => {
let u = s.ucs_point(p);
self.point(s, [u.x, u.y, 0.0])
}
Input::Point(p) => self.point(s, [p.x, p.y, 0.0]),
// A deferred tangent/perpendicular snap is the point it was picked at here.
Input::Deferred(d) => {
let u = s.ucs_point(d.at);
self.point(s, [u.x, u.y, 0.0])
}
Input::Deferred(d) => self.point(s, [d.at.x, d.at.y, 0.0]),
Input::Pick(hs) => match (self.kind, hs.first()) {
(GetKind::EntSel, Some(h)) => {
let u = s.ucs_point(s.last_point);
Ok(Value::list(vec![Value::Ename(*h), Value::point(&[u.x, u.y, 0.0])]))
}
(GetKind::EntSel, Some(h)) => Ok(Value::list(vec![Value::Ename(*h), Value::point(&[s.last_point.x, s.last_point.y, 0.0])])),
_ => Err("Invalid point.".into()),
},
Input::Text(t) => self.text(s, &t),
@@ -151,8 +141,7 @@ impl GetRequest {
let ap = s.settings.pickbox.max(1.0) * s.pixel_size();
let space = s.state().map(|st| st.edit_space()).map_err(|e| Again::Msg(e.to_string()))?;
let d = s.doc().map_err(|e| Again::Msg(e.to_string()))?;
// `p` is in the UCS; objects are picked at the world point.
match crate::select::pick_in(d, &space, s.viewport_frozen(), s.input_ucs().to_wcs(Vec2::new(p[0], p[1])), ap) {
match crate::select::pick_in(d, &space, s.viewport_frozen(), Vec2::new(p[0], p[1]), ap) {
Some(h) => Ok(Value::list(vec![Value::Ename(h), Value::point(&p)])),
None => Err("Missed, try again.".into()),
}
@@ -198,8 +187,6 @@ impl GetRequest {
},
GetKind::Angle { orient } => match s.angle_settings().direction(t) {
Some(a) => {
// Measured in the UCS, as an angle from two points is.
let a = a - s.angle_settings().ucs;
let a = if orient { a } else { a - s.lisp_angbase() };
self.check_number(a.rem_euclid(std::f64::consts::TAU), false)
}
-284
View File
@@ -1,284 +0,0 @@
//! AutoLISP in a UCS (#1106): `getpoint` and friends answer in the current UCS, `command` takes
//! UCS points, `trans` converts between the WCS, the UCS, display coordinates and an object's
//! OCS, and entity lists stay in world coordinates.
#![allow(clippy::unwrap_used)]
use cadcraft_geom::Vec2;
use serde_json::json;
use super::value::to_text;
use crate::Session;
use crate::cmd::file::{EntityCodec, set_entity_codec};
fn session() -> Session {
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
let mut s = Session::new();
s.new_drawing(false);
s
}
fn ok(s: &mut Session, code: &str) -> String {
match s.lisp_eval(code, false, true, Vec::new()) {
Ok(Some(Ok(v))) => to_text(&v, true),
other => panic!("{code}: {other:?}"),
}
}
fn err(s: &mut Session, code: &str) -> bool {
matches!(s.lisp_eval(code, false, true, Vec::new()), Ok(Some(Err(_))) | Err(_))
}
/// The three numbers of a printed point.
fn pt(text: &str) -> [f64; 3] {
let v: Vec<f64> = text.trim_matches(['(', ')']).split_whitespace().map(|x| x.parse().unwrap()).collect();
[v[0], v[1], v.get(2).copied().unwrap_or(0.0)]
}
fn close(a: [f64; 3], b: [f64; 3]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
}
/// The UCS at (100, 50) turned 90° (UCS X is world +Y).
fn turned(s: &mut Session) {
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap();
}
#[test]
fn trans_between_world_ucs_and_display() {
let mut s = session();
turned(&mut s);
// UCS (10, 0) is world (100, 60).
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 0)")), [100.0, 60.0, 0.0]));
assert!(close(pt(&ok(&mut s, "(trans '(100 60 0) 0 1)")), [10.0, 0.0, 0.0]));
// A 2D point is at Z 0.
assert!(close(pt(&ok(&mut s, "(trans '(10 0) 1 0)")), [100.0, 60.0, 0.0]));
// Displacements turn but don't move.
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 0 T)")), [0.0, 10.0, 0.0]));
// The display system lines up with the world one in a plan view.
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 2)")), [100.0, 60.0, 0.0]));
assert!(close(pt(&ok(&mut s, "(trans '(3 4 5) 2 0)")), [3.0, 4.0, 5.0]));
// UCS → UCS and back is the identity.
assert!(close(pt(&ok(&mut s, "(trans (trans '(7 -3 2) 1 0) 0 1)")), [7.0, -3.0, 2.0]));
// In a view twisted 90° counterclockwise, world +X points up the screen and world -Y runs
// right across it: display X.
s.execute("dview", &json!({"twist": 90.0})).unwrap();
assert!(close(pt(&ok(&mut s, "(trans '(0 -10 0) 0 2)")), [10.0, 0.0, 0.0]));
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 2 0)")), [0.0, -10.0, 0.0]));
}
#[test]
fn trans_to_and_from_an_objects_ocs() {
let mut s = session();
// A circle in the world XY plane: its OCS is the WCS.
ok(&mut s, "(command \"_.CIRCLE\" '(5 5) 2)");
assert!(close(pt(&ok(&mut s, "(trans '(5 5 0) 0 (entlast))")), [5.0, 5.0, 0.0]));
// An extrusion direction straight up is the WCS too; one along +X follows the arbitrary
// axis algorithm (OCS X = world Y × N = (0, 0, -1)... the DXF Reference's rule).
assert!(close(pt(&ok(&mut s, "(trans '(1 2 3) '(0 0 1) 0)")), [1.0, 2.0, 3.0]));
let w = pt(&ok(&mut s, "(trans '(1 0 0) '(1 0 0) 0)"));
assert!(close(w, [0.0, 1.0, 0.0]), "{w:?}");
let back = pt(&ok(&mut s, "(trans (trans '(1 2 3) '(1 0 0) 0) 0 '(1 0 0))"));
assert!(close(back, [1.0, 2.0, 3.0]), "{back:?}");
// Bad systems and points are errors, not crashes.
for bad in [
"(trans '(1 2) 7 0)",
"(trans '(1 2) \"x\" 0)",
"(trans '(1 2) '(0 0 0) 0)",
"(trans \"p\" 0 1)",
"(trans '(1 2) 0)",
"(trans '(1e308 1e308) '(1e-320 0 0) 0)",
] {
assert!(err(&mut s, bad), "{bad}");
}
}
#[test]
fn getpoint_answers_in_the_ucs_and_command_reads_ucs_points() {
let mut s = session();
turned(&mut s);
s.cmdline("(setq p (getpoint))").unwrap();
// The user clicks world (100, 60): the routine gets UCS (10, 0).
s.input(crate::Input::Point(Vec2::new(100.0, 60.0))).unwrap();
assert!(close(pt(&to_text(&s.lisp_var("P"), true)), [10.0, 0.0, 0.0]), "{}", to_text(&s.lisp_var("P"), true));
// Typed at getpoint: read in the UCS, given back in it.
s.cmdline("(setq q (getpoint))").unwrap();
s.cmdline("3,4").unwrap();
assert!(close(pt(&to_text(&s.lisp_var("Q"), true)), [3.0, 4.0, 0.0]));
// `command` takes those points as UCS points: the line lands at the world places clicked.
ok(&mut s, "(command \"_.LINE\" p q \"\")");
let d = s.doc().unwrap();
let l = d.model.iter().find_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
assert!(l.a.xy().dist(Vec2::new(100.0, 60.0)) < 1e-9 && l.b.xy().dist(Vec2::new(96.0, 53.0)) < 1e-9, "{l:?}");
// Entity lists stay in world coordinates.
let g = ok(&mut s, "(cdr (assoc 10 (entget (entlast))))");
assert!(close(pt(&g), [100.0, 60.0, 0.0]), "{g}");
// `!expr` at the command line is a UCS point too.
s.cmdline("line").unwrap();
s.cmdline("!p").unwrap();
s.cmdline("!q").unwrap();
s.cmdline("").unwrap();
let n = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Line(_))).count();
assert_eq!(n, 2);
let d = s.doc().unwrap();
let last = d.model.iter().filter_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).last().unwrap();
assert!(last.a.xy().dist(Vec2::new(100.0, 60.0)) < 1e-9 && last.b.xy().dist(Vec2::new(96.0, 53.0)) < 1e-9, "{last:?}");
}
/// The rubber band of `getpoint`/`getcorner` with a base point starts where that UCS point is in
/// the world, and `getcorner`'s rectangle runs along the UCS axes.
#[test]
fn getpoint_and_getcorner_previews_start_at_the_ucs_base() {
let ends = |k: &cadcraft_doc::EntityKind| match k {
cadcraft_doc::EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
other => panic!("{other:?}"),
};
let near = |a: Vec2, b: Vec2| a.dist(b) < 1e-9;
let mut s = session();
turned(&mut s);
// UCS (0, 0) is world (100, 50); the cursor is at world (90, 70), UCS (20, 10).
let cursor = Vec2::new(90.0, 70.0);
s.cmdline("(setq p (getpoint '(0 0)))").unwrap();
let band = s.lisp_preview(cursor).unwrap();
assert_eq!(band.len(), 1);
let (a, b) = ends(&band[0]);
assert!(near(a, Vec2::new(100.0, 50.0)) && near(b, cursor), "{a:?} {b:?}");
s.input(crate::Input::Point(cursor)).unwrap();
s.cmdline("(setq c (getcorner '(0 0)))").unwrap();
let rect: Vec<(Vec2, Vec2)> = s.lisp_preview(cursor).unwrap().iter().map(ends).collect();
// Along UCS X (world +Y) to UCS (20, 0), the cursor, UCS (0, 10) (world (90, 50)), back.
let want = [(100.0, 50.0), (100.0, 70.0), (90.0, 70.0), (90.0, 50.0)].map(|(x, y)| Vec2::new(x, y));
assert_eq!(rect.len(), 4);
for (i, (a, b)) in rect.iter().enumerate() {
assert!(near(*a, want[i]) && near(*b, want[(i + 1) % 4]), "side {i}: {a:?} {b:?}");
}
s.input(crate::Input::Point(cursor)).unwrap();
assert!(close(pt(&to_text(&s.lisp_var("C"), true)), [20.0, 10.0, 0.0]), "the corner it returns, in the UCS");
}
#[test]
fn getangle_and_getdist_measure_in_the_ucs() {
let mut s = session();
turned(&mut s);
// Two clicks one above the other in the world: along the UCS X axis, angle 0.
s.cmdline("(setq a (getangle))").unwrap();
s.input(crate::Input::Point(Vec2::new(100.0, 50.0))).unwrap();
s.input(crate::Input::Point(Vec2::new(100.0, 70.0))).unwrap();
let a: f64 = to_text(&s.lisp_var("A"), true).parse().unwrap();
assert!(a.abs() < 1e-6 || (a - std::f64::consts::TAU).abs() < 1e-6, "{a}");
// A typed angle is measured in the UCS as well.
s.cmdline("(setq b (getangle))").unwrap();
s.cmdline("45").unwrap();
let b: f64 = to_text(&s.lisp_var("B"), true).parse().unwrap();
assert!((b - std::f64::consts::FRAC_PI_4).abs() < 1e-6, "{b} (printed to 6 places)");
// Distances don't depend on the UCS.
s.cmdline("(setq d (getdist '(0 0)))").unwrap();
s.cmdline("3,4").unwrap();
assert_eq!(to_text(&s.lisp_var("D"), true), "5.0");
// The UCS variables read from LISP.
assert!(close(pt(&ok(&mut s, "(getvar \"UCSORG\")")), [100.0, 50.0, 0.0]));
assert!(close(pt(&ok(&mut s, "(getvar \"UCSXDIR\")")), [0.0, 1.0, 0.0]));
assert_eq!(ok(&mut s, "(getvar \"WORLDUCS\")"), "0");
}
#[test]
fn entsel_and_getcorner_answer_in_the_ucs() {
let mut s = session();
s.execute("line", &json!({"points": [[100, 60], [100, 80]]})).unwrap();
turned(&mut s);
// entsel: the object, and the pick point in the UCS.
s.cmdline("(setq e (entsel))").unwrap();
s.input(crate::Input::Point(Vec2::new(100.0, 70.0))).unwrap();
let v = to_text(&s.lisp_var("E"), true);
assert!(v.contains("<Entity name"), "{v}");
let p = ok(&mut s, "(cadr e)");
assert!(close(pt(&p), [20.0, 0.0, 0.0]), "{p}");
// entsel with the point typed in the UCS picks the object at its world place.
s.cmdline("(setq e2 (entsel))").unwrap();
s.cmdline("15,0").unwrap();
assert!(to_text(&s.lisp_var("E2"), true).contains("<Entity name"), "{}", to_text(&s.lisp_var("E2"), true));
// getcorner: the base point is a UCS point; the answer is in the UCS.
s.cmdline("(setq c (getcorner '(0 0) \"Corner: \"))").unwrap();
s.input(crate::Input::Point(Vec2::new(95.0, 60.0))).unwrap();
assert!(close(pt(&to_text(&s.lisp_var("C"), true)), [10.0, 5.0, 0.0]), "{}", to_text(&s.lisp_var("C"), true));
// A miss asks again rather than answering.
s.cmdline("(setq e3 (entsel))").unwrap();
s.input(crate::Input::Point(Vec2::new(500.0, 500.0))).unwrap();
assert!(s.lisp_running(), "Missed, try again");
s.cancel();
}
fn model_lines(s: &Session) -> Vec<(Vec2, Vec2)> {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None })
.collect()
}
/// The pick point of an `entsel` result handed to `command` is a UCS point, like the others.
#[test]
fn command_with_entsel_converts_the_pick_point_to_world() {
let mut s = session();
turned(&mut s);
// World (100, 50) to (100, 150): UCS (0, 0) to (100, 0).
s.execute("line", &json!({"points": [[100, 50], [100, 150]]})).unwrap();
ok(&mut s, "(setq e (entlast))");
// Break it from UCS (30, 0) to UCS (60, 0), picked the way `entsel` answers: (ename point).
ok(&mut s, "(command \"_.BREAK\" (list e '(30 0)) '(60 0))");
let mut l = model_lines(&s);
l.sort_by(|a, b| a.0.y.total_cmp(&b.0.y));
assert_eq!(l.len(), 2, "{l:?}");
assert!(l[0].0.dist(Vec2::new(100.0, 50.0)) < 1e-9 && l[0].1.dist(Vec2::new(100.0, 80.0)) < 1e-9, "{l:?}");
assert!(l[1].0.dist(Vec2::new(100.0, 110.0)) < 1e-9 && l[1].1.dist(Vec2::new(100.0, 150.0)) < 1e-9, "{l:?}");
}
/// `ssget` windows, fences, polygons and single picks take UCS points, as `getpoint` gives them.
#[test]
fn ssget_window_takes_ucs_points() {
let mut s = session();
s.execute("ucs", &json!({"option": "origin", "origin": [1000, 1000]})).unwrap();
s.execute("circle", &json!({"center": [1005, 1005], "radius": 1})).unwrap();
s.execute("circle", &json!({"center": [5, 5], "radius": 1})).unwrap();
assert_eq!(ok(&mut s, "(sslength (ssget \"W\" '(0 0) '(10 10)))"), "1");
let found = ok(&mut s, "(cdr (assoc 10 (entget (ssname (ssget \"W\" '(0 0) '(10 10)) 0))))");
assert!(close(pt(&found), [1005.0, 1005.0, 0.0]), "{found}");
assert_eq!(ok(&mut s, "(sslength (ssget \"C\" '(-1 -1) '(11 11)))"), "1");
assert_eq!(ok(&mut s, "(sslength (ssget \"WP\" '((0 0) (10 0) (10 10) (0 10))))"), "1");
assert_eq!(ok(&mut s, "(sslength (ssget \"F\" '((0 0) (10 10))))"), "1");
}
/// `angtof` converts text to radians: ANGBASE and ANGDIR apply, the UCS does not.
#[test]
fn angtof_ignores_the_ucs() {
let mut s = session();
turned(&mut s);
assert_eq!(ok(&mut s, "(angtof \"0\")"), "0.0");
assert_eq!(ok(&mut s, "(angtos (angtof \"45\"))"), "\"45\"");
}
/// A selection window is the world box around its corners whatever the UCS: `ssget` and a SELECT
/// window typed with the same corners pick the same objects.
#[test]
fn ssget_window_matches_select_in_a_turned_ucs() {
let mut s = session();
s.execute("ucs", &json!({"option": "z", "angle": 45})).unwrap();
// The window's corners (UCS 0,0 and 10,4) are world (0,0) and (4.2,9.9): its world box.
for c in [[3.0, 8.0], [1.0, 2.0], [0.0, 7.0], [5.0, 3.0], [40.0, 40.0]] {
s.execute("circle", &json!({"center": c, "radius": 0.5})).unwrap();
}
let count = |s: &mut Session, w: &str| ok(s, &format!("(if (setq ss (ssget \"{w}\" '(0 0) '(10 4))) (sslength ss) 0)"));
let (w, c) = (count(&mut s, "W"), count(&mut s, "C"));
for (key, ssget) in [("w", w), ("c", c)] {
s.cancel();
s.cmdline("select").unwrap();
s.cmdline(key).unwrap();
s.cmdline("0,0").unwrap();
s.cmdline("10,4").unwrap();
s.cmdline("").unwrap();
assert_ne!(ssget, "0", "window {key} finds something");
assert_eq!(s.selection().len().to_string(), ssget, "window {key}");
}
}
+5 -12
View File
@@ -61,13 +61,6 @@ impl Axes {
pub fn combine(self, first: Vec2, second: Vec2) -> Vec2 {
Vec2::new(if self.x { first.x } else { second.x }, if self.y { first.y } else { second.y })
}
/// [`Axes::combine`] with the coordinates read in the UCS `ucs`, where the user typed and saw
/// the points: `.X` takes the first point's X along the UCS X axis, not the world's.
pub fn combine_in(self, ucs: &crate::ucs::UcsFrame, first: Vec2, second: Vec2) -> Vec2 {
let r = ucs.to_wcs(self.combine(ucs.to_ucs(first), ucs.to_ucs(second)));
if r.is_finite() { r } else { self.combine(first, second) }
}
}
/// A pending point modifier.
@@ -243,16 +236,16 @@ impl Session {
// A distance at "Next point" of TK: straight across or up from the last tracking point,
// the way the cursor lies from it.
if let Some(Frame::Track { last: Some(l) }) = self.point_mods.last().copied()
&& self.parse_typed_point(t, self.last_point).is_none()
&& crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_none()
&& let Some(d) = crate::units::parse_distance(t)
{
let dir = (crate::snap::ortho_at(l, self.cursor, self.drafting_settings().ucs_angle) - l).normalized();
let dir = (crate::snap::ortho(l, self.cursor) - l).normalized();
let dir = if dir == Vec2::ZERO || !dir.is_finite() { Vec2::X } else { dir };
return Some(self.modifier_point(l + dir * d));
}
if let Some(Frame::Angle { base, dir }) = self.point_mods.last().copied() {
// Typed coordinates are explicit: they win over the override.
if self.parse_typed_point(t, self.last_point).is_some() {
if crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_some() {
self.point_mods.pop();
return None;
}
@@ -335,7 +328,7 @@ impl Session {
}
Frame::Track { last } => {
// Each point after the first goes straight across or up from the last one.
let q = last.map_or(p, |l| crate::snap::ortho_at(l, p, self.drafting_settings().ucs_angle));
let q = last.map_or(p, |l| crate::snap::ortho(l, p));
self.point_mods.push(Frame::Track { last: Some(q) });
self.last_point = q;
return Ok(());
@@ -343,7 +336,7 @@ impl Session {
// The offset point is already measured from the base (`@` reads the last point).
Frame::From { base: Some(_) } => {}
Frame::Mid { first: Some(f) } => p = (f + p) * 0.5,
Frame::Filter { keep, first: Some(f) } => p = keep.combine_in(&self.input_ucs(), f, p),
Frame::Filter { keep, first: Some(f) } => p = keep.combine(f, p),
Frame::Angle { base, dir } => p = base + dir * (p - base).dot(dir),
Frame::Snap { mode: 0 } => {}
Frame::Snap { mode } => {
+12 -34
View File
@@ -31,7 +31,7 @@ impl Accept {
/// [Truecolor/COlorbook] <BYLAYER>:". A prompt asking for something else besides its keywords has
/// it: "Enter block name or [?]:", "Specify insertion base point or [Basepoint/…]:". Read from
/// AutoCAD's command line over measured runs, where no prompt was written both ways.
const NO_OR: [&str; 28] = [
const NO_OR: &[&str] = &[
"Bring to front",
"Calculate rectangle dimensions based on",
"Choose mode for selected object conversion",
@@ -50,6 +50,7 @@ const NO_OR: [&str; 28] = [
"Enter option",
"Enter polyline linetype generation option",
"Enter property to change",
"Enter states to change",
"Enter the type of array",
"Enter type of unused objects to purge",
"Enter viewport arrangement",
@@ -114,10 +115,7 @@ pub fn parse_polar_text(text: &str, angles: &crate::units::AngleSettings) -> Opt
let body = text.trim().strip_prefix('@')?; // relative form only
let (d, a) = body.split_once('<')?;
let dist = d.trim().parse::<f64>().ok()?;
// The direction `@d<a` draws along, as `parse_point_in` reads it (ANGBASE, ANGDIR and the
// UCS applied): a world angle.
let a = a.trim();
let angle = if a.starts_with('<') { angles.direction(&format!("<{a}"))? } else { angles.direction(a)? };
let angle = angles.amount(a.trim())?;
(dist.is_finite() && angle.is_finite()).then_some((dist, angle))
}
@@ -353,9 +351,10 @@ pub struct Drag {
}
/// Parse a typed point: `x,y[,z]`, `@dx,dy`, `@dist<angle`, `dist<angle`, `#x,y` (absolute),
/// `*x,y` and `*@dx,dy`/`@*dx,dy` (world coordinates).
/// `*x,y` and `*@dx,dy`/`@*dx,dy` (world coordinates: the same as the plain forms, as there is no
/// UCS yet).
/// Relative forms use `last`. Polar angles read the default angle settings (degrees from +X,
/// counterclockwise); `parse_point_with` reads a drawing's, `parse_point_in` a UCS too.
/// counterclockwise); `parse_point_with` reads a drawing's.
pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
parse_point_with(text, last, &crate::units::AngleSettings::default())
}
@@ -363,31 +362,14 @@ pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
/// `parse_point` with polar angles read per `angles` (AUNITS, ANGBASE, ANGDIR); `d<<a` and
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS).
pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSettings) -> Option<Vec2> {
parse_point_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
}
/// `parse_point_with` in a UCS: coordinates are UCS coordinates (`x,y` from its origin along its
/// axes, `@dx,dy` along its axes), and polar angles are measured as `angles` says (which carries
/// the UCS rotation, [`crate::units::AngleSettings::ucs`]). A `*` prefix reads the point in
/// world coordinates instead. `last` and the result are world points.
pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec2> {
let t = text.trim();
if t.is_empty() {
return None;
}
let (mut world, t) = match t.strip_prefix('*') {
Some(r) => (true, r.trim_start()),
None => (false, t),
};
let t = t.strip_prefix('*').map_or(t, str::trim_start);
let (rel, body) = if let Some(b) = t.strip_prefix('@') {
let b = b.trim();
match b.strip_prefix('*') {
Some(r) => {
world = true;
(true, r.trim_start())
}
None => (true, b),
}
(true, b.strip_prefix('*').map_or(b, str::trim_start))
} else if let Some(b) = t.strip_prefix('#') {
(false, b.trim())
} else {
@@ -396,15 +378,11 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
if rel && body.is_empty() {
return Some(last);
}
let (frame, angles) = if world { (crate::ucs::UcsFrame::WORLD, angles.world()) } else { (*ucs, *angles) };
// `p`: a world displacement (polar, whose angle already says the UCS's direction), or UCS
// coordinates (`x,y`).
let p = if let Some((d, a)) = body.split_once('<') {
let dist = crate::units::parse_distance(d)?;
// `d<<a` / `d<<<a`: the override prefixes keep their `<<` / `<<<`.
let ang = if a.starts_with('<') { angles.direction(&format!("<{a}"))? } else { angles.direction(a)? };
let v = Vec2::from_angle(ang) * dist;
if rel { last + v } else { frame.origin.xy() + v }
Vec2::from_angle(ang) * dist
} else {
let parts: Vec<&str> = body.split(',').collect();
if parts.len() < 2 || parts.len() > 3 {
@@ -415,10 +393,10 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
if let Some(z) = parts.get(2) {
crate::units::parse_distance(z)?;
}
let v = Vec2::new(x, y);
if rel { last + frame.vec_to_wcs(v) } else { frame.to_wcs(v) }
Vec2::new(x, y)
};
p.is_finite().then_some(p)
let r = if rel { last + p } else { p };
r.is_finite().then_some(r)
}
#[cfg(test)]
+2 -4
View File
@@ -107,8 +107,7 @@ impl Session {
lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false),
lisp::value::Value::Str(s) => self.typed_token(&s, false),
other => match other.as_point() {
// A point from LISP is in the current UCS, as typed coordinates are.
Some(p) => self.input(Input::Point(self.input_ucs().to_wcs(Vec2::new(p[0], p[1])))),
Some(p) => self.input(Input::Point(Vec2::new(p[0], p[1]))),
None => {
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
Ok(())
@@ -147,8 +146,7 @@ impl Session {
return self.input(Input::Keyword(k));
}
if prompt.accept.point {
self.note_tilted_ucs();
if let Some(p) = self.parse_typed_point(tt, self.last_point) {
if let Some(p) = prompt::parse_point_with(tt, self.last_point, &self.angle_settings()) {
self.last_polar = prompt::parse_polar_text(tt, &self.angle_settings());
return self.input(Input::Point(p));
}
+5 -5
View File
@@ -27,6 +27,10 @@ pub struct Settings {
pub measureinit: bool,
/// -VIEW sEttings > Layer snapshot: named views save the layer settings with them.
pub view_layer_snapshot: bool,
/// -LAYER stAte Save: the properties a new layer state restores (its mask), as the last Save
/// left them. AutoCAD 2024 keeps these toggles in the registry from one Save to the next
/// (measured); Edit doesn't change them.
pub layer_state_mask: u32,
pub dynmode: bool,
/// DYNDIGRIP: which dimensions grip dimensional input shows while a grip is stretched (bits:
/// 1 resulting length, 2 length change, 4 absolute angle, 8 angle change, 16 radius); read
@@ -125,10 +129,6 @@ pub struct Settings {
pub polarsnap: bool,
/// POLARDIST: the PolarSnap step; 0 uses the snap X spacing.
pub polardist: f64,
/// The current UCS's X axis, radians from world +X: ortho, polar and object snap tracking
/// work along the UCS axes. Filled in by [`Session::drafting_settings`]; not a setting.
#[serde(skip)]
pub ucs_angle: f64,
/// AUDITCTL: 1 creates an audit report (.adt) file when AUDIT is run (default: 0).
pub auditctl: bool,
/// ATTREQ: 0 inserts blocks with their attributes' default values instead of asking for them
@@ -152,6 +152,7 @@ impl Default for Settings {
zoomfactor: 60,
measureinit: false,
view_layer_snapshot: true,
layer_state_mask: cadcraft_doc::LayerState::ALL,
dynmode: true,
dyndigrip: 31,
dyndivis: 1,
@@ -197,7 +198,6 @@ impl Default for Settings {
polaraddang: Vec::new(),
polarsnap: false,
polardist: 0.0,
ucs_angle: 0.0,
auditctl: false,
attreq: true,
}
+1 -26
View File
@@ -1025,17 +1025,6 @@ pub fn ortho(base: Vec2, p: Vec2) -> Vec2 {
if d.x.abs() >= d.y.abs() { Vec2::new(p.x, base.y) } else { Vec2::new(base.x, p.y) }
}
/// [`ortho`] along axes turned by `angle` radians (the current UCS's).
pub fn ortho_at(base: Vec2, p: Vec2, angle: f64) -> Vec2 {
if !angle.is_finite() || angle == 0.0 {
return ortho(base, p);
}
let d = (p - base).rotate(-angle);
let along = if d.x.abs() >= d.y.abs() { Vec2::new(d.x, 0.0) } else { Vec2::new(0.0, d.y) };
let r = base + along.rotate(angle);
if r.is_finite() { r } else { p }
}
/// Polar tracking: if the direction base→p is within `tol` radians of a multiple of `inc`,
/// return the point projected onto that ray and the angle.
pub fn polar(base: Vec2, p: Vec2, inc: f64, tol: f64) -> Option<(Vec2, f64)> {
@@ -1069,26 +1058,12 @@ pub fn grid_snap(p: Vec2, unit: Vec2, origin: Vec2, angle: f64) -> Vec2 {
if s.is_finite() { s } else { p }
}
/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing,
/// as stored: in the UCS ([`grid_frame_in`] places them in the world).
/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing.
pub fn grid_frame(d: &Drawing) -> (Vec2, f64) {
let base = d.header.point("SNAPBASE").map(|p| p.xy()).filter(|p| p.is_finite()).unwrap_or(Vec2::ZERO);
(base, d.header.f64("SNAPANG", 0.0).to_radians())
}
/// The snap grid's origin and rotation in world coordinates, for `space`: SNAPBASE is a point of
/// the current UCS and SNAPANG is measured from its X axis, so the grid and grid snap lie in the
/// UCS (in the World UCS while it is tilted out of the XY plane).
pub fn grid_frame_in(d: &Drawing, space: &Space) -> (Vec2, f64) {
let (base, angle) = grid_frame(d);
let ucs = crate::ucs::current_frame(d, space);
if !ucs.is_planar() {
return (base, angle);
}
let (o, a) = (ucs.to_wcs(base), ucs.rotation() + angle);
if o.is_finite() && a.is_finite() { (o, a) } else { (base, angle) }
}
#[cfg(test)]
mod tests {
use super::*;
+7 -68
View File
@@ -118,11 +118,11 @@ pub fn lattice_snap(p: Vec2, d: f64, origin: Vec2, angle: f64) -> Vec2 {
/// isometric lattice, and the settings with grid snap off so the rectangular grid leaves it be.
/// Otherwise both unchanged, also when PolarSnap (SNAPTYPE 1) is the snap type: snap mode then
/// steps along the tracking paths instead.
pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, space: &cadcraft_doc::Space, mut s: Settings, p: Vec2) -> (Vec2, Settings) {
pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, mut s: Settings, p: Vec2) -> (Vec2, Settings) {
if !(s.snapmode && s.isodraft) || s.polarsnap {
return (p, s);
}
let (origin, angle) = super::grid_frame_in(doc, space);
let (origin, angle) = super::grid_frame(doc);
s.snapmode = false;
(lattice_snap(p, s.snapunit.y, origin, angle), s)
}
@@ -144,12 +144,10 @@ fn nearest_axis(plane: IsoPlane, d: Vec2) -> Vec2 {
/// Ortho without snapping: `p` constrained relative to `base` to the nearest axis of the current
/// isometric plane (or to horizontal/vertical when isometric drafting is off).
pub fn constrain(s: &Settings, base: Vec2, p: Vec2) -> Vec2 {
// Along the current UCS's axes (`s.ucs_angle`), the isometric ones turned with it.
if !s.isodraft {
return super::ortho_at(base, p, s.ucs_angle);
return super::ortho(base, p);
}
let a = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 };
let dir = nearest_axis(s.isoplane, (p - base).rotate(-a)).rotate(a);
let dir = nearest_axis(s.isoplane, p - base);
let r = base + dir * (p - base).dot(dir);
if r.is_finite() { r } else { p }
}
@@ -216,29 +214,16 @@ pub struct GridLine {
/// major line. Empty when a family would need more than [`MAX_GRID_LINES`] lines.
pub fn grid_lines(view: Bounds2, d: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec<GridLine> {
let Some(d) = spacing(d) else { return Vec::new() };
// Neighbouring lines of a family are d·cos 30° apart.
families(view, &[30.0, 90.0, 150.0], d * COS30, origin, angle, major_every)
}
/// The rectangular grid lines (lines along X and along Y, `d` apart, through `origin`, turned by
/// `angle`) that cross `view`; every `major_every`th line of a family is a major line. Empty when
/// a family would need more than [`MAX_GRID_LINES`] lines.
pub fn rect_grid_lines(view: Bounds2, d: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec<GridLine> {
let Some(d) = spacing(d) else { return Vec::new() };
families(view, &[0.0, 90.0], d, origin, angle, major_every)
}
/// Lines along each of `degs` (turned by `angle`), `gap` apart, one through `origin`, clipped to
/// `view`.
fn families(view: Bounds2, degs: &[f64], gap: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec<GridLine> {
let angle = if angle.is_finite() { angle } else { 0.0 };
if !(view.min.is_finite() && view.max.is_finite() && origin.is_finite()) {
return Vec::new();
}
let corners = [view.min, Vec2::new(view.max.x, view.min.y), view.max, Vec2::new(view.min.x, view.max.y)];
// Neighbouring lines of a family are d·cos 30° apart.
let gap = d * COS30;
let major_every = i64::from(major_every.max(1));
let mut out = Vec::new();
for &deg in degs {
for deg in [30.0f64, 90.0, 150.0] {
let dir = Vec2::from_angle(deg.to_radians() + angle);
let n = dir.perp();
let off = origin.dot(n);
@@ -304,50 +289,4 @@ mod tests {
assert!(grid_lines(v, 1e-9, Vec2::ZERO, 0.0, 5).is_empty());
assert!(grid_lines(v, f64::NAN, Vec2::ZERO, 0.0, 5).is_empty());
}
/// The rectangular grid: lines along X and Y through the snap base, `d` apart, every
/// `major_every`th major, all turned by SNAPANG (in the World UCS too) and clipped to the view.
#[test]
fn rect_grid_lines_lie_in_the_snap_frame() {
let v = Bounds2 { min: Vec2::new(0.0, 0.0), max: Vec2::new(10.0, 10.0) };
let lines = rect_grid_lines(v, 1.0, Vec2::ZERO, 0.0, 5);
// 0..=10 along each axis.
assert_eq!(lines.len(), 22);
let inside = |p: Vec2| p.x >= -1e-9 && p.x <= 10.0 + 1e-9 && p.y >= -1e-9 && p.y <= 10.0 + 1e-9;
assert!(lines.iter().all(|l| inside(l.a) && inside(l.b)));
let vertical_major: Vec<f64> = lines.iter().filter(|l| (l.a.x - l.b.x).abs() < 1e-9 && l.major).map(|l| l.a.x).collect();
assert_eq!(vertical_major.len(), 3, "x = 0, 5 and 10");
assert!(vertical_major.iter().all(|x| (x / 5.0 - (x / 5.0).round()).abs() < 1e-9));
// Turned 30° about a base at (0.5, 0.25): every line runs at 30° or 120°, and one of each
// passes through the base.
let (base, a) = (Vec2::new(0.5, 0.25), 30f64.to_radians());
let turned = rect_grid_lines(v, 1.0, base, a, 5);
assert!(!turned.is_empty());
let (ux, uy) = (Vec2::from_angle(a), Vec2::from_angle(a).perp());
for l in &turned {
let d = (l.b - l.a).normalized();
assert!(d.cross(ux).abs() < 1e-9 || d.cross(uy).abs() < 1e-9, "{l:?}");
// Each line is a whole number of steps from the base across its direction.
let k = (l.a - base).cross(d);
assert!((k - k.round()).abs() < 1e-9, "{l:?}");
}
let through = |dir: Vec2| turned.iter().any(|l| (l.b - l.a).normalized().cross(dir).abs() < 1e-9 && (base - l.a).cross(dir).abs() < 1e-9);
assert!(through(ux) && through(uy));
// Too many lines, or no spacing: nothing drawn.
assert!(rect_grid_lines(v, 1e-6, Vec2::ZERO, 0.0, 5).is_empty());
assert!(rect_grid_lines(v, f64::NAN, Vec2::ZERO, 0.0, 5).is_empty());
assert!(rect_grid_lines(v, 1.0, Vec2::new(f64::INFINITY, 0.0), 0.0, 5).is_empty());
}
/// A view far larger than any grid (a zoom to hostile extents) draws no grid instead of
/// overflowing the line count.
#[test]
fn rect_grid_lines_survive_extreme_views() {
let huge = Bounds2::new(Vec2::new(-1e300, -1e300), Vec2::new(1e300, 1e300));
assert!(rect_grid_lines(huge, 1.0, Vec2::ZERO, 0.0, 5).is_empty());
let far = Bounds2::new(Vec2::new(1e300, 1e300), Vec2::new(1e300 + 1.0, 1e300 + 1.0));
assert!(rect_grid_lines(far, 1.0, Vec2::ZERO, 0.0, 5).len() <= 2 * (MAX_GRID_LINES + 1));
let normal = Bounds2::new(Vec2::new(-5.0, 0.0), Vec2::new(5.0, 10.0));
assert_eq!(rect_grid_lines(normal, 1.0, Vec2::ZERO, 0.0, 5).len(), 22);
}
}
+8 -14
View File
@@ -259,14 +259,12 @@ impl TrackConfig {
/// direction (radians) of the last segment when the base point ends it.
pub fn relative_to(s: &crate::Settings, angbase: f64, last: Option<f64>) -> Self {
let additional: &[f64] = if s.polar_flags & polarmode::ADDITIONAL != 0 { &s.polaraddang } else { &[] };
// Measured in the current UCS: from ANGBASE off its X axis.
let ucs = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 };
let absolute = polar_angles(s.polarang, additional, angbase + ucs);
let absolute = polar_angles(s.polarang, additional, angbase);
let polar = match last.filter(|a| a.is_finite() && s.polar_flags & polarmode::RELATIVE != 0) {
Some(a) => polar_angles(s.polarang, additional, a),
None => absolute.clone(),
};
let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal(ucs) };
let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal() };
TrackConfig {
otrack: s.otrack,
osmode: s.osmode,
@@ -281,9 +279,9 @@ impl TrackConfig {
}
}
/// Along the UCS axes (turned `ucs` radians from the world's), both ways.
fn orthogonal(ucs: f64) -> Vec<f64> {
[0.0, PI / 2.0, PI, 1.5 * PI].iter().map(|a| norm_angle(a + ucs)).collect()
/// Horizontal and vertical, both ways.
fn orthogonal() -> Vec<f64> {
vec![0.0, PI / 2.0, PI, 1.5 * PI]
}
/// Every multiple of the increment `inc` (POLARANG) around the circle, plus the `additional`
@@ -809,11 +807,10 @@ impl crate::Session {
return CursorSnap { point: h.point, snap: Some(h), track: None, wait };
}
// Isometric snap (SNAPSTYL 1): its lattice in place of the rectangular grid.
let snapmode = s.snapmode;
let (raw, mut s) = super::iso::grid_snap(&doc, &space, s, raw);
let (raw, s) = super::iso::grid_snap(&doc, s, raw);
let mut p = raw;
if s.snapmode && !s.polarsnap {
let (origin, angle) = super::grid_frame_in(&doc, &space);
let (origin, angle) = super::grid_frame(&doc);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
}
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
@@ -832,10 +829,7 @@ impl crate::Session {
&& s.orthomode
&& !q.corner
{
// Grid snap as it was before the isometric lattice took it (`grid_snap` turns it off),
// so ortho keeps whole snap steps along the isometric axes.
s.snapmode = snapmode;
p = super::iso::ortho(&s, b, p);
p = super::iso::ortho(&self.settings, b, p);
}
CursorSnap { point: p, snap: None, track: None, wait }
}
-18
View File
@@ -188,19 +188,6 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
json!([v.center.x, v.center.y, 0.0])
}
"VIEWSIZE" => json!(s.state().ok()?.view().height),
// The current UCS of the space commands act on (paper space has its own per layout),
// set by the UCS command.
"UCSNAME" | "UCSORG" | "UCSXDIR" | "UCSYDIR" | "WORLDUCS" => {
let (u, name) = s.ucs_named();
let p = |v: cadcraft_geom::Vec3| json!([v.x, v.y, v.z]);
match n.as_str() {
"UCSNAME" => json!(name),
"UCSORG" => p(u.origin),
"UCSXDIR" => p(u.x),
"UCSYDIR" => p(u.y),
_ => json!(i32::from(u.is_world())),
}
}
// The view twist (DVIEW TWist), in degrees counterclockwise.
"VIEWTWIST" => json!(s.state().ok()?.view().twist.to_degrees()),
"EXTMIN" | "EXTMAX" => {
@@ -285,11 +272,6 @@ const READ_ONLY: &[&str] = &[
"EXTMAX",
"UNDOCTL",
"UNDOMARKS",
"UCSNAME",
"UCSORG",
"UCSXDIR",
"UCSYDIR",
"WORLDUCS",
];
pub fn is_read_only(name: &str) -> bool {
-3
View File
@@ -73,9 +73,6 @@ const HEADER: &[(&str, Kind, Def)] = &[
("TEXTFILL", Kind::Choice(&[0, 1]), Def::Int(1)),
("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
("UCSAXISANG", Kind::Choice(&[5, 10, 15, 18, 22, 30, 45, 90, 180]), Def::Int(90)),
// 1: the UCS icon is shown; 2: at the UCS origin when that is on screen.
("UCSICON", Kind::Int(0, 3), Def::Int(3)),
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
-404
View File
@@ -1,404 +0,0 @@
//! The user coordinate system (UCS): the coordinate system points are typed in, coordinates are
//! shown in and directions are measured in.
//!
//! Model space keeps its current UCS in the drawing header (UCSORG, UCSXDIR, UCSYDIR, UCSNAME,
//! as a DXF file does), each layout its paper-space UCS ([`cadcraft_doc::Layout::ucs`]). The
//! drawing itself stays in world coordinates: a UCS changes how points are read and shown,
//! never the stored geometry, so it costs nothing while drawing or regenerating.
//!
//! CADCraft draws in the world XY plane. A UCS whose XY plane is that plane (any origin, any
//! rotation about Z) is used in full; one tilted out of it is kept and saved as it is, while
//! points are read in the World UCS ([`Session::input_ucs`]).
use cadcraft_doc::{Drawing, HVal, Space, Ucs};
use cadcraft_geom::{Vec2, Vec3};
use crate::{Result, Session};
/// How many earlier UCSs UCS Previous goes back through, in each space.
pub const MAX_PREVIOUS: usize = 10;
/// How close to the World UCS, or to the world XY plane, counts as on it.
const TOL: f64 = 1e-9;
/// A coordinate system: its origin and unit X and Y axes, in world coordinates.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct UcsFrame {
pub origin: Vec3,
pub x: Vec3,
pub y: Vec3,
}
impl Default for UcsFrame {
fn default() -> Self {
Self::WORLD
}
}
impl UcsFrame {
pub const WORLD: UcsFrame = UcsFrame { origin: Vec3::ZERO, x: Vec3::new(1.0, 0.0, 0.0), y: Vec3::new(0.0, 1.0, 0.0) };
/// A frame from an origin and X and Y directions: X is normalised and Y made square to it in
/// their plane. `None` for non-finite values or directions with no length or along each other.
pub fn new(origin: Vec3, x: Vec3, y: Vec3) -> Option<UcsFrame> {
if !(origin.is_finite() && x.is_finite() && y.is_finite()) {
return None;
}
let xl = x.len();
if !(xl > TOL && xl.is_finite()) {
return None;
}
let x = x * (1.0 / xl);
let yo = y.len();
if !(yo > TOL && yo.is_finite()) {
return None;
}
// What is left of Y square to X: next to nothing means the two lie along each other.
let y = y - x * x.dot(y);
let yl = y.len();
if !yl.is_finite() || yl <= 1e-9 * yo {
return None;
}
Some(UcsFrame { origin, x, y: y * (1.0 / yl) })
}
/// A UCS table record's frame (`None`: unusable axes).
pub fn of(u: &Ucs) -> Option<UcsFrame> {
UcsFrame::new(u.origin, u.x_axis, u.y_axis)
}
/// This frame as a UCS table record named `name`.
pub fn record(&self, name: &str) -> Ucs {
Ucs { name: name.to_string(), origin: self.origin, x_axis: self.x, y_axis: self.y }
}
pub fn z(&self) -> Vec3 {
self.x.cross(self.y)
}
/// The World UCS (to within rounding).
pub fn is_world(&self) -> bool {
self.origin.len() <= TOL * (1.0 + self.origin.len()) && self.is_planar() && (self.x - Vec3::new(1.0, 0.0, 0.0)).len() <= TOL
}
/// Its XY plane is the world XY plane with Z up (any origin height, any rotation about Z).
pub fn is_planar(&self) -> bool {
self.x.z.abs() <= TOL && self.y.z.abs() <= TOL && self.z().z > 0.0
}
/// The direction of its X axis in the world XY plane, radians counterclockwise from +X.
pub fn rotation(&self) -> f64 {
self.x.xy().angle()
}
/// A point of the UCS XY plane, in world coordinates (planar frames; a tilted frame's XY
/// plane seen from above).
pub fn to_wcs(&self, p: Vec2) -> Vec2 {
self.origin.xy() + self.vec_to_wcs(p)
}
/// A world point in UCS coordinates (planar frames).
pub fn to_ucs(&self, p: Vec2) -> Vec2 {
self.vec_to_ucs(p - self.origin.xy())
}
/// A displacement in the UCS XY plane, in world coordinates.
pub fn vec_to_wcs(&self, v: Vec2) -> Vec2 {
self.x.xy() * v.x + self.y.xy() * v.y
}
/// A world displacement in UCS coordinates.
pub fn vec_to_ucs(&self, v: Vec2) -> Vec2 {
Vec2::new(v.dot(self.x.xy()), v.dot(self.y.xy()))
}
/// A UCS point in world coordinates, in 3D.
pub fn to_wcs3(&self, p: Vec3) -> Vec3 {
self.origin + self.x * p.x + self.y * p.y + self.z() * p.z
}
/// A world point in UCS coordinates, in 3D.
pub fn to_ucs3(&self, p: Vec3) -> Vec3 {
let d = p - self.origin;
Vec3::new(d.dot(self.x), d.dot(self.y), d.dot(self.z()))
}
/// The same axes at another origin.
pub fn with_origin(&self, origin: Vec3) -> UcsFrame {
UcsFrame { origin, ..*self }
}
/// Turned by `angle` radians about its own Z axis (counterclockwise looking down Z).
pub fn rotated_z(&self, angle: f64) -> UcsFrame {
let (s, c) = angle.sin_cos();
UcsFrame { origin: self.origin, x: self.x * c + self.y * s, y: self.y * c - self.x * s }
}
/// UCS from points (world coordinates): a new origin; with a point on the positive X axis,
/// X points at it; with a point on the positive-Y half of the XY plane too, that fixes Y.
/// Without the third point Y stays square to X and to this frame's Z. `None` when the
/// points don't fix an axis (on top of each other, or all three on a line).
pub fn from_points(&self, origin: Vec3, x_point: Option<Vec3>, xy_point: Option<Vec3>) -> Option<UcsFrame> {
let Some(xp) = x_point else { return origin.is_finite().then(|| self.with_origin(origin)) };
let x = xp - origin;
match xy_point {
Some(yp) => UcsFrame::new(origin, x, yp - origin),
None => {
let xl = x.len();
if !(xl > TOL && xl.is_finite()) {
return None;
}
let y = self.z().cross(x * (1.0 / xl));
UcsFrame::new(origin, x, y)
}
}
}
}
/// The usable current UCS of `space` in `d`, if it has one.
fn frame_of(d: &Drawing, space: &Space) -> Option<UcsFrame> {
match space {
Space::Model => {
let h = &d.header;
match (h.point("UCSORG"), h.point("UCSXDIR"), h.point("UCSYDIR")) {
(Some(o), Some(x), Some(y)) => UcsFrame::new(o, x, y),
(o, None, None) => o.filter(|o| o.is_finite()).map(|o| UcsFrame::WORLD.with_origin(o)),
_ => None,
}
}
Space::Paper(name) => d.layout(name).and_then(|l| l.ucs.as_ref()).and_then(UcsFrame::of),
}
}
/// The current UCS of `space` in `d` without its name, so nothing is allocated: what the
/// per-point and per-angle paths need. A missing or unusable one is the World UCS.
pub fn current_frame(d: &Drawing, space: &Space) -> UcsFrame {
frame_of(d, space).unwrap_or(UcsFrame::WORLD)
}
/// The current UCS of `space` in `d` and its name (empty when it isn't a named UCS). A missing
/// or unusable one is the World UCS.
pub fn current(d: &Drawing, space: &Space) -> (UcsFrame, String) {
let Some(frame) = frame_of(d, space) else { return (UcsFrame::WORLD, String::new()) };
let name = match space {
Space::Model => d.header.str("UCSNAME", "").trim().to_string(),
Space::Paper(name) => d.layout(name).and_then(|l| l.ucs.as_ref()).map(|u| u.name.trim().to_string()).unwrap_or_default(),
};
(frame, name)
}
/// Make `frame` (named `name`, empty for an unnamed one) the current UCS of `space`.
pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str) {
match space {
Space::Model => {
let h = &mut d.header;
h.set("UCSORG", HVal::Point(frame.origin));
h.set("UCSXDIR", HVal::Point(frame.x));
h.set("UCSYDIR", HVal::Point(frame.y));
h.set_str("UCSNAME", name);
}
Space::Paper(layout) => {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)) {
l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name));
}
}
}
}
/// `space`'s UCS Previous history, kept in the drawing (so undo restores it) and, for a layout,
/// with the layout (so it follows a rename and goes with a delete). `None`: no such layout.
fn previous_mut<'a>(d: &'a mut Drawing, space: &Space) -> Option<&'a mut Vec<Ucs>> {
match space {
Space::Model => Some(&mut d.ucs_previous),
Space::Paper(layout) => d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)).map(|l| &mut l.ucs_previous),
}
}
/// The named UCS `name` of the drawing's UCS table, if it has one with usable axes.
pub fn named(d: &Drawing, name: &str) -> Option<(UcsFrame, String)> {
let u = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name.trim()))?;
Some((UcsFrame::of(u)?, u.name.clone()))
}
impl Session {
/// The current UCS of the space commands act on, and its name.
pub fn ucs_named(&self) -> (UcsFrame, String) {
self.doc().map(|d| current(d, &self.space())).unwrap_or_default()
}
/// The current UCS of the space commands act on.
pub fn ucs(&self) -> UcsFrame {
self.doc().map(|d| current_frame(d, &self.space())).unwrap_or_default()
}
/// The UCS points are typed in and shown in: the current one, or the World UCS while the
/// current one is tilted out of the XY plane (CADCraft draws in that plane).
pub fn input_ucs(&self) -> UcsFrame {
let u = self.ucs();
if u.is_planar() { u } else { UcsFrame::WORLD }
}
/// A typed point as the user means it: in the current UCS (`*` for world coordinates), with
/// the drawing's angle settings; relative forms from `last`. A world point.
pub fn parse_typed_point(&self, text: &str, last: Vec2) -> Option<Vec2> {
crate::prompt::parse_point_in(text, last, &self.angle_settings(), &self.input_ucs())
}
/// A world point in the coordinates shown to the user (the current UCS).
pub fn ucs_point(&self, p: Vec2) -> Vec2 {
self.input_ucs().to_ucs(p)
}
/// A world direction (radians from world +X) measured from the current UCS X axis.
pub fn ucs_angle(&self, a: f64) -> f64 {
cadcraft_geom::norm_angle(a - self.input_ucs().rotation())
}
/// Make `frame` the current UCS (named `name`; empty for an unnamed one), remembering the one
/// it replaces for UCS Previous. Part of the running command's undo step.
pub fn set_ucs(&mut self, frame: UcsFrame, name: &str) -> Result<()> {
let space = self.space();
let (old, old_name) = self.ucs_named();
if old == frame && old_name.eq_ignore_ascii_case(name) {
return Ok(());
}
let d = self.doc_mut()?;
set_current(d, &space, &frame, name);
if let Some(h) = previous_mut(d, &space) {
h.push(old.record(&old_name));
// At most MAX_PREVIOUS: drop the oldest.
if h.len() > MAX_PREVIOUS {
h.remove(0);
}
}
Ok(())
}
/// Go back to the UCS before the current one in this space; `false` when there is none.
pub fn ucs_previous(&mut self) -> Result<bool> {
let space = self.space();
// Nothing to go back to: the drawing stays unmodified.
let none = self.doc().map_or(true, |d| match &space {
Space::Model => d.ucs_previous.is_empty(),
Space::Paper(layout) => d.layout(layout).is_none_or(|l| l.ucs_previous.is_empty()),
});
if none {
return Ok(false);
}
let d = self.doc_mut()?;
// An entry with unusable axes (none is ever stored) is skipped, not restored.
while let Some(u) = previous_mut(d, &space).and_then(|h| h.pop()) {
if let Some(frame) = UcsFrame::of(&u) {
set_current(d, &space, &frame, &u.name);
return Ok(true);
}
}
Ok(false)
}
/// UCSICON: 1 the icon is shown, 2 at the UCS origin (when that is on screen).
pub fn ucsicon_bits(&self) -> i64 {
self.doc().map(|d| d.header.i64("UCSICON", 3)).unwrap_or(3).clamp(0, 3)
}
/// Tell the user once per drawing that its current UCS is tilted and points are read in the
/// World UCS for now.
pub(crate) fn note_tilted_ucs(&mut self) {
if self.ucs().is_planar() {
return;
}
let Ok(st) = self.state_mut() else { return };
if std::mem::replace(&mut st.ucs_tilted_noted, true) {
return;
}
self.echo("The current UCS is tilted out of the XY plane; points are read and shown in the World UCS for now.");
}
}
#[cfg(test)]
mod tests {
use super::*;
fn near(a: Vec2, b: Vec2) -> bool {
a.dist(b) < 1e-9
}
#[test]
fn world_is_the_identity() {
let w = UcsFrame::WORLD;
assert!(w.is_world() && w.is_planar());
assert_eq!(w.rotation(), 0.0);
let p = Vec2::new(3.5, -2.25);
assert_eq!(w.to_wcs(p), p);
assert_eq!(w.to_ucs(p), p);
}
#[test]
fn a_rotated_moved_frame_maps_both_ways() {
let f = UcsFrame::WORLD.with_origin(Vec3::new(100.0, 50.0, 0.0)).rotated_z(30f64.to_radians());
assert!(f.is_planar() && !f.is_world());
assert!((f.rotation() - 30f64.to_radians()).abs() < 1e-12);
// The UCS X axis one unit out is 30° from world +X.
assert!(near(f.to_wcs(Vec2::new(1.0, 0.0)), Vec2::new(100.0 + 30f64.to_radians().cos(), 50.0 + 30f64.to_radians().sin())));
for p in [Vec2::new(0.0, 0.0), Vec2::new(12.0, -7.0), Vec2::new(-1e6, 3e5)] {
assert!(near(f.to_ucs(f.to_wcs(p)), p), "{p:?}");
let q = Vec3::new(p.x, p.y, 4.0);
assert!((f.to_ucs3(f.to_wcs3(q)) - q).len() < 1e-9);
}
assert!(near(f.vec_to_ucs(f.vec_to_wcs(Vec2::new(2.0, 3.0))), Vec2::new(2.0, 3.0)));
}
#[test]
fn new_squares_and_rejects() {
let f = UcsFrame::new(Vec3::ZERO, Vec3::new(2.0, 0.0, 0.0), Vec3::new(1.0, 5.0, 0.0)).unwrap();
assert_eq!((f.x, f.y), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)));
assert!(UcsFrame::new(Vec3::ZERO, Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0)).is_none());
assert!(UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 0.0)).is_none());
assert!(UcsFrame::new(Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)).is_none());
assert!(UcsFrame::new(Vec3::ZERO, Vec3::new(f64::INFINITY, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)).is_none());
}
#[test]
fn tilted_and_flipped_frames_are_not_planar() {
let front = UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0)).unwrap();
assert!(!front.is_planar());
let bottom = UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0)).unwrap();
assert!(!bottom.is_planar(), "Z down");
let raised = UcsFrame::WORLD.with_origin(Vec3::new(0.0, 0.0, 25.0));
assert!(raised.is_planar() && !raised.is_world());
}
#[test]
fn from_points() {
let w = UcsFrame::WORLD;
let o = Vec3::new(10.0, 10.0, 0.0);
assert_eq!(w.from_points(o, None, None), Some(w.with_origin(o)));
let f = w.from_points(o, Some(Vec3::new(10.0, 20.0, 0.0)), None).unwrap();
assert!((f.rotation() - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && f.is_planar());
// A third point on the negative-Y side of the X axis turns the UCS over.
let g = w.from_points(o, Some(Vec3::new(20.0, 10.0, 0.0)), Some(Vec3::new(15.0, 0.0, 0.0))).unwrap();
assert!(!g.is_planar());
assert!(w.from_points(o, Some(o), None).is_none());
assert!(w.from_points(o, Some(Vec3::new(20.0, 10.0, 0.0)), Some(Vec3::new(30.0, 10.0, 0.0))).is_none());
}
#[test]
fn stored_per_space() {
let mut d = Drawing::default();
let paper = Space::Paper(d.layouts[0].name.clone());
let f = UcsFrame::WORLD.with_origin(Vec3::new(5.0, 5.0, 0.0)).rotated_z(0.5);
set_current(&mut d, &Space::Model, &f, "SITE");
let (m, n) = current(&d, &Space::Model);
assert!((m.origin - f.origin).len() < 1e-12 && (m.x - f.x).len() < 1e-12 && n == "SITE");
assert_eq!(current(&d, &paper).0, UcsFrame::WORLD, "paper space has its own");
set_current(&mut d, &paper, &f, "");
assert!(d.layouts[0].ucs.is_some());
set_current(&mut d, &paper, &UcsFrame::WORLD, "");
assert!(d.layouts[0].ucs.is_none());
// Broken header values are the World UCS.
d.header.set("UCSXDIR", HVal::Point(Vec3::ZERO));
assert_eq!(current(&d, &Space::Model).0, UcsFrame::WORLD);
d.header.set("UCSXDIR", HVal::Point(Vec3::new(f64::NAN, 0.0, 0.0)));
assert_eq!(current(&d, &Space::Model).0, UcsFrame::WORLD);
}
}
+17 -54
View File
@@ -269,20 +269,11 @@ pub struct AngleSettings {
pub angbase: f64,
/// ANGDIR 1: positive angles turn clockwise.
pub clockwise: bool,
/// The current UCS's X axis, radians counterclockwise from world +X: directions are measured
/// in the UCS (ANGBASE from its X axis, the overrides and bearings too). Sizes of angles
/// ([`AngleSettings::amount`], [`AngleSettings::rotation`]) don't depend on it.
pub ucs: f64,
}
impl AngleSettings {
pub fn from_header(h: &cadcraft_doc::Header) -> Self {
AngleSettings { aunits: h.i64("AUNITS", 0), angbase: h.f64("ANGBASE", 0.0), clockwise: h.i64("ANGDIR", 0) != 0, ucs: 0.0 }
}
/// The same settings with directions measured in the World UCS (`*` coordinates).
pub fn world(&self) -> Self {
AngleSettings { ucs: 0.0, ..*self }
AngleSettings { aunits: h.i64("AUNITS", 0), angbase: h.f64("ANGBASE", 0.0), clockwise: h.i64("ANGDIR", 0) != 0 }
}
/// A typed angle size in radians (included angles, sweeps, angles from an axis): a bare
@@ -304,31 +295,29 @@ impl AngleSettings {
/// (AutoCAD refuses `<<N45dE` and `<<N`).
pub fn direction(&self, s: &str) -> Option<f64> {
let t = s.trim();
let ucs = |a: f64| Some(a + self.ucs).filter(|v| v.is_finite());
if let Some(r) = t.strip_prefix("<<<") {
return parse_units(r, self.aunits).and_then(|(a, _)| ucs(a));
return parse_units(r, self.aunits).map(|(a, _)| a);
}
if let Some(r) = t.strip_prefix("<<") {
return parse_units(r, 0).filter(|(_, bearing)| !bearing).and_then(|(a, _)| ucs(a));
return parse_units(r, 0).filter(|(_, bearing)| !bearing).map(|(a, _)| a);
}
let (a, _) = parse_units(t, self.aunits)?;
ucs(self.angbase + if self.clockwise { -a } else { a })
let v = self.angbase + if self.clockwise { -a } else { a };
v.is_finite().then_some(v)
}
/// Direction `dir` (radians counterclockwise from world +X) as the drawing shows directions,
/// in radians: from ANGBASE in the ANGDIR sense, measured in the current UCS (`ucs`) as typed
/// directions are read ([`AngleSettings::direction`]), 0 up to a full turn. (A block turned
/// 2.23° shows as 87.77 in a drawing measured clockwise from north, as in AutoCAD's Properties.)
/// Direction `dir` (radians counterclockwise from +X) as the drawing shows directions, in
/// radians: from ANGBASE in the ANGDIR sense, 0 up to a full turn. (A block turned 2.23°
/// shows as 87.77 in a drawing measured clockwise from north, as in AutoCAD's Properties.)
pub fn shown(&self, dir: f64) -> f64 {
let local = dir - self.ucs;
let a = if self.clockwise { self.angbase - local } else { local - self.angbase };
let a = if self.clockwise { self.angbase - dir } else { dir - self.angbase };
a.rem_euclid(std::f64::consts::TAU)
}
/// The direction (radians counterclockwise from world +X) the drawing shows as `v`
/// (radians): the inverse of [`AngleSettings::shown`].
/// The direction (radians counterclockwise from +X) the drawing shows as `v` (radians): the
/// inverse of [`AngleSettings::shown`].
pub fn unshown(&self, v: f64) -> f64 {
(self.ucs + self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU)
(self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU)
}
}
@@ -429,12 +418,9 @@ fn parse_dms(t: &str) -> Option<f64> {
}
impl crate::Session {
/// How typed angles are read in the current drawing (the defaults without one): directions
/// are measured in the current UCS.
/// How typed angles are read in the current drawing (the defaults without one).
pub fn angle_settings(&self) -> AngleSettings {
let a = self.doc().map(|d| AngleSettings::from_header(&d.header)).unwrap_or_default();
let ucs = self.input_ucs().rotation();
AngleSettings { ucs: if ucs.is_finite() { ucs } else { 0.0 }, ..a }
self.doc().map(|d| AngleSettings::from_header(&d.header)).unwrap_or_default()
}
}
@@ -478,7 +464,7 @@ mod tests {
#[test]
fn directions_show_from_angbase_in_the_angdir_sense() {
let north_clockwise = AngleSettings { aunits: 0, angbase: 90f64.to_radians(), clockwise: true, ucs: 0.0 };
let north_clockwise = AngleSettings { aunits: 0, angbase: 90f64.to_radians(), clockwise: true };
// AutoCAD shows a block turned 2.22729505553431° as 87.77 in such a drawing.
let shown = north_clockwise.shown(2.22729505553431f64.to_radians()).to_degrees();
assert!((shown - 87.77270494446569).abs() < 1e-9, "{shown}");
@@ -488,33 +474,10 @@ mod tests {
let plain = AngleSettings::default();
assert!((plain.shown(0.5) - 0.5).abs() < 1e-12 && (plain.unshown(0.5) - 0.5).abs() < 1e-12);
// Counterclockwise from a base of 30°: 45° shows as 15.
let based = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: false, ucs: 0.0 };
let based = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: false };
assert!((based.shown(45f64.to_radians()).to_degrees() - 15.0).abs() < 1e-9);
}
/// In a turned UCS, a shown direction (the Properties palette's Rotation) is measured from
/// the UCS X axis, as typed directions are: what is typed as 0 shows as 0, and back.
#[test]
fn shown_directions_are_measured_in_the_ucs() {
let turned = AngleSettings { ucs: 90f64.to_radians(), ..AngleSettings::default() };
let typed = turned.direction("0").unwrap();
assert!((typed - 90f64.to_radians()).abs() < 1e-12, "0 in the UCS is world 90°");
assert!(turned.shown(typed).abs() < 1e-12, "and shows as 0");
assert!((turned.unshown(0.0) - typed).abs() < 1e-12, "0 entered is that direction");
// With ANGBASE and ANGDIR too: every direction shown and entered back is itself.
let s = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: true, ucs: 50f64.to_radians() };
for deg in [0.0, 12.5, 90.0, 181.0, 359.0] {
let dir = f64::to_radians(deg);
let back = s.unshown(s.shown(dir));
assert!((back - dir).rem_euclid(std::f64::consts::TAU).min((dir - back).rem_euclid(std::f64::consts::TAU)) < 1e-9, "{deg}");
let typed = s.direction(&format!("{}", s.shown(dir).to_degrees())).unwrap();
assert!(
((typed - dir).rem_euclid(std::f64::consts::TAU)).min((dir - typed).rem_euclid(std::f64::consts::TAU)) < 1e-9,
"{deg}: shown then typed"
);
}
}
#[test]
fn decimal_and_arch() {
assert_eq!(format_distance(28.98524, 2, 4), "28.9852");
@@ -606,7 +569,7 @@ mod tests {
// What surveyor's units show for a due bearing can be typed back, e.g. `@10<E`. AutoCAD 2024
// reads the letter as an angle like any other, from ANGBASE in the ANGDIR sense: with
// ANGBASE 90 and ANGDIR 1, `@10<N` draws east.
let a = AngleSettings { aunits: 4, angbase: PI / 2.0, clockwise: true, ucs: 0.0 };
let a = AngleSettings { aunits: 4, angbase: PI / 2.0, clockwise: true };
for (t, want) in [("E", PI / 2.0), ("n", 0.0), ("W", 1.5 * PI), ("s", PI)] {
let got = a.direction(t).unwrap().rem_euclid(2.0 * PI);
assert!((got - want).abs() < 1e-12, "{t}: {got}");
+2 -2
View File
@@ -84,7 +84,7 @@ fn bearings_and_compass_points_turn_with_angbase_and_angdir() {
assert_near(line_end(&mut s, to), 10.0 * a.cos(), 10.0 * a.sin(), &format!("{to} AUNITS {aunits} ANGBASE {angbase} ANGDIR {angdir}"));
}
// `<<` is in degrees only: AutoCAD refuses a bearing or a compass point there.
let settings = AngleSettings { aunits: 0, angbase: std::f64::consts::FRAC_PI_2, clockwise: true, ucs: 0.0 };
let settings = AngleSettings { aunits: 0, angbase: std::f64::consts::FRAC_PI_2, clockwise: true };
assert_eq!(settings.direction("<<N45dE"), None);
assert_eq!(settings.direction("<<N"), None);
assert!(settings.direction("<<45").is_some_and(|a| (a - std::f64::consts::FRAC_PI_4).abs() < 1e-12));
@@ -161,7 +161,7 @@ fn json_and_default_parsing_keep_degrees_from_east() {
// SETVAR reports ANGBASE in degrees.
let v = cadcraft_engine::sysvars::get(&s, "ANGBASE").unwrap();
assert!((v.as_f64().unwrap() - 90.0).abs() < 1e-9, "{v}");
let a = AngleSettings { aunits: 0, angbase: 0.0, clockwise: false, ucs: 0.0 };
let a = AngleSettings { aunits: 0, angbase: 0.0, clockwise: false };
assert_eq!(a.direction(""), None);
assert_eq!(a.direction("nan"), None);
assert_eq!(a.direction("1e400"), None);
+202
View File
@@ -0,0 +1,202 @@
//! The Key point option of a base point: ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and
//! REPlace) take the source objects' key point (an end point, midpoint, centre…) nearest the
//! picked point as the base point; the JSON forms take `keyPoint`.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{ArrayKind, ArrayParams, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::json;
fn source_line(s: &mut Session) -> String {
let r = s.execute("line", &json!({"points": [[0, 0], [2, 1]]})).unwrap();
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()
}
fn handle(v: &serde_json::Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
}
/// The array's insertion point (its base point) and parameters.
fn array(s: &Session, h: Handle) -> (Vec2, ArrayParams) {
let d = s.doc().unwrap();
let e = d.entity(h).unwrap();
let EntityKind::Insert(i) = &e.kind else { panic!("not an array") };
(i.insert.xy(), d.array_params(e).unwrap())
}
fn only_array(s: &Session) -> Handle {
let d = s.doc().unwrap();
let arrays: Vec<Handle> = d.model.iter().filter(|e| d.array_params(e).is_some()).map(|e| e.handle).collect();
assert_eq!(arrays.len(), 1);
arrays[0]
}
fn typed(s: &mut Session, inputs: &[&str]) {
for t in inputs {
s.cmdline(t).unwrap();
}
}
#[test]
fn arrayrect_and_arraypolar_take_a_key_point_as_the_base_point() {
let mut s = Session::new();
let l = source_line(&mut s);
let r = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "keyPoint": [1.9, 1.05]})).unwrap();
assert!(array(&s, handle(&r)).0.near(Vec2::new(2.0, 1.0), 1e-9));
let mut s = Session::new();
let l = source_line(&mut s);
let r = s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "keyPoint": [1.1, 0.4]})).unwrap();
assert!(array(&s, handle(&r)).0.near(Vec2::new(1.0, 0.5), 1e-9), "the line's midpoint");
}
#[test]
fn typed_key_points_at_arrayrect_and_arraypolar() {
let mut s = Session::new();
source_line(&mut s);
typed(&mut s, &["arrayrect", "l", "", "b", "k", "1.9,0.95", "x"]);
assert!(array(&s, only_array(&s)).0.near(Vec2::new(2.0, 1.0), 1e-9));
// Enter at the key point prompt goes back to the base point prompt.
let mut s = Session::new();
source_line(&mut s);
typed(&mut s, &["arraypolar", "l", "", "b", "k"]);
assert!(s.current_prompt().unwrap().message.contains("key point"));
typed(&mut s, &[""]);
assert!(s.current_prompt().unwrap().message.contains("base point"));
typed(&mut s, &["k", "0.1,0.1", "-10,0", "x"]);
assert!(array(&s, only_array(&s)).0.near(Vec2::new(0.0, 0.0), 1e-9));
}
#[test]
fn arrayedit_moves_the_base_point_to_a_key_point_of_an_item() {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
// Near the start of the third item: the base point goes to (10, 0), the items stay.
s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [10.2, 0.05]})).unwrap();
let (at, p) = array(&s, h);
assert!(at.near(Vec2::new(10.0, 0.0), 1e-9), "{at:?}");
assert!(matches!(p.kind, ArrayKind::Rect(r) if r.cols == 3 && r.col_spacing == 5.0));
let items = s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
assert!(items.to_string().len() > 2);
let d = s.doc().unwrap();
let mut starts: Vec<(i64, i64)> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(((l.a.x * 10.0).round() as i64, (l.a.y * 10.0).round() as i64)),
_ => None,
})
.collect();
starts.sort();
assert_eq!(starts, [(0, 0), (50, 0), (100, 0)]);
// Not on an item: refused.
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [3.5, 40]})).is_err());
assert!(array(&s, h).0.near(Vec2::ZERO, 1e-9));
// Typed: Base point, Key point, a point on the second item near its end.
s.set_selection(vec![h]);
typed(&mut s, &["arrayedit", "b", "k", "6.9,0.9", "x"]);
assert!(array(&s, h).0.near(Vec2::new(7.0, 1.0), 1e-9));
}
#[test]
fn replacement_objects_take_a_key_point_as_their_base_point() {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
// The circle's right quadrant is the base point: on item 1 (at x = 5) its centre is at x = 4.
s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": [51.2, 50.1], "items": [[1, 0, 0]]}})).unwrap();
s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
let d = s.doc().unwrap();
// The replaced item stays a reference to the replacement block.
let centres: Vec<Vec2> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Insert(i) => d.block(&i.block).map(|b| (i.transform(b.base.xy()), b)),
_ => None,
})
.flat_map(|(m, b)| {
b.entities
.iter()
.filter_map(move |e| match &e.kind {
EntityKind::Circle(c) => Some(m.apply(c.center.xy())),
_ => None,
})
.collect::<Vec<_>>()
})
.collect();
assert!(centres.iter().any(|c| c.near(Vec2::new(4.0, 0.0), 1e-9)), "{centres:?}");
}
#[test]
fn hostile_key_points_never_panic() {
let mut s = Session::new();
let l = source_line(&mut s);
for kp in [json!(["a", 1]), json!([1e308, -1e308]), json!([]), json!("x"), json!(null)] {
let _ = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": kp}));
let _ = s.execute("arraypolar", &json!({"handles": [l], "center": [5, 5], "count": 3, "keyPoint": kp}));
}
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
for kp in [json!([1e308, 1e308]), json!([-1e308, 0]), json!(["x"]), json!([0.5, 0.25])] {
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": kp}));
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [], "keyPoint": kp, "items": [[0, 0, 0]]}}));
}
// Typed key points far away or on nothing are refused without leaving the command broken.
s.set_selection(vec![h]);
typed(&mut s, &["arrayedit", "b", "k"]);
assert!(s.cmdline("1e300,1e300").is_err() || s.running.is_some());
s.cancel();
}
/// A `keyPoint` that is there but isn't a point is refused, not taken as no key point (which
/// would make the array at another base point).
#[test]
fn a_key_point_that_is_not_a_point_is_refused() {
let mut s = Session::new();
let l = source_line(&mut s);
assert!(s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": ["bad", 1]})).is_err());
assert!(s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 3, "keyPoint": "x"})).is_err());
assert!(s.doc().unwrap().model.iter().all(|e| s.doc().unwrap().array_params(e).is_none()), "no array made");
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [1]})).is_err());
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": {}, "items": [[1, 0, 0]]}})).is_err());
}
/// More objects than the key point search takes are refused rather than searched in part, which
/// could miss the nearest key point.
#[test]
fn a_key_point_of_too_many_objects_is_refused() {
let mut s = Session::new();
// 10,001 lines; the last one ends nearest the key point.
let pts: Vec<[f64; 2]> = (0..10_002).map(|i| [f64::from(i), 0.0]).collect();
let r = s.execute("line", &json!({ "points": pts })).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
assert_eq!(hs.len(), 10_001, "{r}");
let e = s.execute("arraypolar", &json!({"handles": hs, "center": [0, -50], "count": 2, "keyPoint": [10_001.2, 0]})).unwrap_err();
assert!(e.to_string().contains("10000"), "{e}");
}
/// ARRAYEDIT with a new base point (`base` or `keyPoint`) and a polar `center` in one call puts the
/// centre where asked: the base point moves the array's insertion point, so the centre is read in
/// the array's placement after that move.
#[test]
fn arrayedit_center_with_a_new_base_point_lands_where_asked() {
for (key, at) in [("base", json!([2, 1])), ("keyPoint", json!([1.95, 0.99]))] {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "base": [0, 0]})).unwrap());
s.execute("arrayedit", &json!({"handle": h.hex(), key: at, "center": [5, 0]})).unwrap();
let (ins, p) = array(&s, h);
let ArrayKind::Polar(k) = p.kind else { panic!("not polar") };
assert!(ins.near(Vec2::new(2.0, 1.0), 1e-9), "{key}: {ins:?}");
// The centre is kept relative to the insertion point.
assert!((ins + k.center).near(Vec2::new(5.0, 0.0), 1e-9), "{key}: centre at {:?}", ins + k.center);
}
}
+43 -4
View File
@@ -83,14 +83,22 @@ fn dash_attedit_one_at_a_time_edits_the_selected_attributes() {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", ""]);
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
// Unsupported options say so and keep the prompt.
s.cmdline("p").unwrap();
assert!(s.log.iter().any(|l| l.contains("Position is not available yet")), "{:?}", s.log);
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
// Edit Position, Height, Angle, and Style
type_lines(&mut s, &["p", "10,20", "h", "2.5", "a", "45", "s", "Standard"]);
// Edit Value: change and replace
type_lines(&mut s, &["v", "c", "b", "B", "v", "r", "replaced value", "n"]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(value(&s, h, "T"), "replaced value");
assert_eq!(value(&s, h, "U"), "u");
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
let att = ins.attribs.iter().find(|a| a.tag == "T").unwrap();
assert!((att.text.insert.x - 10.0).abs() < 1e-6);
assert!((att.text.insert.y - 20.0).abs() < 1e-6);
assert!((att.text.height - 2.5).abs() < 1e-6);
assert!((att.text.rotation.to_degrees() - 45.0).abs() < 1e-4);
assert_eq!(att.text.style, "Standard");
}
#[test]
@@ -109,3 +117,34 @@ fn attribute_tags_match_in_any_case_and_unknown_tags_are_reported() {
let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "four"}})).unwrap();
assert_eq!(r, json!({"changed": 1}));
}
/// -ATTEDIT Position moves an aligned or fit attribute without losing its baseline: both of its
/// points move by the same offset (setting both to the picked point would leave no direction or
/// length to fit the text between).
#[test]
fn dash_attedit_position_keeps_an_aligned_attributes_baseline() {
use cadcraft_doc::HAlign;
use cadcraft_geom::Vec3;
for halign in [HAlign::Aligned, HAlign::Fit] {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
for a in i.attribs.iter_mut().filter(|a| a.tag == "T") {
a.text.halign = halign;
a.text.insert = Vec3::new(100.0, 1.0, 0.0);
a.text.align_pt = Some(Vec3::new(104.0, 1.0, 0.0));
}
}
})
.unwrap();
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", "", "p", "10,20", "n"]);
assert!(s.running.is_none(), "{}", s.prompt_text());
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
let t = &ins.attribs.iter().find(|a| a.tag == "T").unwrap().text;
assert!(t.insert.xy().near(cadcraft_geom::Vec2::new(10.0, 20.0), 1e-9), "{halign:?}: {:?}", t.insert);
assert!(t.align_pt.is_some_and(|p| p.xy().near(cadcraft_geom::Vec2::new(14.0, 20.0), 1e-9)), "{halign:?}: {:?}", t.align_pt);
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ fn dash_attedit_sets_layer_and_colour_of_one_attribute() {
for t in ["-attedit", "y", "", "T", "", "105,0", ""] {
s.cmdline(t).unwrap();
}
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
s.cmdline("l").unwrap();
assert!(s.prompt_text().contains("Enter new layer name <0>"), "{}", s.prompt_text());
// An unknown layer is refused and asked again.
@@ -0,0 +1,247 @@
//! -LAYER stAte: AutoCAD 2024's layer state prompts and messages (measured with accoreconsole on a
//! drawing with layers A, red, and B), and the `layerstate.*` commands they run.
use cadcraft_engine::doc::LayerState;
use cadcraft_engine::{Input, Session};
use serde_json::json;
const LABELS: [&str; 10] = ["On", "Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"];
/// The toggles AutoCAD lists before "Enter states to change", with `no` the ones set to No.
fn table(no: &[&str]) -> Vec<String> {
let mut v = vec!["States".to_string()];
v.extend(LABELS.iter().map(|l| format!("{l:<20}{}", if no.contains(l) { "No" } else { "Yes" })));
v
}
/// Layers A (red) and B; the current layer stays 0.
fn drawing() -> Session {
let mut s = Session::new();
s.script("-LAYER N A,B C 1 A\n\n").unwrap();
s
}
/// Run `script` to its end and return what it wrote besides the commands' names and -LAYER's
/// "Current layer" line.
fn run(s: &mut Session, script: &str) -> Vec<String> {
let at = s.log.len();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script:?} ends at: {}", s.prompt_text());
s.log[at..].iter().filter(|l| !l.starts_with("Command: ") && !l.starts_with("Current layer:")).cloned().collect()
}
fn states(s: &Session) -> Vec<(String, u32)> {
s.doc().unwrap().layer_states.iter().map(|st| (st.name.clone(), st.mask)).collect()
}
fn state(name: &str, mask: u32) -> (String, u32) {
(name.to_string(), mask)
}
#[test]
fn save_asks_the_states_and_remembers_them_for_the_next_save() {
let mut s = drawing();
// Each toggle lists the states again; On off is AutoCAD's 2046.
let out = run(&mut s, "-LAYER A S S6 ON\n\n\n\nLINE 0,0 1,0\n\n");
assert_eq!(out, [table(&[]), table(&["On"])].concat());
assert_eq!(states(&s), [state("S6", 2046)]);
assert_eq!(s.doc().unwrap().model.len(), 1, "the next command runs");
// The next Save starts from the toggles the last one left: On alone is 513, then every
// toggle once more is 2046 (AutoCAD's S7 and S8).
let out = run(&mut s, "-LAYER A S S7 ON F L P N C T W TR S\n\n\n\n");
assert_eq!(out[..11], table(&["On"]));
assert_eq!(
out[out.len() - 11..],
table(&["Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"])
);
run(&mut s, "-LAYER A S S8 ON F L P N C T W TR S\n\n\n\n");
run(&mut s, "-LAYER A S S9 ON\n\n\n\n");
assert_eq!(states(&s)[1..], [state("S7", 513), state("S8", 2046), state("S9", LayerState::ALL)]);
// Edit lists and changes the state's own mask (found in any case), not the next Save's
// toggles (AutoCAD: Edit S1 to 2015, then S2 is 2047).
let out = run(&mut s, "-LAYER A E s6 ON C\n\n\n\n");
assert_eq!(out, [table(&["On"]), table(&[]), table(&["Color"])].concat());
run(&mut s, "-LAYER A S S10\n\n\n\n");
assert_eq!(states(&s)[0], state("S6", 2015));
assert_eq!(states(&s)[4], state("S10", LayerState::ALL));
// Each -LAYER is one undo step.
s.undo().unwrap();
assert_eq!(states(&s).len(), 4);
s.undo().unwrap();
assert_eq!(states(&s)[0], state("S6", 2046));
// A state from AutoCAD after a restore (mask 67583 = 2047 + 65536) named as AutoCAD names a
// state renamed to "*X": `?` lists it, and Edit keeps the bit no toggle reaches.
s.doc_mut().unwrap().layer_states.push(LayerState { name: "*A1".into(), mask: 67583, ..LayerState::default() });
assert_eq!(
run(
&mut s,
"-LAYER A ?
"
)[2],
"*A1"
);
run(
&mut s,
"-LAYER A E *a1 C
",
);
assert_eq!(states(&s)[4], state("*A1", 67583 - 32));
}
#[test]
fn names_follow_autocads_rules_and_messages() {
let mut s = drawing();
run(&mut s, "-LAYER A S S1\n\n\n\n");
// A saved name in another case is refused and asked again.
let out = run(&mut s, "-LAYER A S s1 S2\n\n\n\n");
assert_eq!(out, [vec!["Layer state \"s1\" already exists.".to_string()], table(&[])].concat());
// The layer name characters, and more than 255 characters, are refused; Enter goes back.
let long = "y".repeat(256);
let out = run(&mut s, &format!("-LAYER A S *X a<b a,b {long}\n\n\n\n"));
assert_eq!(
out,
[
"\"*X\" is an invalid layer state name.",
"\"a<b\" is an invalid layer state name.",
"\"a,b\" is an invalid layer state name.",
&format!("\"{long}\" is an invalid layer state name.")
]
);
run(&mut s, &format!("-LAYER A S {}\n\n\n\n", "x".repeat(255)));
assert_eq!(states(&s).len(), 3);
run(&mut s, &format!("-LAYER A D {}\n\n\n", "x".repeat(255)));
// `?` lists by name without regard to case.
run(&mut s, "-LAYER A S b\n\n\n\n");
let list = ["Layer state", "-----------------------------", "b", "S1", "S2"];
assert_eq!(run(&mut s, "-LAYER A ?\n\n\n"), list);
// Each name prompt lists on `?`, says an unknown name and asks again, and Enter goes back.
let out = run(&mut s, "-LAYER A R ? NOSUCH\n\nE NOSUCH\n\nN NOSUCH\n\nD NOSUCH\n\n\n\n");
assert_eq!(out[..5], list);
assert_eq!(out[5..], ["Unknown layer state name."; 4]);
// Unknown options, Import and EXport.
let out = run(&mut s, "-LAYER A XYZ I EX\n\n\n");
assert_eq!(out, ["Invalid option keyword.", "-LAYER stAte Import is not available yet.", "-LAYER stAte EXport is not available yet."]);
let out = run(&mut s, "-LAYER A S T1 XYZ\n\n\n\n");
assert_eq!(out, [table(&[]), vec!["Invalid option keyword.".to_string()]].concat());
assert_eq!(states(&s).len(), 4, "T1 is saved after the invalid toggle");
run(&mut s, "-LAYER A D T1\n\n\n");
// Name: a name some state has in any case, the state's own too, is refused with two lines.
assert_eq!(run(&mut s, "-LAYER A N S1 S2\n\n\n"), ["Layer state could not be renamed.", "S2 already exists."]);
assert_eq!(run(&mut s, "-LAYER A N S1 s1\n\n\n"), ["Layer state could not be renamed.", "s1 already exists."]);
// A name with a refused character leaves the state as it is, with no message; Enter too.
assert!(run(&mut s, "-LAYER A N S1 a,b\n\n\n").is_empty());
assert!(run(&mut s, "-LAYER A N S1\n\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S1", "S2", "b"]);
// The old name in another case.
assert!(run(&mut s, "-LAYER A N s1 S9\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S9", "S2", "b"]);
assert!(run(&mut s, "-LAYER A D s9\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S2", "b"]);
}
#[test]
fn esc_drops_the_state_being_saved_and_undo_takes_back_name_and_delete() {
let mut s = drawing();
run(
&mut s,
"-LAYER A S S1
",
);
// Esc at the toggles: that state isn't saved and the next Save's toggles stay as they were;
// what the same -LAYER did before Esc stays, as for the other -LAYER options.
s.script(
"-LAYER A S S2
S S3 C ON
",
)
.unwrap();
// AutoCAD 2024 asks for the toggles without "or" before them.
assert_eq!(
s.current_prompt().unwrap().display(),
"Enter states to change [On/Frozen/Lock/Plot/Newvpfreeze/Color/lineType/lineWeight/TRansparency/plotStyle]:"
);
s.input(Input::Cancel).unwrap();
assert!(s.running.is_none());
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
assert_eq!(s.settings.layer_state_mask, LayerState::ALL);
// Name and Delete are one undo step each, like Save.
run(
&mut s,
"-LAYER A N S1 S9
",
);
run(
&mut s,
"-LAYER A D S2
",
);
assert_eq!(states(&s), [state("S9", LayerState::ALL)]);
s.undo().unwrap();
assert_eq!(states(&s), [state("S9", LayerState::ALL), state("S2", LayerState::ALL)]);
s.undo().unwrap();
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
}
#[test]
fn restore_finds_the_state_in_any_case() {
let mut s = drawing();
run(&mut s, "-LAYER A S S1\n\n\n\n");
run(&mut s, "-LAYER C 3 A M C\n\n");
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(3), "C".to_string()));
assert!(run(&mut s, "-LAYER A R s1\n\n\n").is_empty());
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(1), "0".to_string()));
}
#[test]
fn json_layer_states_take_a_mask_and_find_names_in_any_case() {
let mut s = drawing();
s.execute("layerstate.save", &json!({ "name": "M" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "On", "mask": LayerState::ON })).unwrap();
for bad in [json!(4096), json!(-1), json!(1.5), json!("1")] {
assert!(s.execute("layerstate.save", &json!({ "name": "X", "mask": bad })).is_err(), "{bad}");
}
assert_eq!(states(&s), [state("M", LayerState::ALL), state("On", 513)]);
// Restore, Rename and Delete find a name in another case; a name another state has in any
// case is refused, the state's own in another case too.
s.execute("layer.set", &json!({ "name": "A", "color": "3" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "m" })).unwrap();
assert_eq!(s.doc().unwrap().layer("A").unwrap().color, cadcraft_color::Color::Index(1));
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "ON" })).is_err());
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "m" })).is_err());
s.execute("layerstate.rename", &json!({ "from": "m", "to": "M2" })).unwrap();
s.execute("layerstate.delete", &json!({ "name": "on" })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
// A name -LAYER stAte Save refuses is refused here too, and nothing is saved.
let long = "x".repeat(256);
for name in ["", " ", "a<b", "a\nb", long.as_str()] {
assert!(s.execute("layerstate.save", &json!({ "name": name })).is_err(), "{name:?}");
}
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
// Save onto a name another state has in another case replaces that state, as one spelled the
// same: AutoCAD 2024 keeps one state per name in any case.
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON })).unwrap();
assert_eq!(states(&s), [state("m2", 513)]);
// Names that differ only in case (CADCraft's own record keeps the second of them, which AutoCAD
// 2024 doesn't see): Save and Delete take the one spelled so, though the other comes first, and
// leave the other.
s.doc_mut().unwrap().layer_states.insert(0, LayerState::new("M2", Vec::new(), ""));
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON | LayerState::FROZEN })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL), state("m2", 515)]);
s.execute("layerstate.delete", &json!({ "name": "m2" })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
}
+2
View File
@@ -4,6 +4,7 @@ mod annotate_options;
mod annotative;
mod arc_ctrl_direction;
mod array_commands;
mod array_key_point;
mod assoc_array;
mod attdef_command;
mod attdisp_attsync;
@@ -78,6 +79,7 @@ mod join_close;
mod json_param_validation;
mod layer_cmdline;
mod layer_merge_delete;
mod layer_state_cmdline;
mod layoff_repeat;
mod layout_prompts;
mod leader_command;
+128 -6
View File
@@ -76,13 +76,135 @@ fn rename_prompts_type_old_and_new_name() {
assert!(d.block("Pump").is_some() && d.layer("New").is_some() && d.layer("Old").is_none(), "{:?}", s.log);
assert_eq!(insert_targets(d), ["Assy", "Pump", "Pump", "Pump"]);
assert_eq!(d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
// An unknown old name re-prompts; a type CADCraft lacks reads both names and reports.
s.script("-RENAME LA Missing\nNew\nNewer\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.doc().unwrap().layer("Newer").is_some());
// A type CADCraft lacks reads both names and reports.
let n = s.log.len();
s.script("-RENAME VP a b\nLINE 0,0 2,0\n\n").unwrap();
s.script("-RENAME M a b\nLINE 0,0 2,0\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.log[n..].iter().any(|l| l.contains("not available yet")), "{:?}", &s.log[n..]);
assert!(s.log[n..].iter().any(|l| l.contains("Renaming a material is not available yet.")), "{:?}", &s.log[n..]);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 2);
}
/// What `script` adds to the log; the command has ended.
fn said(s: &mut Session, script: &str) -> Vec<String> {
let n = s.log.len();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
s.log[n..].to_vec()
}
fn says(log: &[String], text: &str) -> bool {
log.iter().any(|l| l.contains(text))
}
#[test]
fn rename_ends_on_a_name_it_cannot_take_with_autocads_messages() {
// AutoCAD 2024 (accoreconsole, measured, the same for blocks, dimension styles, layers,
// linetypes, text styles, UCSs and views): `Cannot find layer "X".` for an old name that
// doesn't exist, `A layer named "X" already exists.` and `*Invalid*` for a new name that does,
// `Invalid layer name.` for one it can't take; each ends the command.
let mut s = drawing();
for name in ["A1", "A2"] {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
let log = said(&mut s, "-RENAME LA NOSUCH\nLINE 0,0 3,0\n\n");
assert!(says(&log, "Cannot find layer \"NOSUCH\"."), "{log:?}");
// The command ended there: the next input started LINE.
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
let log = said(&mut s, "-RENAME LA A1 A2\n");
assert!(says(&log, "A layer named \"A2\" already exists.") && says(&log, "*Invalid*"), "{log:?}");
let log = said(&mut s, "-RENAME LA A1 X<Y\n");
assert!(says(&log, "Invalid layer name."), "{log:?}");
// No new name at all is an invalid one too.
s.cmdline("-RENAME LA A1").unwrap();
let n = s.log.len();
s.cmdline("").unwrap();
assert!(s.running.is_none() && says(&s.log[n..], "Invalid layer name."), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().layer("A1").is_some());
said(&mut s, "-RENAME LA A1 B1\n");
assert!(s.doc().unwrap().layer("B1").is_some() && s.doc().unwrap().layer("A1").is_none());
// The old name in another case than stored, and the new name as typed: a rename to that case
// (AutoCAD 2024, measured: LAY1 typed lay1, new name lay1, gives lay1).
said(&mut s, "-RENAME LA b1 b1\n");
assert!(s.doc().unwrap().layers.iter().any(|l| l.name == "b1"));
// Old names AutoCAD 2024 won't rename (measured), each ending the command before the new name.
let lines = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
for (script, message) in [
("-RENAME LA 0\n", "Cannot rename layer \"0\"."),
("-RENAME LT continuous\n", "Cannot rename linetype \"continuous\"."),
("-RENAME LT ByLayer\n", "Invalid linetype name."),
("-RENAME LT byblock\n", "Invalid linetype name."),
("-RENAME LT CONTINUOUS\n", "Cannot rename linetype \"CONTINUOUS\"."),
("-RENAME B *Model_Space\n", "Invalid block name."),
("-RENAME B *U1\n", "Invalid block name."),
] {
let n = lines(&s);
let log = said(&mut s, &format!("{script}LINE 0,0 4,0\n\n"));
assert!(says(&log, message), "{script}: {log:?}");
assert_eq!(says(&log, "*Invalid*"), message.starts_with("Cannot"), "{script}: {log:?}");
assert_eq!(lines(&s), n + 1, "{script}: the next input starts a command");
}
// A UCS is "ucs" in the prompts and in "A ucs named", "UCS" in the other two.
for name in ["U1", "U2"] {
let ucs = cadcraft_engine::doc::Ucs { name: name.into(), origin: Default::default(), x_axis: Default::default(), y_axis: Default::default() };
s.doc_mut().unwrap().ucss.push(ucs);
}
s.cmdline("-RENAME U").unwrap();
assert!(s.prompt_text().contains("Enter old ucs name"), "{}", s.prompt_text());
s.cancel();
assert!(says(&said(&mut s, "-RENAME U NOSUCH\n"), "Cannot find UCS \"NOSUCH\"."));
assert!(says(&said(&mut s, "-RENAME U U1 U2\n"), "A ucs named \"U2\" already exists."));
assert!(says(&said(&mut s, "-RENAME U U1 X<Y\n"), "Invalid UCS name."));
}
#[test]
fn rename_takes_a_saved_viewport_configuration() {
// AutoCAD 2024 (measured): -RENAME VPort renames a saved configuration, every tile of it, old
// name in any case, and to another case of its own name; "*ACTIVE" (old or new), names with
// characters AutoCAD refuses and names already used are refused as for the other types.
let mut s = Session::new();
s.execute("-vports", &json!({ "option": "2", "arrangement": "vertical" })).unwrap();
s.execute("-vports", &json!({ "option": "save", "name": "CFG1" })).unwrap();
s.execute("-vports", &json!({ "option": "save", "name": "CFG3" })).unwrap();
let names = |s: &Session| -> Vec<(String, usize)> { s.doc().unwrap().vports.iter().map(|v| (v.name.clone(), v.tiles.len())).collect() };
said(&mut s, "-RENAME VP cfg1 CFG2\n");
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
for (script, message) in [
// A refused old name ends the command before the new name is asked.
("-RENAME VP NOSUCH\n", "Cannot find viewport configuration \"NOSUCH\"."),
("-RENAME VP *ACTIVE\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 *ACTIVE\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 A<B\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 CFG3\n", "A viewport configuration named \"CFG3\" already exists."),
] {
let log = said(&mut s, script);
assert!(says(&log, message), "{script}: {log:?}");
// "*Invalid*" follows a name already used only.
assert_eq!(says(&log, "*Invalid*"), message.ends_with("already exists."), "{script}: {log:?}");
}
// No new name at all is an invalid one too (measured: CFG1, then Enter).
s.cmdline("-RENAME VP CFG2").unwrap();
let n = s.log.len();
s.cmdline("").unwrap();
assert!(s.running.is_none() && says(&s.log[n..], "Invalid viewport configuration name."), "{:?}", &s.log[n..]);
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
said(&mut s, "-RENAME VP CFG2 cfg2\n");
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("CFG3".to_string(), 2)]);
// The new name is compared with the stored one, not with the old name as typed (measured:
// CFG1 typed cfg1 to cfg1 gives cfg1; typed cfg1 to CFG1 changes nothing).
said(&mut s, "-RENAME VP CFG2 CFG2\n");
assert_eq!(names(&s)[1].0, "CFG2");
said(&mut s, "-RENAME VP cfg2 CFG2\n");
assert_eq!(names(&s)[1].0, "CFG2");
said(&mut s, "-RENAME VP cfg2 cfg2\n");
assert_eq!(names(&s)[1].0, "cfg2");
// The JSON form too, which never takes the configuration shown, and refuses a name already
// used (in any case) or with a character AutoCAD refuses, as for the other tables.
s.execute("rename", &json!({ "table": "vport", "from": "CFG3", "to": "Pair" })).unwrap();
assert_eq!(names(&s)[2].0, "Pair");
for to in ["Shown", "CFG2", "A<B"] {
let from = if to == "Shown" { "*Active" } else { "Pair" };
assert!(s.execute("rename", &json!({ "table": "vport", "from": from, "to": to })).is_err(), "{from} to {to}");
}
s.execute("rename", &json!({ "table": "vport", "from": "pair", "to": "PAIR" })).unwrap();
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("PAIR".to_string(), 2)]);
}
-765
View File
@@ -1,765 +0,0 @@
//! The user coordinate system (#1106): the UCS command and its options, typed coordinates and
//! directions read in the current UCS, coordinates shown in it, the UCS system variables,
//! UCSICON, paper space's own UCS, undo, and hostile input.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, HVal, Space};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::ucs::UcsFrame;
use serde_json::{Value, json};
const TAU: f64 = std::f64::consts::TAU;
fn session() -> Session {
let mut s = Session::new();
s.new_drawing(false);
s
}
fn typed(s: &mut Session, lines: &[&str]) {
for l in lines {
s.cmdline(l).unwrap();
}
}
fn near(a: Vec2, x: f64, y: f64) -> bool {
a.dist(Vec2::new(x, y)) < 1e-9
}
fn near3(a: Vec3, b: Vec3) -> bool {
(a - b).len() < 1e-9
}
fn ang_eq(a: f64, b: f64) -> bool {
let d = (a - b).rem_euclid(TAU);
d < 1e-9 || TAU - d < 1e-9
}
fn lines(s: &Session) -> Vec<(Vec2, Vec2)> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).collect()
}
fn last_line(s: &Session) -> (Vec2, Vec2) {
*lines(s).last().expect("a line")
}
fn logged(s: &Session, text: &str) -> bool {
s.log.iter().any(|l| l.contains(text))
}
fn var(s: &Session, name: &str) -> Value {
cadcraft_engine::sysvars::get(s, name).unwrap_or(Value::Null)
}
fn vec3(v: &Value) -> Vec3 {
Vec3::new(v[0].as_f64().unwrap(), v[1].as_f64().unwrap(), v[2].as_f64().unwrap())
}
/// A UCS at (100, 50) turned 90°: UCS X is world +Y, UCS Y is world -X.
fn turned(s: &mut Session) {
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap();
let u = s.ucs();
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}");
}
// ---------------- the UCS command ----------------
#[test]
fn a_new_drawing_is_in_the_world_ucs() {
let s = session();
assert!(s.ucs().is_world());
assert_eq!(var(&s, "WORLDUCS"), json!(1));
assert_eq!(var(&s, "UCSNAME"), json!(""));
assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::ZERO));
assert!(near3(vec3(&var(&s, "UCSXDIR")), Vec3::new(1.0, 0.0, 0.0)));
assert!(near3(vec3(&var(&s, "UCSYDIR")), Vec3::new(0.0, 1.0, 0.0)));
}
#[test]
fn ucs_origin_then_enter_moves_the_origin_and_keeps_the_axes() {
let mut s = session();
typed(&mut s, &["ucs 100,50 "]);
assert!(logged(&s, "Current ucs name: *WORLD*"));
let u = s.ucs();
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)));
assert_eq!(var(&s, "WORLDUCS"), json!(0));
assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::new(100.0, 50.0, 0.0)));
typed(&mut s, &["ucs "]);
assert!(logged(&s, "Current ucs name: *NO NAME*"), "{:?}", s.log);
assert!(s.ucs().is_world(), "Enter at the first prompt is World");
}
#[test]
fn ucs_by_three_points() {
let mut s = session();
// Origin, a point on the new X axis (straight up), Enter: Y square to it.
typed(&mut s, &["ucs 10,10 10,30 "]);
let u = s.ucs();
assert!(near3(u.origin, Vec3::new(10.0, 10.0, 0.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)) && near3(u.y, Vec3::new(-1.0, 0.0, 0.0)), "{u:?}");
// All three points; typed points are read in the UCS current while UCS runs.
typed(&mut s, &["ucs w", "ucs 0,0 1,1 -1,1"]);
let u = s.ucs();
let r = std::f64::consts::FRAC_1_SQRT_2;
assert!(near3(u.x, Vec3::new(r, r, 0.0)) && near3(u.y, Vec3::new(-r, r, 0.0)) && u.is_planar(), "{u:?}");
// A third point below the X axis would turn the UCS over: refused, and the UCS is kept.
let before = s.ucs();
let _ = s.cmdline("ucs 0,0 10,0 5,-5");
assert!(near3(s.ucs().x, before.x), "a turned-over UCS is not taken");
s.cancel();
// Points on one line define nothing.
assert!(s.execute("ucs", &json!({"origin": [0, 0], "xPoint": [10, 0], "xyPoint": [20, 0]})).is_err());
assert!(s.execute("ucs", &json!({"origin": [0, 0], "xPoint": [0, 0]})).is_err());
}
#[test]
fn ucs_z_turns_about_z_and_defaults_to_ucsaxisang() {
let mut s = session();
typed(&mut s, &["ucs z 30"]);
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
typed(&mut s, &["ucs z "]);
assert!(ang_eq(s.ucs().rotation(), 120f64.to_radians()), "Enter takes UCSAXISANG (90)");
cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(45)).unwrap();
typed(&mut s, &["ucs z "]);
assert!(ang_eq(s.ucs().rotation(), 165f64.to_radians()));
assert!(cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(33)).is_err(), "only the listed angles");
typed(&mut s, &["ucs z -165"]);
assert!(ang_eq(s.ucs().rotation(), 0.0));
// 30 is one of the listed angles too.
cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(30)).unwrap();
typed(&mut s, &["ucs z "]);
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
}
#[test]
fn ucs_previous_walks_back_ten_steps_per_space() {
let mut s = session();
for i in 1..=12 {
s.execute("ucs", &json!({"option": "origin", "origin": [i, 0]})).unwrap();
}
for i in (2..=11).rev() {
typed(&mut s, &["ucs p"]);
assert!(near3(s.ucs().origin, Vec3::new(f64::from(i), 0.0, 0.0)), "back to {i}: {:?}", s.ucs());
}
let at = s.ucs();
typed(&mut s, &["ucs p"]);
assert!(logged(&s, "There is no previous UCS."));
assert_eq!(s.ucs(), at, "only ten are kept");
assert!(s.execute("ucs", &json!({"option": "previous"})).is_err());
}
#[test]
fn named_ucs_save_restore_list_delete() {
let mut s = session();
turned(&mut s);
typed(&mut s, &["ucs na s SITE"]);
assert_eq!(var(&s, "UCSNAME"), json!("SITE"));
assert_eq!(s.doc().unwrap().ucss.len(), 1);
typed(&mut s, &["ucs w"]);
assert!(s.ucs().is_world());
typed(&mut s, &["ucs na r site"]);
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)) && var(&s, "UCSNAME") == json!("SITE"), "restored by any case");
// Saving over a name asks first.
typed(&mut s, &["ucs z 10", "ucs na s SITE", "n"]);
let saved = s.doc().unwrap().ucss[0].clone();
assert!(near3(saved.x_axis, Vec3::new(0.0, 1.0, 0.0)), "No keeps the saved one");
typed(&mut s, &["ucs na s SITE", "y"]);
assert!(!near3(s.doc().unwrap().ucss[0].x_axis, Vec3::new(0.0, 1.0, 0.0)), "Yes replaces it");
// Listing.
s.execute("ucs", &json!({"option": "named", "action": "save", "name": "Base 2"})).unwrap();
let list = s.execute("ucs", &json!({"option": "named", "action": "list"})).unwrap()["list"].as_str().unwrap().to_string();
assert!(list.contains("SITE") && list.contains("Base 2") && list.contains("Origin = <") && list.contains("Z Axis = <"), "{list}");
typed(&mut s, &["ucs na ? *"]);
assert!(logged(&s, "Saved coordinate systems:"));
// Deleting by wildcard, and the current UCS loses a deleted name.
let r = s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "BASE*"})).unwrap();
assert_eq!(r["deleted"], json!(1));
assert_eq!(var(&s, "UCSNAME"), json!(""), "the current one was Base 2");
typed(&mut s, &["ucs na d SITE"]);
assert!(s.doc().unwrap().ucss.is_empty());
// Unknown and invalid names.
assert!(s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "NOPE"})).is_err());
for bad in ["", " ", "a<b", "x*", "semi;colon", "World", "*WORLD*", &"n".repeat(300)] {
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": bad})).is_err(), "{bad:?}");
}
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": "SITE"})).is_ok());
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": "site"})).is_err(), "names are case-blind");
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": "site", "replace": true})).is_ok());
assert_eq!(s.doc().unwrap().ucss.len(), 1);
}
#[test]
fn ucs_object_follows_each_kind_of_object() {
let mut s = session();
let at = |s: &mut Session, kind: EntityKind, pick: [f64; 2]| -> Result<UcsFrame, String> {
let h = s.add_entity(kind).unwrap();
s.execute("ucs", &json!({"option": "world"})).unwrap();
s.execute("ucs", &json!({"option": "object", "handle": h.hex(), "at": pick})).map_err(|e| e.to_string())?;
Ok(s.ucs())
};
use cadcraft_engine::doc::{Arc, Circle, Face3d, Line, LwPolyline, Point};
// A line: the nearer end; X along the line.
let u = at(&mut s, EntityKind::Line(Line { a: Vec3::new(10.0, 10.0, 0.0), b: Vec3::new(10.0, 30.0, 0.0) }), [10.0, 29.0]).unwrap();
assert!(near3(u.origin, Vec3::new(10.0, 30.0, 0.0)) && near3(u.x, Vec3::new(0.0, -1.0, 0.0)), "{u:?}");
// A circle: the centre; X through the pick.
let u = at(&mut s, EntityKind::Circle(Circle { center: Vec3::new(5.0, 5.0, 2.0), radius: 3.0 }), [5.0, 8.0]).unwrap();
assert!(near3(u.origin, Vec3::new(5.0, 5.0, 2.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}");
// An arc: the centre; X through the nearer end.
let u = at(&mut s, EntityKind::Arc(Arc { center: Vec3::ZERO, radius: 2.0, start: 0.0, end: std::f64::consts::FRAC_PI_2 }), [0.1, 2.0]).unwrap();
assert!(near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}");
// A polyline: its first vertex; X toward the next.
let pl = LwPolyline {
vertices: vec![
cadcraft_engine::geom::PolyVertex::new(Vec2::new(1.0, 1.0)),
cadcraft_engine::geom::PolyVertex::new(Vec2::new(1.0, 1.0)),
cadcraft_engine::geom::PolyVertex::new(Vec2::new(-4.0, 1.0)),
],
closed: false,
const_width: 0.0,
elevation: 3.0,
plinegen: false,
};
let u = at(&mut s, EntityKind::LwPolyline(pl), [0.0, 0.0]).unwrap();
assert!(near3(u.origin, Vec3::new(1.0, 1.0, 3.0)) && near3(u.x, Vec3::new(-1.0, 0.0, 0.0)), "{u:?}");
// Text (and blocks, by the same rule): the insertion point; X along its rotation.
s.execute("ucs", &json!({"option": "world"})).unwrap();
typed(&mut s, &["text 2,3 1 28.64788975654116 A", ""]);
let th = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).map(|e| e.handle).last().unwrap();
s.execute("ucs", &json!({"option": "object", "handle": th.hex()})).unwrap();
let u = s.ucs();
assert!(near3(u.origin, Vec3::new(2.0, 3.0, 0.0)) && ang_eq(u.rotation(), 0.5), "{u:?}");
// A point: there, the X axis kept.
let u = at(&mut s, EntityKind::Point(Point { p: Vec3::new(4.0, 4.0, 0.0), angle: 0.0 }), [0.0, 0.0]).unwrap();
assert!(near3(u.origin, Vec3::new(4.0, 4.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)));
// A flat 3D face works; a tilted one, an ellipse and a zero-length line don't.
let flat = Face3d { corners: [Vec3::ZERO, Vec3::new(0.0, 5.0, 0.0), Vec3::new(-5.0, 5.0, 0.0), Vec3::new(-5.0, 0.0, 0.0)], hidden_edges: 0 };
let u = at(&mut s, EntityKind::Face3d(flat), [0.0, 0.0]).unwrap();
assert!(near3(u.x, Vec3::new(0.0, 1.0, 0.0)) && u.is_planar());
let tilted = Face3d { corners: [Vec3::ZERO, Vec3::new(5.0, 0.0, 0.0), Vec3::new(5.0, 0.0, 5.0), Vec3::new(0.0, 0.0, 5.0)], hidden_edges: 0 };
assert!(at(&mut s, EntityKind::Face3d(tilted), [0.0, 0.0]).unwrap_err().contains("not available yet"));
let ell = cadcraft_engine::doc::Ellipse { center: Vec3::ZERO, major: Vec3::new(2.0, 0.0, 0.0), ratio: 0.5, start: 0.0, end: TAU };
assert!(at(&mut s, EntityKind::Ellipse(ell), [0.0, 0.0]).is_err());
assert!(at(&mut s, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 9.0) }), [0.0, 0.0]).is_err());
assert!(s.ucs().is_world(), "a refused object leaves the UCS");
// Interactively: a pick on the object.
s.execute("line", &json!({"points": [[50, 50], [50, 80]]})).unwrap();
typed(&mut s, &["ucs ob 50,79"]);
assert!(near3(s.ucs().origin, Vec3::new(50.0, 80.0, 0.0)), "{:?}", s.ucs());
let _ = s.cmdline("ucs ob 900,900");
assert!(s.running.is_some() || logged(&s, "No object found"), "a miss asks again");
s.cancel();
}
#[test]
fn ucs_view_and_the_tilted_options() {
let mut s = session();
turned(&mut s);
typed(&mut s, &["ucs v"]);
let u = s.ucs();
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)), "square to the plan view, origin kept");
for k in ["x", "y", "za", "f"] {
s.cmdline(&format!("ucs {k}")).unwrap();
assert!(logged(&s, "not available yet"), "{k}");
assert!(s.running.is_some(), "{k}: still at the prompt");
s.cancel();
assert!(s.execute("ucs", &json!({"option": k})).unwrap_err().to_string().contains("not available yet"), "{k}");
}
}
/// UCS View on a twisted view: X runs along the screen's horizontal, not the world's.
#[test]
fn ucs_view_follows_the_view_twist() {
let mut s = session();
typed(&mut s, &["ucs 100,50 "]);
// The drawing appears turned 90° counterclockwise, so the screen's X is the world's -Y.
s.execute("dview", &json!({"twist": 90.0})).unwrap();
typed(&mut s, &["ucs v"]);
let u = s.ucs();
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)), "origin kept: {u:?}");
assert!(near3(u.x, Vec3::new(0.0, -1.0, 0.0)) && near3(u.y, Vec3::new(1.0, 0.0, 0.0)), "{u:?}");
// The JSON form gives the same frame; with no twist, the World axes.
s.execute("dview", &json!({"twist": 30.0})).unwrap();
s.execute("ucs", &json!({"option": "view"})).unwrap();
let a = -30f64.to_radians();
assert!(near3(s.ucs().x, Vec3::new(a.cos(), a.sin(), 0.0)), "{:?}", s.ucs());
s.execute("dview", &json!({"twist": 0.0})).unwrap();
s.execute("ucs", &json!({"option": "view"})).unwrap();
assert!(near3(s.ucs().x, Vec3::new(1.0, 0.0, 0.0)) && near3(s.ucs().origin, Vec3::new(100.0, 50.0, 0.0)));
}
#[test]
fn a_ucs_change_is_undone_like_an_edit() {
let mut s = session();
typed(&mut s, &["ucs 100,50 "]);
typed(&mut s, &["ucs z 45"]);
s.undo().unwrap();
let u = s.ucs();
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)), "{u:?}");
s.undo().unwrap();
assert!(s.ucs().is_world());
s.redo().unwrap();
assert!(near3(s.ucs().origin, Vec3::new(100.0, 50.0, 0.0)));
}
/// Undo restores UCS Previous's history with the UCS: undoing UCS Previous gives back the entry
/// it used, and undoing a UCS change takes away the entry it added.
#[test]
fn undo_restores_the_ucs_previous_history() {
let previous = |s: &mut Session| s.execute("ucs", &json!({"option": "previous"})).is_ok();
let mut s = session();
typed(&mut s, &["ucs z 30"]);
assert!(previous(&mut s) && s.ucs().is_world());
s.undo().unwrap();
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()), "undo of UCS Previous");
// Redo (before any new command clears the redo stack) does UCS Previous again.
assert!(s.redo().unwrap().is_some(), "UCS Previous is on the redo stack");
assert!(s.ucs().is_world(), "redo of UCS Previous");
s.undo().unwrap();
assert!(previous(&mut s) && s.ucs().is_world(), "its history entry came back too");
let mut s = session();
typed(&mut s, &["ucs z 30", "ucs z 30"]);
assert!(ang_eq(s.ucs().rotation(), 60f64.to_radians()));
s.undo().unwrap();
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
// The 30° the undone step remembered is gone: Previous goes straight to the World UCS.
assert!(previous(&mut s) && s.ucs().is_world());
assert!(!previous(&mut s), "nothing before the World UCS");
}
/// A layout's UCS Previous history goes with the layout: it follows a rename, and a layout
/// deleted and made again under the same name starts without one.
#[test]
fn a_layouts_ucs_history_follows_it_and_goes_with_it() {
let previous = |s: &mut Session| s.execute("ucs", &json!({"option": "previous"})).is_ok();
let set = |s: &mut Session, name: &str| s.execute("layout.set", &json!({"name": name})).unwrap();
let mut s = session();
s.execute("layout", &json!({"option": "new", "name": "A"})).unwrap();
set(&mut s, "A");
typed(&mut s, &["ucs z 30"]);
set(&mut s, "Model");
s.execute("layout", &json!({"option": "rename", "name": "A", "to": "B"})).unwrap();
set(&mut s, "B");
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
assert!(previous(&mut s) && s.ucs().is_world(), "the history followed the rename");
typed(&mut s, &["ucs z 45"]);
set(&mut s, "Model");
s.execute("layout", &json!({"option": "delete", "name": "B"})).unwrap();
s.execute("layout", &json!({"option": "new", "name": "B"})).unwrap();
set(&mut s, "B");
assert!(s.ucs().is_world() && !previous(&mut s), "a new layout B has none of the old B's history");
// Model space's history is its own throughout.
set(&mut s, "Model");
assert!(!previous(&mut s));
}
#[test]
fn paper_space_has_its_own_ucs() {
let mut s = session();
turned(&mut s);
let layout = s.doc().unwrap().layouts[0].name.clone();
s.execute("layout.set", &json!({"name": layout})).unwrap();
assert!(s.ucs().is_world(), "a layout starts in the World UCS");
typed(&mut s, &["ucs z 30"]);
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
assert!(s.doc().unwrap().layouts[0].ucs.is_some());
// UCS Previous stays in its space.
typed(&mut s, &["ucs p"]);
assert!(s.ucs().is_world());
typed(&mut s, &["ucs p"]);
assert!(logged(&s, "There is no previous UCS."), "model space's history isn't paper space's");
s.execute("layout.set", &json!({"name": "Model"})).unwrap();
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)), "model space kept its own");
let (m, _) = cadcraft_engine::ucs::current(s.doc().unwrap(), &Space::Model);
assert!(near3(m.origin, Vec3::new(100.0, 50.0, 0.0)));
}
// ---------------- typed input in the UCS ----------------
#[test]
fn typed_points_are_read_in_the_ucs() {
let mut s = session();
turned(&mut s);
// Absolute: from the UCS origin along its axes.
typed(&mut s, &["line 10,0 20,0 "]);
let (a, b) = last_line(&s);
assert!(near(a, 100.0, 60.0) && near(b, 100.0, 70.0), "{a:?} {b:?}");
// Relative Cartesian along the UCS axes; polar angles from the UCS X axis.
typed(&mut s, &["line 0,0 @5,0 @0,5 @10<90 "]);
let ls = lines(&s);
let n = ls.len();
assert!(near(ls[n - 3].1, 100.0, 55.0) && near(ls[n - 2].1, 95.0, 55.0) && near(ls[n - 1].1, 85.0, 55.0), "{ls:?}");
// Absolute polar: from the UCS origin.
typed(&mut s, &["line 0,0 10<0 "]);
assert!(near(last_line(&s).1, 100.0, 60.0), "{:?}", last_line(&s));
// `#` is absolute in the UCS; `*` and `@*` are world coordinates.
typed(&mut s, &["line #1,2 *1,2 @*3,0 @*5<0 "]);
let ls = lines(&s);
let n = ls.len();
assert!(near(ls[n - 3].0, 98.0, 51.0) && near(ls[n - 3].1, 1.0, 2.0) && near(ls[n - 2].1, 4.0, 2.0) && near(ls[n - 1].1, 9.0, 2.0), "{ls:?}");
// A 3D point keeps working (Z is ignored as before).
typed(&mut s, &["line 1,1,5 2,1,5 "]);
let (a, _) = last_line(&s);
assert!(near(a, 99.0, 51.0), "{a:?}");
}
#[test]
fn the_world_ucs_reads_points_as_before() {
let script = ["line 1,2 @3,4 @5<30 #7,8 *9,10 @*1,1 "];
let mut a = session();
typed(&mut a, &script);
let mut b = session();
typed(&mut b, &["ucs 100,50 ", "ucs z 33", "ucs w"]);
typed(&mut b, &script);
let (la, lb) = (lines(&a), lines(&b));
assert_eq!(la.len(), lb.len());
for (x, y) in la.iter().zip(&lb) {
assert!(x.0.dist(y.0) < 1e-12 && x.1.dist(y.1) < 1e-12, "{x:?} vs {y:?}");
}
}
#[test]
fn directions_are_measured_from_the_ucs_x_axis() {
let mut s = session();
typed(&mut s, &["ucs z 30"]);
// TEXT's rotation 0 lies along the UCS X axis.
typed(&mut s, &["text 0,0 2 0 Hello", ""]);
let rot = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.rotation) } else { None }).unwrap();
assert!(ang_eq(rot, 30f64.to_radians()), "{rot}");
// ANGBASE is measured from the UCS X axis too.
cadcraft_engine::sysvars::set(&mut s, "ANGBASE", &json!(90)).unwrap();
typed(&mut s, &["line 0,0 @10<0 "]);
let (a, b) = last_line(&s);
assert!(ang_eq((b - a).angle(), 120f64.to_radians()), "{:?}", (b - a).angle().to_degrees());
// `<<` overrides ANGBASE but stays in the UCS.
typed(&mut s, &["line 0,0 @10<<0 "]);
let (a, b) = last_line(&s);
assert!(ang_eq((b - a).angle(), 30f64.to_radians()));
cadcraft_engine::sysvars::set(&mut s, "ANGBASE", &json!(0)).unwrap();
// A rotation by an angle is a size, the same in any UCS.
let h = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()["handles"][0].as_str().unwrap().to_string();
typed(&mut s, &["rotate l 0,0 90"]);
let l = s.doc().unwrap().model.iter().find(|e| e.handle.hex() == h).map(|e| e.kind.clone()).unwrap();
let EntityKind::Line(l) = l else { panic!() };
assert!(near(l.b.xy(), 0.0, 10.0), "{:?}", l.b);
// JSON parameters stay in world coordinates.
s.execute("line", &json!({"points": [[0, 0], [3, 0]]})).unwrap();
assert!(near(last_line(&s).1, 3.0, 0.0));
}
#[test]
fn coordinates_are_shown_in_the_ucs() {
let mut s = session();
turned(&mut s);
// ID: the message in the UCS; the JSON result keeps world values beside it.
let r = s.execute("id", &json!({"at": [100, 60]})).unwrap();
assert!(r["message"].as_str().unwrap().starts_with("X = 10.0000 Y = 0.0000"), "{r}");
assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(100.0), Some(60.0)));
assert!((r["ucs"][0].as_f64().unwrap() - 10.0).abs() < 1e-9);
typed(&mut s, &["id 3,4"]);
assert!(logged(&s, "X = 3.0000 Y = 4.0000"), "{:?}", s.log.last());
// DIST: the deltas and the angle in the UCS.
let r = s.execute("dist", &json!({"p1": [100, 50], "p2": [100, 60]})).unwrap();
let m = r["message"].as_str().unwrap();
assert!(m.contains("Angle in XY Plane = 0") && m.contains("Delta X = 10.0000") && m.contains("Delta Y = 0.0000"), "{m}");
// The helpers the status bar and dynamic input use.
assert!(near(s.ucs_point(Vec2::new(100.0, 60.0)), 10.0, 0.0));
assert!(ang_eq(s.ucs_angle(std::f64::consts::FRAC_PI_2), 0.0));
}
// ---------------- variables, UCSICON, tilted UCSs ----------------
#[test]
fn ucs_variables_are_read_only() {
let mut s = session();
for v in ["UCSNAME", "UCSORG", "UCSXDIR", "UCSYDIR", "WORLDUCS"] {
assert!(cadcraft_engine::sysvars::set(&mut s, v, &json!(1)).is_err(), "{v}");
}
typed(&mut s, &["ucs 5,6 ", "ucs na s A"]);
assert_eq!(var(&s, "UCSNAME"), json!("A"));
assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::new(5.0, 6.0, 0.0)));
}
#[test]
fn ucsicon_options() {
let mut s = session();
assert_eq!(s.ucsicon_bits(), 3, "shown, at the origin");
typed(&mut s, &["ucsicon off"]);
assert_eq!(s.ucsicon_bits(), 2);
typed(&mut s, &["ucsicon on", "ucsicon n"]);
assert_eq!(s.ucsicon_bits(), 1);
typed(&mut s, &["ucsicon or"]);
assert_eq!(s.ucsicon_bits(), 3);
s.cmdline("ucsicon s").unwrap();
assert!(logged(&s, "not available yet"));
s.cancel();
let r = s.execute("ucsicon", &json!({"on": false, "origin": false})).unwrap();
assert_eq!(r, json!({"on": false, "origin": false}));
assert_eq!(var(&s, "UCSICON"), json!(0));
assert!(s.execute("ucsicon", &json!({"on": "yes"})).is_err());
assert!(cadcraft_engine::sysvars::set(&mut s, "UCSICON", &json!(9)).is_err());
}
/// Asking UCSICON (or setting what is already set) leaves the drawing unmodified.
#[test]
fn ucsicon_query_does_not_modify_the_drawing() {
let mut s = session();
assert!(!s.state().unwrap().is_dirty());
assert_eq!(s.execute("ucsicon", &json!({})).unwrap(), json!({"on": true, "origin": true}));
s.execute("ucsicon", &json!({"on": true})).unwrap();
assert!(!s.state().unwrap().is_dirty(), "nothing changed");
s.execute("ucsicon", &json!({"on": false})).unwrap();
assert!(s.state().unwrap().is_dirty(), "a real change is unsaved");
}
/// UCS Previous with no earlier UCS changes nothing, so the drawing stays unmodified.
#[test]
fn ucs_previous_without_history_does_not_modify_the_drawing() {
let mut s = session();
assert!(s.execute("ucs", &json!({"option": "previous"})).is_err());
typed(&mut s, &["ucs p"]);
assert!(logged(&s, "There is no previous UCS."));
assert!(!s.state().unwrap().is_dirty());
}
/// UCSICON is its own undo step: undoing it brings the icon back, and an undo never undoes the
/// edit before it while leaving the icon setting behind (or the other way round).
#[test]
fn ucsicon_is_undone_on_its_own() {
let mut s = session();
let lines = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
typed(&mut s, &["ucsicon off"]);
assert_eq!(s.ucsicon_bits() & 1, 0);
s.undo().unwrap();
assert_eq!(s.ucsicon_bits() & 1, 1, "undo takes back UCSICON OFF");
assert_eq!(lines(&s), 1, "and leaves the line drawn before it");
s.undo().unwrap();
assert_eq!(lines(&s), 0);
assert_eq!(s.ucsicon_bits() & 1, 1);
s.redo().unwrap();
s.redo().unwrap();
assert_eq!((lines(&s), s.ucsicon_bits() & 1), (1, 0), "redo brings both back");
}
#[test]
fn a_tilted_ucs_from_a_file_is_kept_and_input_stays_in_the_world_ucs() {
let mut s = session();
{
let h = &mut s.doc_mut().unwrap().header;
h.set("UCSORG", HVal::Point(Vec3::new(10.0, 0.0, 0.0)));
h.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
h.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0)));
}
assert!(!s.ucs().is_planar());
assert_eq!(s.input_ucs(), UcsFrame::WORLD);
typed(&mut s, &["line 1,1 2,2 "]);
assert!(near(last_line(&s).0, 1.0, 1.0), "read in the World UCS");
assert!(logged(&s, "tilted out of the XY plane"));
let n = s.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count();
typed(&mut s, &["line 3,3 4,4 "]);
assert_eq!(s.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count(), n, "told once");
// The UCS itself is untouched until the user sets another.
assert!(near3(vec3(&var(&s, "UCSYDIR")), Vec3::new(0.0, 0.0, 1.0)));
// A tilted named UCS isn't restored.
s.doc_mut().unwrap().ucss.push(cadcraft_engine::doc::Ucs {
name: "FRONT".into(),
origin: Vec3::ZERO,
x_axis: Vec3::new(1.0, 0.0, 0.0),
y_axis: Vec3::new(0.0, 0.0, 1.0),
});
s.execute("ucs", &json!({"option": "world"})).unwrap();
assert!(s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "FRONT"})).unwrap_err().to_string().contains("tilted"));
assert!(s.ucs().is_world());
}
#[test]
fn hostile_ucs_input_never_panics() {
let mut s = session();
let bad: Vec<Value> = vec![
json!({"option": "origin", "origin": [f64::MAX, -f64::MAX, f64::MAX]}),
json!({"option": "origin", "origin": ["a", 1]}),
json!({"option": "origin", "origin": [1]}),
json!({"option": "origin", "origin": [0, 0], "xPoint": [1e308, 1e308], "xyPoint": [-1e308, 1e308]}),
json!({"option": "origin", "origin": [0, 0], "xyPoint": [0, 1]}),
json!({"option": "z", "angle": 1e308}),
json!({"option": "z", "angle": "ninety"}),
json!({"option": "object"}),
json!({"option": "object", "handle": "ZZZZ"}),
json!({"option": "object", "handle": "FFFFFF"}),
json!({"option": "named", "action": "explode", "name": "A"}),
json!({"option": "named", "action": "delete", "name": "*,?,[,]"}),
json!({"option": "warp"}),
json!({"option": 7}),
json!(null),
json!([1, 2, 3]),
];
for p in &bad {
let _ = s.execute("ucs", p);
let u = s.ucs();
assert!(u.origin.is_finite() && u.x.is_finite() && u.y.is_finite(), "{p}: {u:?}");
}
for t in ["ucs 1e400,0", "ucs nan,nan", "ucs 0,0 0,0", "ucs z 1e999", "ucs na s \u{0}", "ucs na r ", "ucs ob", "ucs na ? [", "ucsicon blah"] {
let _ = s.cmdline(t);
s.cancel();
}
// Broken header values read as the World UCS.
for v in [HVal::Point(Vec3::new(f64::NAN, 0.0, 0.0)), HVal::Point(Vec3::ZERO), HVal::Str("x".into()), HVal::Int(3)] {
s.doc_mut().unwrap().header.set("UCSXDIR", v);
let u = s.ucs();
assert!(u.origin.is_finite() && u.x.is_finite());
typed(&mut s, &["line 0,0 1,0 "]);
}
}
// ---------------- review fixes ----------------
/// A deferred TAN first point followed by a typed `@d<a`: the angle is read in the UCS (and with
/// ANGBASE), like every other typed direction.
#[test]
fn deferred_line_polar_follows_the_ucs() {
use cadcraft_engine::Input;
use cadcraft_engine::snap::{Deferred, SnapCurve, mode};
let mut s = session();
turned(&mut s);
s.start("line").unwrap();
let d = Deferred { mode: mode::TAN, curve: SnapCurve::Circle { center: Vec2::new(500.0, 500.0), radius: 5.0 }, at: Vec2::new(505.0, 500.0) };
s.input(Input::Deferred(d)).unwrap();
// UCS angle 0 is world +Y: the tangent to the circle in that direction, then 10 along it.
s.cmdline("@10<0").unwrap();
s.cancel();
let (a, b) = last_line(&s);
assert!((b - a).len() > 9.999 && (b.x - a.x).abs() < 1e-9 && (b.y - a.y - 10.0).abs() < 1e-9, "{a:?} {b:?}");
}
/// Deleting a named UCS clears its name wherever it is the current UCS: model space and every
/// layout, not only the space deleted from.
#[test]
fn deleting_a_named_ucs_clears_it_in_every_space() {
let mut s = session();
turned(&mut s);
s.execute("ucs", &json!({"option": "named", "action": "save", "name": "SITE"})).unwrap();
let layout = s.doc().unwrap().layouts[0].name.clone();
s.execute("layout.set", &json!({"name": layout})).unwrap();
s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "SITE"})).unwrap();
assert_eq!(s.ucs_named().1, "SITE");
// Delete from paper space: model space is still named SITE.
s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "SITE"})).unwrap();
assert_eq!(s.ucs_named().1, "", "the current space");
assert_eq!(s.doc().unwrap().header.str("UCSNAME", ""), "", "model space");
assert!(s.doc().unwrap().layouts.iter().all(|l| l.ucs.as_ref().is_none_or(|u| u.name.is_empty())), "every layout");
// The axes stay.
s.execute("layout.set", &json!({"name": "Model"})).unwrap();
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)));
}
/// The origin prompt offers the origin in the UCS's own terms (0,0,0), so Enter, or the default
/// typed back, keeps the origin.
#[test]
fn pressing_enter_at_the_origin_prompt_keeps_the_origin() {
let mut s = session();
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
s.execute("ucs", &json!({"option": "z", "angle": 30})).unwrap();
let before = s.ucs();
s.start("ucs.origin").unwrap();
let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default();
s.cmdline(&shown).unwrap();
assert!(near3(s.ucs().origin, before.origin), "typing the default {shown:?} back: {:?}", s.ucs().origin);
s.start("ucs.origin").unwrap();
s.cmdline("").unwrap();
assert!(near3(s.ucs().origin, before.origin));
}
/// DIST's JSON keeps world values at the top level, as ID does, and has the numbers its message
/// shows (angle and deltas in the current UCS) under `ucs`.
#[test]
fn dist_json_keeps_world_values_and_adds_ucs() {
let mut s = session();
turned(&mut s);
// Points are given in the world: UCS (0,0) and (10,0).
let r = s.execute("dist", &json!({"p1": [100, 50], "p2": [100, 60]})).unwrap();
let f = |v: &Value, k: &str| v[k].as_f64().unwrap();
assert!(f(&r, "dx").abs() < 1e-9 && (f(&r, "dy") - 10.0).abs() < 1e-9 && (f(&r, "angle") - 90.0).abs() < 1e-9, "{r}");
let u = &r["ucs"];
assert!((f(u, "dx") - 10.0).abs() < 1e-9 && f(u, "dy").abs() < 1e-9 && f(u, "angle").abs() < 1e-9, "{r}");
assert!(r["message"].as_str().unwrap().contains("Delta X = 10"), "{r}");
assert!(r.get("world").is_none(), "{r}");
}
/// Deleting the current named UCS leaves no trace of its name: UCS Previous goes back to the axes
/// before it, unnamed, and does not bring the deleted name back.
#[test]
fn ucs_previous_after_deleting_the_current_named_ucs() {
let mut s = session();
typed(&mut s, &["ucs na s SITE"]);
turned(&mut s);
typed(&mut s, &["ucs na r SITE"]);
typed(&mut s, &["ucs na d SITE"]);
assert_eq!(s.ucs_named().1, "");
assert!(s.doc().unwrap().ucs_previous.iter().all(|u| u.name.is_empty()), "{:?}", s.doc().unwrap().ucs_previous);
typed(&mut s, &["ucs p"]);
assert_eq!(s.ucs_named().1, "", "the deleted name does not come back");
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)), "back to the axes before SITE: {:?}", s.ucs());
assert_eq!(s.doc().unwrap().header.str("UCSNAME", ""), "");
}
/// Enter at the 3 Point origin prompt keeps the origin and asks for the X axis point.
#[test]
fn three_point_ucs_enter_keeps_the_origin() {
let mut s = session();
turned(&mut s);
let before = s.ucs();
s.start("ucs.3point").unwrap();
s.cmdline("").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message.contains("X-axis")), "{:?}", s.current_prompt().map(|p| p.message));
// A point 10 along the UCS X axis, then Enter for the XY point: the origin is kept.
s.cmdline("10,0").unwrap();
s.cmdline("").unwrap();
assert!(near3(s.ucs().origin, before.origin) && near3(s.ucs().x, before.x), "{:?}", s.ucs());
}
/// With the current UCS tilted, points are read in the World UCS: the origin prompt shows the
/// origin there, so Enter, or the default typed back, keeps it.
#[test]
fn tilted_ucs_origin_default_keeps_the_origin() {
let mut s = session();
{
let h = &mut s.doc_mut().unwrap().header;
h.set("UCSORG", HVal::Point(Vec3::new(50.0, 20.0, 7.0)));
h.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
h.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0)));
}
let before = s.ucs().origin;
s.start("ucs.origin").unwrap();
let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default();
assert_eq!(shown, "50,20,7");
s.cmdline(&shown).unwrap();
assert!(near3(s.ucs().origin, before), "typed {shown:?}: {:?}", s.ucs().origin);
s.start("ucs.origin").unwrap();
s.cmdline("").unwrap();
assert!(near3(s.ucs().origin, before));
}
/// The origin prompt's default is a clean number: no negative zero, no 16-digit noise.
#[test]
fn origin_default_prints_no_negative_zero() {
let mut s = session();
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
s.execute("ucs", &json!({"option": "z", "angle": 200})).unwrap();
s.start("ucs.origin").unwrap();
let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default();
assert_eq!(shown, "0,0,0");
}
/// Deleting the named World UCS of a layout leaves the layout with no UCS, as setting the World
/// UCS does.
#[test]
fn deleting_a_named_world_ucs_in_a_layout_leaves_no_ucs() {
let mut s = session();
let layout = s.doc().unwrap().layouts[0].name.clone();
s.execute("layout.set", &json!({"name": layout})).unwrap();
s.execute("ucs", &json!({"option": "named", "action": "save", "name": "HOME"})).unwrap();
s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "HOME"})).unwrap();
assert_eq!(s.ucs_named().1, "HOME");
s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "HOME"})).unwrap();
assert!(s.doc().unwrap().layouts.iter().all(|l| l.ucs.is_none()), "{:?}", s.doc().unwrap().layouts.iter().map(|l| &l.ucs).collect::<Vec<_>>());
}
-239
View File
@@ -1,239 +0,0 @@
//! The drafting aids follow the current UCS (#1106): ortho and direct distance entry along its
//! axes, grid snap in its XY plane (SNAPBASE from its origin, SNAPANG from its X axis), polar and
//! object snap tracking measured from its X axis, isometric axes turned with it, and DIMLINEAR's
//! horizontal and vertical along its axes. In the World UCS everything is as before.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{DimKind, EntityKind};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::snap::tracking::{CursorQuery, TrackConfig};
use cadcraft_engine::snap::{self, iso};
use serde_json::json;
const DEG: f64 = std::f64::consts::PI / 180.0;
fn session() -> Session {
let mut s = Session::new();
s.new_drawing(false);
// Nothing running that would snap the cursor elsewhere.
s.settings.osmode = 0;
s.settings.otrack = false;
s.settings.polarmode = false;
s.settings.orthomode = false;
s.settings.snapmode = false;
s
}
/// The UCS at (5, 5) turned `deg` degrees.
fn turned(s: &mut Session, deg: f64) {
s.execute("ucs", &json!({"option": "origin", "origin": [5, 5]})).unwrap();
s.execute("ucs", &json!({"option": "z", "angle": deg})).unwrap();
}
fn query(base: Option<Vec2>) -> CursorQuery {
CursorQuery { base, deferred: false, corner: false, aperture: 0.01, tol: 1.0, now: 0.0, shift: false }
}
fn near(a: Vec2, x: f64, y: f64) -> bool {
a.dist(Vec2::new(x, y)) < 1e-9
}
fn ang_eq(a: f64, b: f64) -> bool {
let d = (a - b).rem_euclid(std::f64::consts::TAU);
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
}
#[test]
fn ortho_follows_the_ucs_axes() {
let mut s = session();
s.settings.orthomode = true;
// World UCS: horizontal.
let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point;
assert!(near(p, 10.0, 0.0), "{p:?}");
// Turned 30°: along the UCS X axis, as far as the cursor reaches along it.
turned(&mut s, 30.0);
let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point;
let along = 10.0 * (30.0 * DEG).cos() + 4.0 * (30.0 * DEG).sin();
assert!(near(p, along * (30.0 * DEG).cos(), along * (30.0 * DEG).sin()), "{p:?}");
// And along its Y axis when the cursor is nearer that.
let p = s.snap_cursor(Vec2::new(-4.0, 9.0), &query(Some(Vec2::ZERO))).point;
let d = p - Vec2::ZERO;
assert!(ang_eq(d.angle(), 120.0 * DEG) || ang_eq(d.angle(), 300.0 * DEG), "{:?}", d.angle() / DEG);
}
/// Holding Shift turns ortho on (or off) while it is held, along the current UCS's axes too.
#[test]
fn shift_ortho_follows_the_ucs_axes() {
let mut s = session();
s.settings.orthomode = false;
turned(&mut s, 30.0);
let shifted = CursorQuery { shift: true, ..query(Some(Vec2::ZERO)) };
let p = s.snap_cursor(Vec2::new(10.0, 4.0), &shifted).point;
let along = 10.0 * (30.0 * DEG).cos() + 4.0 * (30.0 * DEG).sin();
assert!(near(p, along * (30.0 * DEG).cos(), along * (30.0 * DEG).sin()), "Shift: ortho on, along the UCS X axis: {p:?}");
// Without Shift the cursor goes where it is; with ORTHOMODE on, Shift turns it off.
assert!(near(s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point, 10.0, 4.0));
s.settings.orthomode = true;
assert!(near(s.snap_cursor(Vec2::new(10.0, 4.0), &shifted).point, 10.0, 4.0), "Shift: ortho off");
assert!(s.settings.orthomode, "ORTHOMODE itself is unchanged");
}
#[test]
fn direct_distance_with_ortho_goes_along_the_ucs_axis() {
let mut s = session();
turned(&mut s, 30.0);
s.settings.orthomode = true;
s.cmdline("line 0,0").unwrap();
// The cursor a little off the UCS X axis: 10 along it.
s.cursor = s.input_ucs().to_wcs(Vec2::new(8.0, 1.0));
s.cmdline("10").unwrap();
s.cmdline("").unwrap();
let l = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
let u = s.input_ucs();
assert!(l.a.xy().dist(u.to_wcs(Vec2::ZERO)) < 1e-9 && l.b.xy().dist(u.to_wcs(Vec2::new(10.0, 0.0))) < 1e-9, "{l:?}");
}
#[test]
fn grid_snap_lies_in_the_ucs() {
let mut s = session();
cadcraft_engine::sysvars::set(&mut s, "SNAPUNIT", &json!([1, 1])).unwrap();
s.settings.snapmode = true;
let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point;
assert!(near(p, 5.0, 7.0), "World: {p:?}");
// Turned 90° at (5, 5): the lattice through (5, 5) along the turned axes; with SNAPBASE and
// SNAPANG measured in the UCS.
turned(&mut s, 90.0);
let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point;
assert!(near(p, 5.0, 7.0), "{p:?}");
s.execute("ucs", &json!({"option": "z", "angle": -45})).unwrap();
let u = s.input_ucs();
let p = s.snap_cursor(u.to_wcs(Vec2::new(2.2, -0.9)), &query(None)).point;
assert!(u.to_ucs(p).dist(Vec2::new(2.0, -1.0)) < 1e-9, "UCS {:?}", u.to_ucs(p));
let d = s.doc().unwrap();
let (o, a) = snap::grid_frame_in(d, &s.space());
assert!(near(o, 5.0, 5.0) && ang_eq(a, 45.0 * DEG), "{o:?} {}", a / DEG);
// SNAPBASE is a UCS point, SNAPANG an angle from its X axis.
cadcraft_engine::sysvars::set(&mut s, "SNAPBASE", &json!([1, 0])).unwrap_or(());
s.doc_mut().unwrap().header.set("SNAPBASE", cadcraft_engine::doc::HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
s.doc_mut().unwrap().header.set_f64("SNAPANG", 10.0);
let (o, a) = snap::grid_frame_in(s.doc().unwrap(), &s.space());
assert!(o.dist(u.to_wcs(Vec2::new(1.0, 0.0))) < 1e-9 && ang_eq(a, 55.0 * DEG), "{o:?} {}", a / DEG);
// The stored values are unchanged (they are UCS values).
assert_eq!(snap::grid_frame(s.doc().unwrap()), (Vec2::new(1.0, 0.0), 10.0 * DEG));
}
#[test]
fn polar_tracking_is_measured_from_the_ucs_x_axis() {
let mut s = session();
s.settings.polarmode = true;
s.settings.polarang = 90.0 * DEG;
let base = Vec2::ZERO;
let at32 = Vec2::from_angle(32.0 * DEG) * 10.0;
// World UCS, 90° steps: 32° is on no path.
assert!(s.snap_cursor(at32, &query(Some(base))).track.is_none());
// Turned 30°: the path at 30° catches it.
turned(&mut s, 30.0);
let snapped = s.snap_cursor(at32, &query(Some(base)));
let t = snapped.track.expect("on the 30° path");
let d = t.point - base;
assert!(ang_eq(d.angle(), 30.0 * DEG), "{}", d.angle() / DEG);
// The configuration itself: polar angles and the orthogonal tracking paths turn with the UCS.
let st = s.drafting_settings();
let cfg = TrackConfig::new(&st, 0.0);
for want in [30.0, 120.0, 210.0, 300.0] {
assert!(
cfg.polar_angles.iter().any(|a| ang_eq(*a, want * DEG)),
"{want}: {:?}",
cfg.polar_angles.iter().map(|a| a / DEG).collect::<Vec<_>>()
);
assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG)), "{want}");
}
// ANGBASE adds to it.
let cfg = TrackConfig::new(&st, 15.0 * DEG);
assert!(cfg.polar_angles.iter().any(|a| ang_eq(*a, 45.0 * DEG)));
}
#[test]
fn the_world_ucs_drafts_as_before() {
let s = session();
let st = s.drafting_settings();
assert_eq!(st.ucs_angle, 0.0);
for (b, p) in [(Vec2::ZERO, Vec2::new(10.0, 4.0)), (Vec2::new(3.0, 3.0), Vec2::new(1.0, 20.0)), (Vec2::ZERO, Vec2::new(-5.0, 5.0))] {
assert_eq!(snap::ortho_at(b, p, 0.0), snap::ortho(b, p));
assert_eq!(iso::constrain(&st, b, p), snap::ortho(b, p));
}
let cfg = TrackConfig::new(&st, 0.0);
for want in [0.0, 90.0, 180.0, 270.0] {
assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG)));
}
assert_eq!(snap::grid_frame_in(s.doc().unwrap(), &s.space()), snap::grid_frame(s.doc().unwrap()));
// Hostile angles fall back to the world axes.
assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::NAN), Vec2::new(3.0, 0.0));
assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::INFINITY), Vec2::new(3.0, 0.0));
}
#[test]
fn isometric_axes_turn_with_the_ucs() {
let mut s = session();
s.settings.isodraft = true;
let st0 = s.drafting_settings();
turned(&mut s, 40.0);
let st = s.drafting_settings();
for v in [Vec2::new(10.0, 3.0), Vec2::new(-2.0, 9.0), Vec2::new(4.0, -7.0)] {
let base = Vec2::new(1.0, 2.0);
let r = iso::constrain(&st, base, base + v.rotate(40.0 * DEG)) - base;
let want = iso::constrain(&st0, Vec2::ZERO, v).rotate(40.0 * DEG);
assert!(r.dist(want) < 1e-9, "{v:?}: {r:?} vs {want:?}");
}
}
fn last_dim_rotation(s: &Session) -> f64 {
let d = s.doc().unwrap();
let r = d.model.iter().filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm.kind) } else { None }).last();
match r {
Some(DimKind::Linear { rotation }) => rotation,
other => panic!("not a linear dimension: {other:?}"),
}
}
#[test]
fn dimlinear_horizontal_and_vertical_follow_the_ucs() {
let mut s = session();
turned(&mut s, 30.0);
// Placed above the points (in the UCS): horizontal along the UCS X axis.
s.cmdline("dimlinear 0,0 10,0 5,5").unwrap();
assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG), "{}", last_dim_rotation(&s) / DEG);
// Beside them: vertical along its Y axis.
s.cmdline("dimlinear 0,0 0,10 5,5").unwrap();
assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG), "{}", last_dim_rotation(&s) / DEG);
// The keywords.
s.cmdline("dimlinear 0,0 10,10 h 5,20").unwrap();
assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG));
s.cmdline("dimlinear 0,0 10,10 v 20,5").unwrap();
assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG));
// JSON stays in world coordinates: horizontal is world horizontal.
s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 5]})).unwrap();
assert!(ang_eq(last_dim_rotation(&s), 0.0));
// World UCS: as before.
s.execute("ucs", &json!({"option": "world"})).unwrap();
s.cmdline("dimlinear 0,0 10,0 5,5").unwrap();
assert!(ang_eq(last_dim_rotation(&s), 0.0));
s.cmdline("dimlinear 0,0 0,10 5,5").unwrap();
assert!(ang_eq(last_dim_rotation(&s), 90.0 * DEG));
}
/// A point filter takes its coordinates in the UCS: `.X` of one point and `YZ` of another make
/// the point with the first's UCS X and the second's UCS Y.
#[test]
fn point_filters_and_ortho_follow_the_ucs() {
let mut s = session();
turned(&mut s, 90.0);
s.cmdline("line 0,0").unwrap();
s.cmdline(".x").unwrap();
s.cmdline("3,4").unwrap();
s.cmdline("7,9").unwrap();
s.cmdline("").unwrap();
let l = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
// UCS (3, 9): the UCS at (5, 5) turned 90° puts it at world (5 - 9, 5 + 3).
assert!(near(l.b.xy(), -4.0, 8.0), "{l:?}");
}
-34
View File
@@ -35,40 +35,6 @@ pub(crate) const PLOT_STYLE_NAMES_KEY: &str = "ACAD_PLOTSTYLENAME";
pub(crate) const HANDSEED_KEY: &str = "CADCRAFT_HANDSEED";
/// Named-object-dictionary key of the XRECORD holding the current multileader style.
pub(crate) const MLEADER_STYLE_KEY: &str = "CADCRAFT_MLEADERSTYLE";
/// Named-object-dictionary key of the XRECORD holding model space's current UCS name ($UCSNAME,
/// which the DWG bridge drops).
pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME";
/// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding):
/// only then is the current UCS still that named one, read or written. The origin may differ by
/// printing round-off only: we write the shortest exact form and other programs 15–16
/// significant digits (half a unit in the 15th is 5e-16 of the value), so 1e-14 of the value,
/// plus 1e-9 near the World origin, covers it while even 1e12 away a 0.5 move is a different UCS.
pub(crate) fn is_named_frame(u: &cadcraft_doc::Ucs, origin: cadcraft_geom::Vec3, x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool {
(origin - u.origin).len() <= 1e-9 + 1e-14 * origin.len() && (x - u.x_axis).len() <= 1e-9 && (y - u.y_axis).len() <= 1e-9
}
/// The UCS table record named `name` whose frame the UCS at `origin`, `x`, `y` still is: the only
/// case in which a current UCS (model space's or a layout's, read or written) keeps that name.
pub(crate) fn named_ucs<'a>(
ucss: &'a [cadcraft_doc::Ucs],
name: &str,
origin: cadcraft_geom::Vec3,
x: cadcraft_geom::Vec3,
y: cadcraft_geom::Vec3,
) -> Option<&'a cadcraft_doc::Ucs> {
let name = name.trim();
if name.is_empty() {
return None;
}
ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name) && is_named_frame(u, origin, x, y))
}
/// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative
/// to their lengths, so short but square axes are fine). Read and written by the same rule.
pub(crate) fn usable_axes(x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool {
x.is_finite() && y.is_finite() && x.len() > 1e-12 && y.len() > 1e-12 && x.cross(y).len() > 1e-9 * x.len() * y.len()
}
/// Most plot style tables and plot style names read from a file.
pub(crate) const MAX_PLOT_STYLE_TABLES: usize = 1000;
pub(crate) const MAX_PLOT_STYLE_NAMES: usize = 100_000;
+294
View File
@@ -0,0 +1,294 @@
//! Saved layer states as AutoCAD keeps them: the LAYER table's extension dictionary holds an
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. Measured in AutoCAD 2024 (DXFOUT of
//! states saved with -LAYER stAte), an XRECORD holds `280 1`, the mask (91), a text (301: empty
//! as -LAYER saves it; AutoCAD keeps one a file holds through restore and DXFOUT), `290 0` and
//! the current layer's name (302), then for each layer its LAYER handle (330),
//! flags (90: 1 off, 2 frozen, 4 locked, 8 plotted, 16 frozen in new viewports), colour index
//! (62), lineweight (370), for a layer of an xref 93 (0 for a newly attached one; a file can hold
//! 1, whose meaning isn't measured), LTYPE handle (331), plot style (in a drawing of colour-dependent
//! plot styles the name `Color_N` in group 1, N its colour index; of named ones the handle of its
//! placeholder object in group 390), transparency (440: 0 opaque, else `0x02000000 | alpha`) and,
//! for a true colour, 92 (`0xC2RRGGBB`).
//!
//! States AutoCAD's dictionary can't hold stay in CADCraft's own record (`CADCRAFT_LAYERSTATES`):
//! the view layer snapshots (`*VIEW name`), and a name that repeats an earlier one in another
//! case: AutoCAD 2024 opens the entries `S` and `s` of one dictionary as one state, named as the
//! first entry and holding the last one's record (measured), and so does the reader here.
use std::collections::{HashMap, HashSet};
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Layer, LayerState, Lineweight};
use craft_dxf::Tag;
use crate::dxf_ext::{transparency_from_dxf, transparency_to_dxf};
/// The key of the states dictionary in the LAYER table's extension dictionary.
pub(crate) const KEY: &str = "ACAD_LAYERSTATES";
/// The prefix of a true colour in group 92.
const TRUE_COLOR: u32 = 0xC200_0000;
/// The bytes of layers the states of one file may copy (CWE-400). Each entry of a state is a copy
/// of the drawing's layer, its names and description included, so without a bound a small file
/// naming one layer with a long description in a great many entries would take gigabytes.
pub(crate) const MAX_COPIED_BYTES: usize = 256 << 20;
/// Which of `states` go into AutoCAD's dictionary (the others into CADCraft's record).
pub(crate) fn in_acad(states: &[LayerState]) -> Vec<bool> {
let mut seen: HashSet<String> = HashSet::with_capacity(states.len());
states.iter().map(|st| !st.name.trim().is_empty() && !st.name.starts_with('*') && seen.insert(st.name.to_lowercase())).collect()
}
/// The states CADCraft's own record keeps (those [`in_acad`] leaves out).
pub(crate) fn own(states: &[LayerState]) -> Vec<LayerState> {
states.iter().zip(in_acad(states)).filter(|(_, acad)| !acad).map(|(st, _)| st.clone()).collect()
}
/// Handles of the objects that hold the drawing's states in AutoCAD's form.
#[derive(Default)]
pub(crate) struct Plan {
/// The LAYER table, which owns the extension dictionary.
pub table: String,
/// The LAYER table's extension dictionary.
pub xdict: String,
/// The `ACAD_LAYERSTATES` dictionary.
dict: String,
/// (index in the drawing's states, XRECORD handle).
records: Vec<(usize, String)>,
}
impl Plan {
pub fn new(states: &[LayerState], mut handle: impl FnMut() -> String) -> Self {
let acad = in_acad(states);
if !acad.contains(&true) {
return Plan::default();
}
let xdict = handle();
let dict = handle();
let records = acad.iter().enumerate().filter(|(_, a)| **a).map(|(i, _)| (i, handle())).collect();
Plan { table: String::new(), xdict, dict, records }
}
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
}
/// What the state objects need from the rest of the file.
pub(crate) struct Refs<'a> {
/// Upper-case layer name → LAYER record handle.
pub layers: &'a HashMap<String, String>,
/// Upper-case linetype name → LTYPE record handle.
pub ltypes: &'a HashMap<String, String>,
/// Upper-case plot style name → its placeholder object's handle.
pub pstyles: &'a HashMap<String, String>,
/// Plot styles by colour (`$PSTYLEMODE` 1): the plot style name is `Color_N`.
pub colour_dependent: bool,
}
/// The objects of plan `p`: the extension dictionary, the `ACAD_LAYERSTATES` dictionary and one
/// XRECORD per state. Layers the drawing no longer has are left out of a state (AutoCAD names
/// layers by handle).
pub(crate) fn objects(p: &Plan, states: &[LayerState], refs: &Refs) -> Vec<Tag> {
let mut t = Vec::new();
if p.is_empty() {
return t;
}
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.xdict), Tag::s(330, &p.table), Tag::s(100, "AcDbDictionary"), Tag::i(280, 1), Tag::i(281, 1)]);
t.extend([Tag::s(3, KEY), Tag::s(360, &p.dict)]);
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.dict), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.xdict), Tag::s(102, "}")]);
t.extend([Tag::s(330, &p.xdict), Tag::s(100, "AcDbDictionary"), Tag::i(281, 1)]);
let planned = || p.records.iter().filter_map(|(i, h)| Some((states.get(*i)?, h)));
for (st, h) in planned() {
t.extend([Tag::s(3, &st.name), Tag::s(350, h)]);
}
for (st, h) in planned() {
t.extend([Tag::s(0, "XRECORD"), Tag::s(5, h), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.dict), Tag::s(102, "}"), Tag::s(330, &p.dict)]);
t.extend([Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, i64::from(st.mask)), Tag::s(301, &st.description), Tag::i(290, 0)]);
t.push(Tag::s(302, &st.current));
for l in &st.layers {
if let Some(lh) = refs.layers.get(&l.name.to_ascii_uppercase()) {
layer(&mut t, l, lh, refs);
}
}
}
t
}
/// One layer of a state's XRECORD.
fn layer(t: &mut Vec<Tag>, l: &Layer, handle: &str, refs: &Refs) {
let flags = i64::from(!l.on) | i64::from(l.frozen) << 1 | i64::from(l.locked) << 2 | i64::from(l.plot) << 3 | i64::from(l.vp_freeze_new) << 4;
let aci = match l.color {
Color::True(rgb) => i64::from(cadcraft_color::nearest_aci(rgb)),
c => i64::from(c.to_aci()).clamp(1, 255),
};
t.extend([Tag::s(330, handle), Tag::i(90, flags), Tag::i(62, aci), Tag::i(370, i64::from(l.lineweight.to_dxf()))]);
if crate::dxf_xref::dependent(&l.name) {
t.push(Tag::i(93, 0));
}
// A linetype the drawing no longer has: Continuous, which every drawing has.
if let Some(lt) = refs.ltypes.get(&l.linetype.to_ascii_uppercase()).or_else(|| refs.ltypes.get("CONTINUOUS")) {
t.push(Tag::s(331, lt));
}
if refs.colour_dependent {
t.push(Tag::s(1, format!("Color_{aci}")));
} else if let Some(ps) = refs.pstyles.get(&l.plot_style.trim().to_ascii_uppercase()).or_else(|| refs.pstyles.get("NORMAL")) {
t.push(Tag::s(390, ps));
}
t.push(Tag::i(440, if l.transparency == 0 { 0 } else { transparency_to_dxf(l.transparency) }));
if let Color::True(rgb) = l.color {
t.push(Tag::i(92, i64::from(i32::from_be_bytes((TRUE_COLOR | rgb.to_u32()).to_be_bytes()))));
}
}
/// What a state's handles name in the drawing being read.
pub(crate) struct Lookup<'a> {
/// The drawing's layer a LAYER handle names: a state's layer starts as a copy of it (what the
/// state doesn't hold, such as the description, is the drawing's).
pub layer: &'a dyn Fn(&str) -> Option<Layer>,
/// The linetype an LTYPE handle names.
pub ltype: &'a dyn Fn(&str) -> Option<String>,
/// The plot style a placeholder handle names.
pub pstyle: &'a dyn Fn(&str) -> Option<String>,
/// Plot styles by colour: group 1 (`Color_N`) says nothing the layer's colour doesn't.
pub colour_dependent: bool,
}
/// The state `name` from its XRECORD's groups. A layer whose record is gone (AutoCAD keeps a
/// purged layer's entry, measured) is skipped. A layer named in two entries is in the state once,
/// the later entry's groups over the earlier one's, as restoring both in turn did: AutoCAD 2024
/// restores the later one (measured with entries that each set every property). Each copy of a
/// layer is charged to `budget`, the file's [`MAX_COPIED_BYTES`]; once it is spent, the entries
/// left are left out.
pub(crate) fn read(name: &str, tags: &[Tag], lookup: &Lookup, budget: &mut usize) -> LayerState {
let mut st = LayerState { name: name.to_string(), ..LayerState::default() };
// The data follows the subclass marker (an XRECORD without one holds none).
let start = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbXrecord").map_or(tags.len(), |i| i + 1);
let body = tags.get(start..).unwrap_or_default();
let first = body.iter().position(|t| t.code == 330).unwrap_or(body.len());
for t in body.get(..first).unwrap_or_default() {
match t.code {
91 => st.mask = t.str().trim().parse::<u32>().unwrap_or(LayerState::ALL),
301 => st.description = t.str(),
302 => st.current = t.str(),
_ => {}
}
}
let rest = body.get(first..).unwrap_or_default();
// The index in the state of each layer by its LAYER handle.
let mut index: HashMap<String, usize> = HashMap::new();
let mut at = 0;
while let Some(group) = rest.get(at..) {
let Some(head) = group.first() else { break };
let len = group.iter().skip(1).position(|t| t.code == 330).map_or(group.len(), |n| n + 1);
at += len;
let groups = group.get(1..len).unwrap_or_default();
let key = head.str().trim().to_ascii_uppercase();
if let Some(slot) = index.get(&key).and_then(|&i| st.layers.get_mut(i)) {
entry(slot, groups, lookup);
} else if let Some(mut l) = (lookup.layer)(&head.str()) {
let Some(left) = budget.checked_sub(cost(&l)) else { break };
*budget = left;
entry(&mut l, groups, lookup);
index.insert(key, st.layers.len());
st.layers.push(l);
}
}
st
}
/// The bytes a copy of layer `l` takes.
fn cost(l: &Layer) -> usize {
std::mem::size_of::<Layer>() + l.name.len() + l.linetype.len() + l.description.len() + l.plot_style.len()
}
/// A layer's properties from the groups after its handle.
fn entry(l: &mut Layer, groups: &[Tag], lookup: &Lookup) {
let int = |t: &Tag| t.str().trim().parse::<i64>().ok();
let mut true_color = None;
for t in groups {
match t.code {
90 => {
if let Some(f) = int(t) {
(l.on, l.frozen, l.locked, l.plot, l.vp_freeze_new) = (f & 1 == 0, f & 2 != 0, f & 4 != 0, f & 8 != 0, f & 16 != 0);
}
}
62 => {
if let Some(c) = int(t).map(i64::abs).and_then(|c| u8::try_from(c).ok()).filter(|c| *c >= 1) {
l.color = Color::Index(c);
}
}
92 => true_color = int(t).and_then(|v| u32::try_from(v & 0xFFFF_FFFF).ok()).filter(|v| v & 0xFF00_0000 == TRUE_COLOR),
370 => {
if let Some(w) = int(t).and_then(|w| i16::try_from(w).ok()) {
l.lineweight = Lineweight::from_dxf(w);
}
}
331 => {
if let Some(lt) = (lookup.ltype)(&t.str()) {
l.linetype = lt;
}
}
390 => {
if let Some(ps) = (lookup.pstyle)(&t.str()) {
l.plot_style = ps;
}
}
1 if !lookup.colour_dependent => l.plot_style = t.str(),
440 => {
if let Some(v) = int(t) {
l.transparency = transparency_from_dxf(v).unwrap_or(0);
}
}
_ => {}
}
}
if let Some(v) = true_color {
l.color = Color::True(Rgb::from_u32(v & 0x00FF_FFFF));
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A state's XRECORD groups with an entry per (layer handle, colour index).
fn tags(entries: &[(&str, i64)]) -> Vec<Tag> {
let mut t = vec![Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, 2047), Tag::s(302, "0")];
for (h, aci) in entries {
t.extend([Tag::s(330, *h), Tag::i(90, 8)]);
// 0: no colour group.
if *aci != 0 {
t.push(Tag::i(62, *aci));
}
}
t
}
#[test]
fn a_layer_named_twice_takes_its_last_entry_and_copies_stop_at_the_budget() {
let layer = |h: &str| match h {
"A1" => Some(Layer::new("A")),
"B1" => Some(Layer::new("B")),
_ => None,
};
let none = |_: &str| None::<String>;
let lookup = Lookup { layer: &layer, ltype: &none, pstyle: &none, colour_dependent: true };
let colours = |st: &LayerState| st.layers.iter().map(|l| (l.name.clone(), l.color)).collect::<Vec<_>>();
// AutoCAD 2024 restores the last of two entries of one layer (measured: green, then blue,
// restores blue); it stays in the first one's place. A later entry without a colour keeps
// the earlier one's, as restoring both in turn did.
let mut budget = MAX_COPIED_BYTES;
let st = read("S", &tags(&[("A1", 3), ("B1", 2), ("A1", 5), ("B1", 0)]), &lookup, &mut budget);
assert_eq!(colours(&st), [("A".to_string(), Color::Index(5)), ("B".to_string(), Color::Index(2))]);
// Each new copy is charged (a repeated entry copies nothing); past the budget the rest of
// the entries, and of the file's states, are left out.
let one = cost(&Layer::new("A"));
let mut budget = one;
let st = read("S", &tags(&[("A1", 3), ("A1", 4), ("B1", 5)]), &lookup, &mut budget);
assert_eq!((colours(&st), budget), (vec![("A".to_string(), Color::Index(4))], 0));
let st = read("T", &tags(&[("B1", 2)]), &lookup, &mut budget);
assert!(st.layers.is_empty());
}
}
+77 -21
View File
@@ -36,10 +36,11 @@ const MODELLED_KEYS: &[&str] = &[
"ACAD_IMAGE_VARS",
];
/// Extension dictionary entries not kept raw: dimension associativity (CADCraft reads and
/// rewrites it), draw order and annotation scale contexts (written from their own models by the
/// changes that model them; stale copies would contradict the drawing).
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
/// Extension dictionary entries not kept raw: dimension associativity and the LAYER table's layer
/// states (CADCraft reads and rewrites them), draw order and annotation scale contexts (written
/// from their own models by the changes that model them; stale copies would contradict the
/// drawing).
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_LAYERSTATES", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
/// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides
/// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept.
@@ -989,20 +990,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s);
let root_keys: HashSet<String> =
objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default();
// Extension dictionaries that go on a written record (one without its own).
let mut block = String::new();
let mut attached: HashSet<String> = HashSet::new();
for r in &recs {
if r.kind == "BLOCK" {
block = up(&val(body(r), 2).unwrap_or_default());
}
if let Some(x) = extra_for(f, &xd, r, body(r), &block)
&& let Some(xd) = x.xdict
&& head(body(r)).xdict.is_none()
{
attached.insert(xd.hex());
}
}
let (mut attached, merged) = kept_dictionaries(f, &xd, &recs, tags);
for (_, t) in planned.values().flatten() {
let x = head(t.get(1..).unwrap_or(&[])).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h));
attached.extend(x.and_then(|x| x.xdict).map(Handle::hex));
@@ -1050,7 +1038,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
if nod.contains(&owner) {
break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some();
}
if attached.contains(&cur) {
if attached.contains(&cur) || merged.contains_key(&cur) {
break true;
}
break unknown.contains(&owner) && written.contains(&owner);
@@ -1068,6 +1056,13 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
alive.insert(o.handle.hex(), format!("{next:X}"));
next = next.saturating_add(1);
}
// A merged dictionary is not written: what pointed at it points at the written one.
for (kept, own) in &merged {
if let Some(h) = alive.get_mut(kept) {
h.clone_from(own);
}
}
let merged_into: HashMap<String, &ForeignObject> = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect();
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities };
let mut out: Vec<Tag> = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::<usize>());
@@ -1081,7 +1076,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
continue;
}
if r.kind == "ENDSEC" && r.sec == "OBJECTS" {
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) {
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.contains_key(&o.handle.hex())) {
let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten();
match number {
Some(n) => {
@@ -1105,11 +1100,15 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
}
out.extend(tags.get(r.start).cloned());
let x = extra_for(f, &xd, r, b, &block);
if x.is_none() && Some(r.start) != root {
let joined = joined_into(&merged_into, b);
if x.is_none() && Some(r.start) != root && joined.is_none() {
out.extend(b.iter().cloned());
continue;
}
record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out);
if let Some(kept) = joined {
join_entries(&map, b, kept, &mut out);
}
}
add_appids(&mut out);
let top = max_handle(&out).saturating_add(1);
@@ -1121,6 +1120,32 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
*tags = out;
}
/// Kept extension dictionaries of written records: those that go on a record without its own,
/// and those whose entries join the one the writer gave a table (the LAYER table's, holding the
/// layer states) as kept dictionary → the written one.
fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> (HashSet<String>, HashMap<String, String>) {
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
let mut block = String::new();
let mut attached: HashSet<String> = HashSet::new();
let mut merged: HashMap<String, String> = HashMap::new();
for r in recs {
if r.kind == "BLOCK" {
block = up(&val(body(r), 2).unwrap_or_default());
}
let Some(kept) = extra_for(f, xd, r, body(r), &block).and_then(|x| x.xdict) else { continue };
match head(body(r)).xdict {
None => {
attached.insert(kept.hex());
}
Some(own) if r.sec == "TABLES" => {
merged.insert(kept.hex(), own);
}
Some(_) => {}
}
}
(attached, merged)
}
/// Complete source tables keep positional identities even when names repeat.
fn proxy_class_number(f: &Foreign, numbers: &HashMap<String, i64>, old: Option<i64>) -> Option<i64> {
if f.complete_class_table {
@@ -1352,6 +1377,37 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
}
}
/// The kept dictionary whose entries join written dictionary `b`, if any.
fn joined_into<'a>(merged_into: &HashMap<String, &'a ForeignObject>, b: &[Tag]) -> Option<&'a ForeignObject> {
if merged_into.is_empty() {
return None;
}
head(b).handle.and_then(|h| merged_into.get(&h).copied())
}
/// The entries of kept dictionary `kept` that written dictionary `b` doesn't have (by key, without
/// regard to case), appended to it with their handles remapped; entries whose object is gone are
/// left out.
fn join_entries(map: &Map, b: &[Tag], kept: &ForeignObject, out: &mut Vec<Tag>) {
let has = |key: &str| b.iter().any(|t| t.code == 3 && up(&t.str()) == up(key));
let mut key: Option<&str> = None;
for t in kept.tags.iter().take_while(|t| t.code < 1000) {
match t.code {
3 => key = Some(t.value.as_str()),
350 | 360 => {
if let Some(k) = key.take()
&& !has(k)
&& let Some(h) = map.get(&t.value).filter(|h| h != "0")
{
out.push(Tag::s(3, k));
out.push(Tag::s(t.code, h));
}
}
_ => {}
}
}
}
/// Kept xdata of applications the record doesn't already carry, handles remapped.
fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>) {
let mut skip = false;
-2
View File
@@ -62,8 +62,6 @@ struct Rx {
block_arrays: HashMap<String, cadcraft_doc::ArrayParams>,
/// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers).
layers: HashMap<String, String>,
/// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345).
ucss: HashMap<String, String>,
/// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport
/// (PAPERVIEW) the reader dropped.
paper_views_dropped: Vec<(Option<String>, bool, Option<String>)>,
+99 -62
View File
@@ -1,17 +1,21 @@
use super::common::T;
use super::dimassoc::dimassoc;
use super::document::sortents_table;
use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Ucs, Vec2, Vec3};
use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Vec2};
/// Non-graphical objects applied once every entity is placed.
#[derive(Default)]
pub(super) struct Objects {
/// Dictionary entry handle (upper case) → entry name.
names: HashMap<String, String>,
/// (dictionary handle, entry handle), both upper case, in the order the dictionaries list them.
entry_order: Vec<(String, String)>,
/// SCALE objects (the annotation scale list), in file order.
scales: Vec<cadcraft_doc::AnnoScale>,
/// XRECORD handle (upper case) → its groups.
xrecords: HashMap<String, Vec<Tag>>,
/// XRECORD handles in file order.
xrecord_order: Vec<String>,
/// TABLESTYLE objects: (handle, groups).
table_styles: Vec<(String, Vec<Tag>)>,
/// DIMASSOC objects.
@@ -22,8 +26,6 @@ pub(super) struct Objects {
groups: Vec<(String, Vec<Tag>)>,
/// Saved paper-space views of layouts: (layout name, view).
layout_views: Vec<(String, (Vec2, f64))>,
/// Layouts' current UCSs: (layout name, origin, X axis, Y axis, named UCS record handle).
layout_ucss: Vec<(String, Vec3, Vec3, Vec3, Option<String>)>,
/// SORTENTSTABLE objects: (owning block record handle, entity handle → sort handle).
pub(super) sortents: Vec<(String, HashMap<Handle, u64>)>,
/// WIPEOUTVARIABLES: the drawing's WIPEOUTFRAME (0 = frames hidden, 1 = shown).
@@ -52,7 +54,11 @@ impl Objects {
if let Some(n) = name.take()
&& self.names.len() < MAX_OBJECTS
{
self.names.insert(t.str().trim().to_ascii_uppercase(), n);
let entry = t.str().trim().to_ascii_uppercase();
if self.entry_order.len() < MAX_OBJECTS {
self.entry_order.push((h.clone(), entry.clone()));
}
self.names.insert(entry, n);
}
}
_ => {}
@@ -60,7 +66,9 @@ impl Objects {
}
}
"XRECORD" if self.xrecords.len() < MAX_OBJECTS => {
self.xrecords.insert(h, tags.to_vec());
if self.xrecords.insert(h.clone(), tags.to_vec()).is_none() {
self.xrecord_order.push(h);
}
}
"TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags.to_vec())),
"DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags.to_vec()),
@@ -72,23 +80,75 @@ impl Objects {
self.sortents.push(t);
}
}
"LAYOUT" if self.layout_views.len() < MAX_OBJECTS && self.layout_ucss.len() < MAX_OBJECTS => {
"LAYOUT" if self.layout_views.len() < MAX_OBJECTS => {
let start = tags.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0);
let own = T(tags.get(start..).unwrap_or(&[]));
if let (Some(name), Some(view)) = (own.s(1), layout_view(tags)) {
if let (Some(name), Some(view)) = (T(tags.get(start..).unwrap_or(&[])).s(1), layout_view(tags)) {
self.layout_views.push((name, view));
}
// Its current UCS (groups 13, 16, 17; 345 when it is a named UCS).
if let Some(name) = own.s(1)
&& [13, 16, 17].iter().all(|c| own.f(*c).is_some())
{
self.layout_ucss.push((name, own.p(13), own.p(16), own.p(17), own.s(345)));
}
}
_ => {}
}
}
/// The layer states of the LAYER table's `ACAD_LAYERSTATES` dictionary (its XRECORDs, in file
/// order), read with the drawing's layers and linetypes. Entries whose names differ only in case
/// are one state, as AutoCAD 2024 opens them (measured with `S` and `s` in both orders): named as
/// the first of them in the dictionary, holding the last one's record, where the first of their
/// records comes in the file.
fn acad_layer_states(&self, d: &Drawing, rx: &Rx) -> Vec<cadcraft_doc::LayerState> {
let dicts: std::collections::HashSet<&str> =
self.names.iter().filter(|(_, n)| n.eq_ignore_ascii_case(crate::dxf_layer_states::KEY)).map(|(h, _)| h.as_str()).collect();
if dicts.is_empty() {
return Vec::new();
}
let mut by_name: HashMap<String, &cadcraft_doc::Layer> = HashMap::with_capacity(d.layers.len());
for l in &d.layers {
by_name.entry(l.name.to_ascii_lowercase()).or_insert(l);
}
let layer_of =
|h: &str| rx.layers.get(&h.trim().to_ascii_uppercase()).and_then(|n| by_name.get(&n.to_ascii_lowercase())).map(|l| (*l).clone());
let ltype_of = |h: &str| rx.ltypes.get(&h.trim().to_ascii_uppercase()).cloned();
let pstyle_of = |h: &str| rx.pstyles.get(&h.trim().to_ascii_uppercase()).cloned();
let lookup = crate::dxf_layer_states::Lookup {
layer: &layer_of,
ltype: &ltype_of,
pstyle: &pstyle_of,
colour_dependent: d.header.i64("PSTYLEMODE", 1) != 0,
};
let ours = |tags: &[Tag]| owner(tags).is_some_and(|o| dicts.contains(o.as_str()));
// By lower-case name: the first entry's name and the last entry's record, in dictionary order.
let mut first: HashMap<String, &String> = HashMap::new();
let mut last: HashMap<String, &Vec<Tag>> = HashMap::new();
for (dict, h) in &self.entry_order {
if dicts.contains(dict.as_str())
&& let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h))
&& ours(tags)
{
first.entry(name.to_ascii_lowercase()).or_insert(name);
last.insert(name.to_ascii_lowercase(), tags);
}
}
let mut out = Vec::new();
let mut taken = std::collections::HashSet::new();
let mut budget = crate::dxf_layer_states::MAX_COPIED_BYTES;
for h in &self.xrecord_order {
let (Some(tags), Some(name)) = (self.xrecords.get(h), self.names.get(h)) else { continue };
if out.len() >= crate::dxf_ext::MAX_LAYER_STATES {
break;
}
if !ours(tags) {
continue;
}
let key = name.to_ascii_lowercase();
if taken.insert(key.clone()) {
let name = first.get(&key).copied().unwrap_or(name);
let tags = last.get(&key).copied().unwrap_or(tags);
out.push(crate::dxf_layer_states::read(name, tags, &lookup, &mut budget));
}
}
out
}
/// The text of the CADCraft XRECORD stored under `key` in a dictionary (its 1/3 strings).
pub(super) fn xrecord_text(&self, key: &str) -> Option<String> {
let h = self.names.iter().find(|(_, n)| n.as_str() == key).map(|(h, _)| h)?;
@@ -103,49 +163,6 @@ impl Objects {
Some(text)
}
/// Model space's UCS name ($UCSNAME, or CADCraft's copy when the file lost it, as through
/// DWG): kept only while the current UCS is still exactly that named UCS, else unnamed.
fn apply_ucs_name(&self, d: &mut Drawing) {
let header_name = d.header.str("UCSNAME", "").trim().to_string();
let name = if header_name.is_empty() {
self.xrecord_text(crate::dxf_ext::UCS_NAME_KEY).map(|n| n.trim().to_string()).unwrap_or_default()
} else {
header_name.clone()
};
let frame = (d.header.point("UCSORG"), d.header.point("UCSXDIR"), d.header.point("UCSYDIR"));
let named = match frame {
(Some(o), Some(x), Some(y)) => crate::dxf_ext::named_ucs(&d.ucss, &name, o, x, y).map(|u| u.name.clone()),
_ => None,
};
match named {
Some(n) => d.header.set_str("UCSNAME", &n),
None if !header_name.is_empty() => d.header.set_str("UCSNAME", ""),
None => {}
}
}
/// Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset.
fn apply_layout_ucss(&self, d: &mut Drawing, rx: &Rx) {
for (name, origin, x, y, named) in &self.layout_ucss {
let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y);
// The named UCS group 345 points at, only while the layout's frame is still that
// record's: a valid frame with a stale reference is kept, unnamed.
let ucs_name = named
.as_ref()
.and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase()))
.and_then(|n| crate::dxf_ext::named_ucs(&d.ucss, n, *origin, *x, *y))
.map(|u| u.name.clone())
.unwrap_or_default();
let world = origin.len() <= 1e-12 && (*x - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 && (*y - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12;
if !usable || (world && ucs_name.is_empty()) {
continue;
}
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
l.ucs = Some(Ucs { name: ucs_name, origin: *origin, x_axis: *x, y_axis: *y });
}
}
}
fn apply_table_styles(&self, d: &mut Drawing) {
// Table styles (named by their ACAD_TABLESTYLE dictionary entries).
for (h, tags) in &self.table_styles {
@@ -243,7 +260,6 @@ impl Objects {
if let Some(style) = self.xrecord_text(crate::dxf_ext::MLEADER_STYLE_KEY).filter(|s| !s.trim().is_empty()) {
d.header.set_str("CMLEADERSTYLE", &style);
}
self.apply_ucs_name(d);
self.apply_table_styles(d);
self.apply_table_style_fixes(d, rx);
// Parametric constraints and parameters.
@@ -261,10 +277,18 @@ impl Objects {
if let Some(p) = self.xrecord_text(crate::dxf_ext::ANNOTATION_KEY).and_then(|t| crate::dxf_ext::parse_anno(&t)) {
crate::dxf_ext::apply_anno(d, p);
}
// Saved layer states.
if let Some(states) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
d.layer_states = states;
// Saved layer states: AutoCAD's, then those of CADCraft's own record (a file of an
// earlier version keeps them all there) that AutoCAD's doesn't hold.
let mut states = self.acad_layer_states(d, rx);
if let Some(own) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
let mut names: std::collections::HashSet<String> = states.iter().map(|s| s.name.clone()).collect();
for st in own {
if states.len() < crate::dxf_ext::MAX_LAYER_STATES && names.insert(st.name.clone()) {
states.push(st);
}
}
}
d.layer_states = states;
// The drawing's plot style tables.
if let Some(tables) = self.xrecord_text(crate::dxf_ext::PLOT_STYLES_KEY).and_then(|t| crate::dxf_ext::parse_plot_styles(&t)) {
d.plot_style_tables = tables;
@@ -276,7 +300,6 @@ impl Objects {
l.view = Some(*view);
}
}
self.apply_layout_ucss(d, rx);
self.apply_groups(d);
// Standard associativity, for dimensions without CADCraft's exact links.
for tags in &self.dimassocs {
@@ -285,6 +308,20 @@ impl Objects {
}
}
/// An object's owner (its first group 330 outside a `102` group), upper case.
fn owner(tags: &[Tag]) -> Option<String> {
let mut inside = false;
for t in tags {
match t.code {
102 => inside = t.str().trim().starts_with('{'),
330 if !inside => return Some(t.str().trim().to_ascii_uppercase()),
100 => return None,
_ => {}
}
}
None
}
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm).
pub(super) fn page_setup(t: &T) -> PageSetup {
let mut p = PageSetup::default();
-11
View File
@@ -214,7 +214,6 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
{
d.header.set("SNAPBASE", HVal::Point(Vec3::new(x, y, 0.0)));
}
ucsicon(d, &t);
if let Some(a) = t.f(50).filter(|a| a.is_finite()) {
d.header.set_f64("SNAPANG", a);
}
@@ -315,21 +314,11 @@ fn index_table_handles(recs: &[(String, Vec<Tag>)], rx: &mut Rx) {
"LAYER" => {
rx.layers.insert(handle.trim().to_ascii_uppercase(), name);
}
"UCS" => {
rx.ucss.insert(handle.trim().to_ascii_uppercase(), name);
}
_ => {}
}
}
}
/// The `*ACTIVE` VPORT's UCSICON setting (group 74: bit 1 the icon shown, bit 2 at the UCS origin).
fn ucsicon(d: &mut Drawing, t: &T) {
if let Some(v) = t.i(74) {
d.header.set_i64("UCSICON", v.clamp(0, 3));
}
}
/// Most tiles a viewport configuration keeps.
const MAX_VPORT_TILES: usize = 64;
+1 -8
View File
@@ -9,7 +9,7 @@ use cadcraft_color::Color;
use cadcraft_doc::{
AssocSnap, Attrib, Block, Common, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, EntityStore, Gradient, Group, HAlign,
HVal, Handle, Hatch, Insert, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
TableStyle, Text, Transparency, Ucs, VAlign, VportConfig, VportTile,
TableStyle, Text, Transparency, VAlign, VportConfig, VportTile,
};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
use craft_dxf::{Tag, Version};
@@ -43,11 +43,6 @@ struct W {
pstyles: HashMap<String, String>,
/// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports).
layers: HashMap<String, String>,
/// Upper-case UCS name → its UCS table record handle (group 345 of layouts and viewports).
ucss: HashMap<String, String>,
/// Active VPORT group-345 tags (their index in `t`) waiting for the handle of the named UCS
/// (upper case) they refer to, filled in after the UCS table is written.
vport_ucs: Vec<(usize, String)>,
/// Persistent reactors of source geometry: the associative hatches and DIMASSOC objects
/// that follow it (groups `{ACAD_REACTORS 330 …}`).
reactors: HashMap<Handle, Vec<String>>,
@@ -160,8 +155,6 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec<Tag>) {
next: d.handseed.max(0x100).saturating_add(0x1000),
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: HashMap::new(),
};
let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() };
+1 -9
View File
@@ -16,15 +16,7 @@ pub(super) fn annotative_xdata(w: &mut W) {
/// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension.
pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
let mut ov = W {
t: Vec::new(),
next: 0,
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: HashMap::new(),
};
let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
let mut sah = false;
for (k, v) in &dm.overrides {
let Some(field) = DimStyle::field_name(k) else { continue };
+2
View File
@@ -58,6 +58,8 @@ pub(super) struct Ctx {
pub(super) frozen_341: bool,
/// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists).
pub(super) legacy_columns: bool,
/// Saved layer states in AutoCAD's form (the LAYER table's extension dictionary).
pub(super) layer_states: crate::dxf_layer_states::Plan,
}
impl Ctx {
+1 -33
View File
@@ -1,4 +1,4 @@
use super::{DimVal, Drawing, HVal, K, Ucs, Vec3, Version, W, dxf_ext};
use super::{DimVal, Drawing, HVal, K, Version, W, dxf_ext};
/// Header variables we write, with their group codes (DXF Reference, HEADER section).
/// `P2`/`P3` = 2D/3D point.
@@ -37,11 +37,6 @@ const HEADER_VARS: &[(&str, i32)] = &[
("CHAMFERB", 40),
("ANGBASE", 50),
("ANGDIR", 70),
// Model space's current UCS (each layout's is in its LAYOUT object).
("UCSNAME", 2),
("UCSORG", -3),
("UCSXDIR", -3),
("UCSYDIR", -3),
("PDMODE", 70),
("PDSIZE", 40),
("PLINEWID", 40),
@@ -57,25 +52,6 @@ const HEADER_VARS: &[(&str, i32)] = &[
("VIEWSIZE", 40),
];
/// Model space's current UCS from the header (UCSORG, UCSXDIR, UCSYDIR, UCSNAME): unusable
/// values are the World UCS's, so a broken one read from a file isn't written back.
pub(super) fn model_ucs(d: &Drawing) -> Ucs {
let h = &d.header;
let p = |name: &str| h.point(name).filter(|v| v.is_finite());
let axis = |name: &str| p(name).filter(|v| v.len() > 1e-12);
let (x, y, usable) = match (axis("UCSXDIR"), axis("UCSYDIR")) {
(Some(x), Some(y)) if x.cross(y).len() > 1e-9 * x.len() * y.len() => (x, y, true),
_ => (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), false),
};
// The name only of a UCS table record whose frame the current UCS still is: a name read from
// a file without its record, beside axes replaced by the World UCS's, or beside an origin or
// axes of its own (restoring the name would move the UCS) is dropped.
let origin = p("UCSORG").unwrap_or(Vec3::ZERO);
let raw = h.str("UCSNAME", "");
let name = crate::dxf_ext::named_ucs(&d.ucss, &raw, origin, x, y).filter(|_| usable).map(|u| u.name.clone()).unwrap_or_default();
Ucs { name, origin, x_axis: x, y_axis: y }
}
/// The current dimension style's variables as header variables (`$DIMTXT`, `$DIMDEC`…), after
/// `$DIMSTYLE`: AutoCAD draws new and updated dimensions with the header's DIM* values, which
/// otherwise stay its defaults (0.18 text, 4 decimals) whatever the current style says (#1051).
@@ -128,9 +104,6 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
let p = match *name {
"SNAPUNIT" => d.header.snap_unit().to3(0.0),
"GRIDUNIT" => d.header.grid_unit().to3(0.0),
"UCSORG" => model_ucs(d).origin,
"UCSXDIR" => model_ucs(d).x_axis,
"UCSYDIR" => model_ucs(d).y_axis,
_ => *p,
};
w.s(9, format!("${name}"));
@@ -155,11 +128,6 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
w.i(c, i);
}
}
// Only the name of a UCS the drawing has, with the axes written above.
(c, _) if *name == "UCSNAME" => {
w.s(9, "$UCSNAME");
w.s(c, model_ucs(d).name);
}
(c, v) => {
if let Some(t) = v.as_str() {
w.s(9, format!("${name}"));
+8 -22
View File
@@ -1,5 +1,4 @@
use super::ctx::Ctx;
use super::header::model_ucs;
use super::{Bounds2, Drawing, Entity, EntityKind, Handle, HashMap, Layout, Vec2, Vec3, VportConfig, VportTile, W, dxf_ext};
/// Layouts with viewports but without the paper-space viewport (id 1, the sheet itself), keyed
@@ -139,36 +138,23 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) {
w.f(42, 50.0);
w.f(50, d.header.f64("SNAPANG", 0.0));
w.f(51, twist.to_degrees());
// UCSICON: bit 1 shows the icon, bit 2 puts it at the UCS origin. A setting of the shown
// configuration (there is no header variable for it).
if name == VportConfig::ACTIVE {
w.i(74, d.header.i64("UCSICON", 3).clamp(0, 3));
}
// The shown configuration's tiles keep model space's current UCS (UCSVP 1).
if name == VportConfig::ACTIVE {
let ucs = model_ucs(d);
w.i(65, 1);
w.p(110, ucs.origin);
w.p(111, ucs.x_axis);
w.p(112, ucs.y_axis);
w.i(79, 0);
// The named UCS it is (none: unnamed). The UCS table comes after VPORT, so the
// handle is filled in once that table has given it one ([`W::vport_ucs`]).
if !ucs.name.is_empty() {
w.s(345, "0");
w.vport_ucs.push((w.t.len() - 1, ucs.name.to_ascii_uppercase()));
}
w.f(146, 0.0);
}
}
w.s(0, "ENDTAB");
}
pub(super) fn table_head(w: &mut W, name: &str, count: usize) -> String {
table_head_x(w, name, count, None)
}
/// A table's head, with its extension dictionary `xdict` when it has one.
pub(super) fn table_head_x(w: &mut W, name: &str, count: usize, xdict: Option<&str>) -> String {
let h = w.h();
w.s(0, "TABLE");
w.s(2, name);
w.s(5, h.clone());
if let Some(x) = xdict {
w.group("ACAD_XDICTIONARY", 360, &[x]);
}
w.s(330, "0");
w.s(100, "AcDbSymbolTable");
w.i(70, count as i64);
+37 -60
View File
@@ -3,12 +3,12 @@ use super::blocks::{arrow_block_entities, dim_block_entities, dim_block_plan, re
use super::common::annotative_xdata;
use super::ctx::{AssocObj, Ctx};
use super::entity::{entity, hatch_reactors};
use super::header::{code_page, header_vars, model_ucs};
use super::layout::{paper_views, record_head, sheet_first, table_head, vport_table};
use super::header::{code_page, header_vars};
use super::layout::{paper_views, record_head, sheet_first, table_head, table_head_x, vport_table};
use super::objects::{cadcraft_fonts_name, group_obj, mleader_style_obj, scale_list, table_style_obj};
use super::{
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, Layout, MLeaderStyle, PageSetup, Space,
TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
};
struct TableWritePlan<'a> {
@@ -68,7 +68,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
}
}
w.s(0, "ENDTAB");
write_layer_table(w, d);
write_layer_table(w, d, &mut cx.layer_states);
// STYLE. Linetype shapes from a shape file that isn't a text style get an unnamed shape
// style record (70 bit 1) naming the file.
let mut shape_files: Vec<String> = Vec::new();
@@ -163,8 +163,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
// UCS: named user coordinate systems (DXF Reference, UCS).
let th = table_head(w, "UCS", d.ucss.len());
for u in &d.ucss {
let h = record_head(w, "UCS", &th, "AcDbUCSTableRecord");
w.ucss.insert(u.name.to_ascii_uppercase(), h);
record_head(w, "UCS", &th, "AcDbUCSTableRecord");
w.s(2, &u.name);
w.i(70, 0);
w.p(10, u.origin);
@@ -174,13 +173,6 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
w.f(146, 0.0);
}
w.s(0, "ENDTAB");
// The active VPORT's named UCS (written before this table had handles).
for (i, name) in std::mem::take(&mut w.vport_ucs) {
let h = w.ucss.get(&name).cloned();
if let (Some(h), Some(t)) = (h, w.t.get_mut(i)) {
*t = Tag::s(345, h);
}
}
let apps = ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP];
let th = table_head(w, "APPID", apps.len());
for app in apps {
@@ -193,8 +185,12 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
ltype_handles
}
fn write_layer_table(w: &mut W, d: &Drawing) {
let th = table_head(w, "LAYER", d.layers.len());
/// The LAYER table; when the drawing has layer states AutoCAD can hold, the table's extension
/// dictionary holds them (written with the objects, [`crate::dxf_layer_states`]).
fn write_layer_table(w: &mut W, d: &Drawing, states: &mut crate::dxf_layer_states::Plan) {
let xdict = (!states.is_empty()).then(|| states.xdict.clone());
let th = table_head_x(w, "LAYER", d.layers.len(), xdict.as_deref());
states.table.clone_from(&th);
for l in &d.layers {
let lh = record_head(w, "LAYER", &th, "AcDbLayerTableRecord");
w.layers.insert(l.name.to_ascii_uppercase(), lh);
@@ -253,15 +249,7 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) {
w.i(70, 0);
let v = serde_json::to_value(s).unwrap_or_default();
let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default();
let mut newer = W {
t: Vec::new(),
next: 0,
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: HashMap::new(),
};
let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
for (field, code, kind) in dxf_ext::DIM_CODES {
let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue };
// DIMPOST is written even when empty: a reader that defaults a missing one to "<>"
@@ -401,8 +389,6 @@ struct LayoutWriteData<'a> {
flags: i64,
page: &'a PageSetup,
view: Option<(Vec2, f64)>,
/// The layout's current UCS (none for model space, whose UCS is in the header).
ucs: Option<&'a Ucs>,
/// The layout's limits as read (`None`: the default 0,0 to 12,9).
limits: Option<(Vec2, Vec2)>,
}
@@ -485,21 +471,12 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
w.p(12, Vec3::ZERO);
w.p(14, Vec3::ZERO);
w.p(15, Vec3::ZERO);
// The layout's current UCS: origin, X and Y axes, orthographic type, then (after the
// block record) the named UCS it is.
// Usable by the rule the reader applies, so what is written reads back.
let u = data.ucs.filter(|u| u.origin.is_finite() && dxf_ext::usable_axes(u.x_axis, u.y_axis));
w.f(146, 0.0);
w.p(13, u.map_or(Vec3::ZERO, |u| u.origin));
w.p(16, u.map_or(Vec3::new(1.0, 0.0, 0.0), |u| u.x_axis));
w.p(17, u.map_or(Vec3::new(0.0, 1.0, 0.0), |u| u.y_axis));
w.p(13, Vec3::ZERO);
w.p(16, Vec3::new(1.0, 0.0, 0.0));
w.p(17, Vec3::new(0.0, 1.0, 0.0));
w.i(76, 0);
w.s(330, brh);
// The named UCS it is, only while its frame is still that record's (as for model space).
let named = u.and_then(|u| dxf_ext::named_ucs(&d.ucss, &u.name, u.origin, u.x_axis, u.y_axis));
if let Some(h) = named.and_then(|u| w.ucss.get(&u.name.to_ascii_uppercase())).cloned() {
w.s(345, h);
}
// The saved paper-space view (centre, height) as CADCraft xdata.
if let Some((c, height)) = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite()) {
w.s(1001, dxf_ext::APP);
@@ -559,17 +536,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
layout_obj(
w,
LayoutWriteContext { drawing: d, dictionary: layout_dict },
LayoutWriteData {
handle: model_layout,
name: "Model",
tab: 0,
block_record: ms_br,
flags: 1,
page: &model_page,
view: None,
ucs: None,
limits: None,
},
LayoutWriteData { handle: model_layout, name: "Model", tab: 0, block_record: ms_br, flags: 1, page: &model_page, view: None, limits: None },
);
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
let h = layout_handles.get(i).cloned().unwrap_or_default();
@@ -584,7 +551,6 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
flags: 1,
page: &l.page,
view: l.view,
ucs: l.ucs.as_ref(),
limits: l.limits,
},
);
@@ -787,6 +753,16 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) {
write_root_group_objects(w, &plan, &groups, &group_owner, &written, &mleader_dict);
write_style_objects(w, &plan, &mleader_dict, &mleader_handles);
write_named_objects(w, &plan);
let layer_states = {
let refs = crate::dxf_layer_states::Refs {
layers: &w.layers,
ltypes: &plan.cx.ltypes,
pstyles: &w.pstyles,
colour_dependent: plan.d.header.i64("PSTYLEMODE", 1) != 0,
};
crate::dxf_layer_states::objects(&plan.cx.layer_states, &plan.d.layer_states, &refs)
};
w.t.extend(layer_states);
write_associative_objects(w, plan.cx);
write_layout_objects(w, &plan);
// Raster image definitions.
@@ -957,8 +933,6 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
next: d.handseed.max(0x100).saturating_add(0x1000),
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: hatch_reactors(d),
};
// Pre-allocate handles for block records.
@@ -1016,14 +990,12 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
if let Some(name) = d.header.get("CMLEADERSTYLE").and_then(HVal::as_str) {
xrecords.push((dxf_ext::MLEADER_STYLE_KEY, w.h(), vec![name.to_string()]));
}
let ucs_name = model_ucs(d).name;
if !ucs_name.is_empty() {
xrecords.push((dxf_ext::UCS_NAME_KEY, w.h(), vec![ucs_name]));
}
if let Some(chunks) = dxf_ext::constraint_chunks(&d.constraints, &d.parametric) {
xrecords.push((dxf_ext::CONSTRAINTS_KEY, w.h(), chunks));
}
if let Some(chunks) = dxf_ext::layer_state_chunks(&d.layer_states) {
// Saved layer states: AutoCAD's dictionary holds those it can, CADCraft's record the others.
cx.layer_states = crate::dxf_layer_states::Plan::new(&d.layer_states, || w.h());
if let Some(chunks) = dxf_ext::layer_state_chunks(&crate::dxf_layer_states::own(&d.layer_states)) {
xrecords.push((dxf_ext::LAYER_STATES_KEY, w.h(), chunks));
}
if let Some(chunks) = dxf_ext::plot_style_chunks(&d.plot_style_tables) {
@@ -1035,14 +1007,19 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
// The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects.
let scale_dict = w.h();
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect();
// Plot style names used by layers and objects (Normal always), each a placeholder object.
// Plot style names used by layers and objects (Normal always), each a placeholder object; in
// a drawing of named plot styles also those of the layers of saved layer states, which name
// theirs by placeholder.
let pstyle_dict = w.h();
let mut pstyle_names: Vec<String> = vec![cadcraft_doc::NORMAL_STYLE.to_string()];
let named = d.layers.iter().map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
let mut seen: std::collections::HashSet<String> = pstyle_names.iter().map(|n| n.to_ascii_uppercase()).collect();
let named_styles = d.header.i64("PSTYLEMODE", 1) == 0;
let in_states = d.layer_states.iter().filter(|_| named_styles).flat_map(|s| s.layers.iter());
let named = d.layers.iter().chain(in_states).map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
for n in named {
let n = n.trim();
let logical = n.is_empty() || n.eq_ignore_ascii_case("bylayer") || n.eq_ignore_ascii_case("byblock");
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && !pstyle_names.iter().any(|x| x.eq_ignore_ascii_case(n)) {
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && seen.insert(n.to_ascii_uppercase()) {
pstyle_names.push(n.to_string());
}
}
+1
View File
@@ -9,6 +9,7 @@ mod dxf_raw;
mod dxf_clip;
mod dxf_ext;
mod dxf_image;
mod dxf_layer_states;
mod dxf_mleader;
mod dxf_read;
mod dxf_table;
+17 -5
View File
@@ -1856,22 +1856,24 @@ fn layer_states_roundtrip_next_to_constraints() {
description: "walls \\ hidden".into(),
..Layer::default()
});
d.layer_states.push(LayerState { name: "Plot".into(), layers: d.layers.clone() });
d.layer_states.push(LayerState::new("Plot", d.layers.clone(), "Wände"));
let mut off = d.layers.clone();
for l in &mut off {
(l.on, l.frozen, l.locked, l.plot) = (false, true, true, false);
}
d.layer_states.push(LayerState { name: "All off".into(), layers: off });
d.layer_states.push(LayerState::new("All off", off, ""));
let text = write_dxf(&d);
assert!(text.contains("CADCRAFT_LAYERSTATES"));
// AutoCAD's dictionary holds both states; CADCraft's record isn't needed.
assert!(text.contains("ACAD_LAYERSTATES") && !text.contains("CADCRAFT_LAYERSTATES"));
let back = read_dxf(text.as_bytes()).unwrap();
assert_eq!(back.layer_states, d.layer_states);
assert_eq!(back.constraints, constraints);
assert_eq!(roundtrip(&back).layer_states, d.layer_states);
#[cfg(not(target_arch = "wasm32"))]
assert_eq!(read(&write(&d, "x.dwg").unwrap(), "x.dwg").unwrap().layer_states, d.layer_states);
// Drawings without saved layer states carry no record.
assert!(!write_dxf(&Drawing::new_imperial()).contains("CADCRAFT_LAYERSTATES"));
// Drawings without saved layer states carry neither.
let none = write_dxf(&Drawing::new_imperial());
assert!(!none.contains("CADCRAFT_LAYERSTATES") && !none.contains("ACAD_LAYERSTATES"));
}
fn table_sample() -> Table {
@@ -3713,3 +3715,13 @@ fn solid_hatch_keeps_angle_scale_and_double_flag() {
assert!(f("41").is_some_and(|s| (s - 2.0).abs() < 1e-12), "{h:?}");
assert_eq!(group(h, "77"), Some("0"), "{h:?}");
}
/// A layer state of CADCraft's own record from before states had a mask, a current layer and a
/// description (its JSON holds only the name and the layers) restores every property and names no
/// current layer.
#[test]
fn a_layer_state_saved_before_masks_restores_everything() {
let states = crate::dxf_ext::parse_layer_states(r#"{"version":1,"states":[{"name":"S","layers":[]}]}"#).unwrap();
let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect();
assert_eq!(got, [("S", LayerState::ALL, "", "")]);
}
+451
View File
@@ -0,0 +1,451 @@
//! Saved layer states in AutoCAD's form: the LAYER table's extension dictionary holds an
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. The groups below are copied from
//! AutoCAD 2024's own DXFOUT of states saved with -LAYER stAte on a self-built drawing.
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Drawing, Layer, LayerState, Lineweight};
use cadcraft_io::{read, write_dxf};
/// `(code, value)` pairs of a DXF, trimmed.
fn pairs(dxf: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = dxf.lines().collect();
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
}
fn join(p: &[(String, String)]) -> String {
p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
fn g(c: &str, v: &str) -> (String, String) {
(c.to_string(), v.to_string())
}
/// The records of a DXF: (type, groups after the `0`).
fn records(p: &[(String, String)]) -> Vec<(String, Vec<(String, String)>)> {
let mut out: Vec<(String, Vec<(String, String)>)> = Vec::new();
for (c, v) in p {
if c == "0" {
out.push((v.clone(), Vec::new()));
} else if let Some(last) = out.last_mut() {
last.1.push((c.clone(), v.clone()));
}
}
out
}
fn value<'a>(groups: &'a [(String, String)], code: &str) -> Option<&'a str> {
groups.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str())
}
/// The handle of table record `kind` named `name`.
fn record_handle(p: &[(String, String)], kind: &str, name: &str) -> String {
let recs = records(p);
let (_, groups) = recs.iter().find(|(k, gs)| k == kind && value(gs, "2").is_some_and(|n| n.eq_ignore_ascii_case(name))).unwrap();
value(groups, "5").unwrap().to_string()
}
/// A handle above every handle of the file, plus `k`.
fn fresh(p: &[(String, String)], k: u64) -> String {
let top = p.iter().filter(|(c, _)| c == "5" || c == "105").filter_map(|(_, v)| u64::from_str_radix(v, 16).ok()).max().unwrap();
format!("{:X}", top + 0x100 + k)
}
/// `dxf` with the LAYER table given extension dictionary `xdict` and `objects` added at the end
/// of OBJECTS.
fn inject(dxf: &str, xdict: &str, objects: Vec<(String, String)>) -> String {
let mut p = pairs(dxf);
let table = p.iter().enumerate().position(|(i, (c, v))| c == "0" && v == "TABLE" && p.get(i + 1).is_some_and(|n| n.1 == "LAYER")).unwrap();
let at = table + p[table..].iter().position(|(c, _)| c == "5").unwrap() + 1;
p.splice(at..at, [g("102", "{ACAD_XDICTIONARY"), g("360", xdict), g("102", "}")]);
let objs = p.iter().position(|(c, v)| c == "2" && v == "OBJECTS").unwrap();
let end = objs + p[objs..].iter().position(|(c, v)| c == "0" && v == "ENDSEC").unwrap();
p.splice(end..end, objects);
join(&p)
}
/// Layers A (red) and B, and the DASHED linetype.
fn drawing() -> Drawing {
let mut d = Drawing::new_metric();
d.layers.push(Layer { color: Color::Index(1), ..Layer::new("A") });
d.layers.push(Layer::new("B"));
d.linetypes.push(cadcraft_doc::library::standard_linetypes().into_iter().find(|l| l.name == "DASHED").unwrap());
d
}
/// State S2 as AutoCAD 2024 wrote it after -LAYER: A true colour 10,20,30 (nearest index 168),
/// 50% transparent, 0.35 mm, DASHED, not plotted; B locked and frozen in new viewports. Then the
/// entry of a layer purged since (AutoCAD keeps it, pointing at handles that are gone).
fn s2(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
let (a, b, zero) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"), record_handle(p, "LAYER", "0"));
let (cont, dashed) = (record_handle(p, "LTYPE", "Continuous"), record_handle(p, "LTYPE", "DASHED"));
let gone = fresh(p, 0x50);
let mut v =
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
v.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
for (h, flags, aci, lw, lt, ps, tr) in [
(b.as_str(), "28", "7", "-3", cont.as_str(), "Color_7", "0"),
(a.as_str(), "0", "168", "35", dashed.as_str(), "Color_168", "33554559"),
(zero.as_str(), "8", "7", "-3", cont.as_str(), "Color_7", "0"),
(gone.as_str(), "8", "7", "-3", gone.as_str(), "Color_7", "0"),
] {
v.extend([g("330", h), g("90", flags), g("62", aci), g("370", lw), g("331", lt), g("1", ps), g("440", tr)]);
if h == a {
v.push(g("92", "-1039526882"));
}
}
v
}
/// State S7, saved with only On and restored once (AutoCAD then sets bit 65536), current layer A.
fn s7(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
let (a, b) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"));
let cont = record_handle(p, "LTYPE", "Continuous");
let mut v =
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
v.extend([g("280", "1"), g("91", "66049"), g("301", "only on"), g("290", "0"), g("302", "A")]);
for (h, aci) in [(b.as_str(), "7"), (a.as_str(), "1")] {
v.extend([g("330", h), g("90", "8"), g("62", aci), g("370", "-3"), g("331", &cont), g("1", &format!("Color_{aci}")), g("440", "0")]);
}
v
}
/// The extension dictionary of the LAYER table and the states dictionary, with `extra` entries in
/// the extension dictionary.
fn dictionaries(p: &[(String, String)], x: &str, y: &str, states: &[(&str, &str)], extra: &[(&str, &str)]) -> Vec<(String, String)> {
let table = {
let recs = records(p);
let (_, gs) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
value(gs, "5").unwrap().to_string()
};
let mut v = vec![g("0", "DICTIONARY"), g("5", x), g("330", &table), g("100", "AcDbDictionary"), g("280", "1"), g("281", "1")];
for (k, h) in extra.iter().copied().chain([("ACAD_LAYERSTATES", y)]) {
v.extend([g("3", k), g("360", h)]);
}
v.extend([
g("0", "DICTIONARY"),
g("5", y),
g("102", "{ACAD_REACTORS"),
g("330", x),
g("102", "}"),
g("330", x),
g("100", "AcDbDictionary"),
g("281", "1"),
]);
for (name, h) in states {
v.extend([g("3", name), g("350", h)]);
}
v
}
fn autocad_file() -> String {
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, r7) = (h(1), h(2), h(3), h(4));
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2), ("S7", &r7)], &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &r7, &y));
inject(&base, &x, objects)
}
#[test]
fn reads_the_layer_states_autocad_writes() {
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["S2", "S7"]);
let s2 = &d.layer_states[0];
assert_eq!((s2.mask, s2.current.as_str(), s2.description.as_str()), (2047, "0", ""));
// The purged layer's entry is skipped.
let layers: Vec<&str> = s2.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(layers, ["B", "A", "0"]);
let a = &s2.layers[1];
assert_eq!(a.color, Color::True(Rgb(10, 20, 30)));
assert_eq!((a.transparency, a.lineweight, a.linetype.as_str()), (50, Lineweight::from_dxf(35), "DASHED"));
assert!(a.on && !a.frozen && !a.locked && !a.plot && !a.vp_freeze_new);
// A colour-dependent drawing: the plot style stays the layer's ("Color_168" is its colour's).
assert_eq!(a.plot_style, "Normal");
let b = &s2.layers[0];
assert!(b.on && !b.frozen && b.locked && b.plot && b.vp_freeze_new, "{b:?}");
assert_eq!((b.color, b.linetype.as_str(), b.transparency), (Color::Index(7), "Continuous", 0));
let s7 = &d.layer_states[1];
assert_eq!((s7.mask, s7.current.as_str(), s7.description.as_str()), (66049, "A", "only on"));
assert_eq!(s7.layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(1));
}
#[test]
fn autocads_layer_states_are_written_back_in_its_form() {
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
let text = write_dxf(&d);
let p = pairs(&text);
// One states dictionary, in the LAYER table's extension dictionary, and no CADCraft copy.
assert_eq!(p.iter().filter(|(c, v)| c == "3" && v == "ACAD_LAYERSTATES").count(), 1);
assert!(!text.contains("CADCRAFT_LAYERSTATES"));
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let x = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
let (_, xd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(x.as_str())).unwrap();
assert_eq!(value(xd, "330"), value(table, "5"));
let back = read(text.as_bytes(), "back.dxf").unwrap();
assert_eq!(back.layer_states, d.layer_states);
// The XRECORD of S2 as AutoCAD writes it: B, then A.
let (a_h, b_h) = (record_handle(&p, "LAYER", "A"), record_handle(&p, "LAYER", "B"));
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
let head = rec.iter().position(|(c, _)| c == "280").unwrap();
assert_eq!(rec[head..head + 5], [("280", "1"), ("91", "2047"), ("301", ""), ("290", "0"), ("302", "0")].map(|(c, v)| g(c, v)));
let cont = record_handle(&p, "LTYPE", "Continuous");
let b = [("330", b_h.as_str()), ("90", "28"), ("62", "7"), ("370", "-3"), ("331", &cont), ("1", "Color_7"), ("440", "0")];
assert_eq!(rec[head + 5..head + 12], b.map(|(c, v)| g(c, v)));
let from = rec.iter().position(|(c, v)| c == "330" && *v == a_h).unwrap();
let a: Vec<(String, String)> = rec[from..from + 9].to_vec();
let dashed = record_handle(&p, "LTYPE", "DASHED");
let want = [
("330", a_h.as_str()),
("90", "0"),
("62", "168"),
("370", "35"),
("331", &dashed),
("1", "Color_168"),
("440", "33554559"),
("92", "-1039526882"),
];
assert_eq!(a[..8], want.map(|(c, v)| g(c, v)), "{a:?}");
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
assert_eq!(read(&dwg, "x.dwg").unwrap().layer_states, d.layer_states);
}
}
#[test]
fn layer_filters_next_to_the_states_are_kept() {
// The LAYER table's extension dictionary of a drawing with layer filters holds them next to
// the states (ACAD_LAYERFILTERS, ACLYDICTIONARY): they stay, in the dictionary CADCraft writes.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, f, fr, gone) = (h(1), h(2), h(3), h(4), h(5), h(6));
// Two entries whose objects the file doesn't have (a handle of nothing, and a null one): they
// aren't written into the table's dictionary.
let extra = [("ACAD_LAYERFILTERS", f.as_str()), ("OTHER_GONE", gone.as_str()), ("OTHER_NULL", "0")];
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2)], &extra);
objects.extend(s2(&p, &r2, &y));
objects.extend([g("0", "DICTIONARY"), g("5", &f), g("102", "{ACAD_REACTORS"), g("330", &x), g("102", "}"), g("330", &x)]);
objects.extend([g("100", "AcDbDictionary"), g("281", "1"), g("3", "Walls"), g("350", &fr)]);
objects.extend([g("0", "XRECORD"), g("5", &fr), g("102", "{ACAD_REACTORS"), g("330", &f), g("102", "}"), g("330", &f), g("100", "AcDbXrecord")]);
objects.extend([g("280", "1"), g("1", "A*")]);
let file = inject(&base, &x, objects);
let mut text = file;
for round in 0..2 {
let d = read(text.as_bytes(), "f.dxf").unwrap();
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S2"], "round {round}");
text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let xdicts: Vec<String> = table.windows(2).filter(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).collect();
assert_eq!(xdicts.len(), 1, "round {round}");
let xd = &xdicts[0];
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
let keys: Vec<&str> = dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect();
assert_eq!(keys, ["ACAD_LAYERSTATES", "ACAD_LAYERFILTERS"], "round {round}");
// The filters dictionary is owned by the written one, and so is its filter by it.
let fh = dict.windows(2).find(|w| w[0] == g("3", "ACAD_LAYERFILTERS")).map(|w| w[1].1.clone()).unwrap();
let (_, fd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(fh.as_str())).unwrap();
let owner = fd.iter().filter(|(c, _)| c == "330").map(|(_, v)| v.as_str()).collect::<Vec<_>>();
assert_eq!(owner, [xd.as_str(), xd.as_str()], "round {round}: reactor and owner");
let walls = value(fd, "350").unwrap();
let (_, wr) = recs.iter().find(|(k, gs)| k == "XRECORD" && value(gs, "5") == Some(walls)).unwrap();
assert!(wr.contains(&g("330", &fh)) && wr.contains(&g("1", "A*")), "round {round}");
// The kept dictionary itself is not written a second time.
assert_eq!(recs.iter().filter(|(k, gs)| k == "DICTIONARY" && gs.iter().any(|(c, v)| c == "3" && v == "ACAD_LAYERFILTERS")).count(), 1);
}
// With every state deleted the filters stay, in the table's own dictionary, and AutoCAD's states
// don't come back.
let mut d = read(text.as_bytes(), "f.dxf").unwrap();
d.layer_states.clear();
let text = write_dxf(&d);
assert!(!text.contains("ACAD_LAYERSTATES"));
let p = pairs(&text);
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let xd = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
assert_eq!(dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect::<Vec<_>>(), ["ACAD_LAYERFILTERS"]);
assert!(read(text.as_bytes(), "g.dxf").unwrap().layer_states.is_empty());
}
#[test]
fn entries_whose_names_differ_only_in_case_open_as_one_state() {
// AutoCAD 2024 opens the entries `S` and `s` of one ACAD_LAYERSTATES dictionary as one state:
// named as the first entry in the dictionary and holding the last entry's record (measured with
// the records in one file order and the entries in both dictionary orders, so the first entry's
// record came first in the file once and last once). Here S2's record (mask 2047) comes first in
// the file, then state T's, then S7's (66049); the merged state stays where S2's record is.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, r7, rt) = (h(1), h(2), h(3), h(4), h(5));
let states = |d: &Drawing| d.layer_states.iter().map(|s| (s.name.clone(), s.mask)).collect::<Vec<_>>();
for (pair, name, mask) in [([("S", r2.as_str()), ("s", r7.as_str())], "S", 66049), ([("s", r7.as_str()), ("S", r2.as_str())], "s", 2047)] {
let entries = [pair[0], ("T", rt.as_str()), pair[1]];
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &rt, &y));
objects.extend(s7(&p, &r7, &y));
let d = read(inject(&base, &x, objects).as_bytes(), "case.dxf").unwrap();
let want = [(name.to_string(), mask), ("T".to_string(), 66049)];
assert_eq!(states(&d), want, "{entries:?}");
// Written back, they are the states AutoCAD opened.
let back = read(write_dxf(&d).as_bytes(), "back.dxf").unwrap();
assert_eq!(states(&back), want, "{entries:?}");
}
// A record the dictionary lists as `s` but another object owns isn't a state, and doesn't stand
// in for S's record either.
let mut objects = dictionaries(&p, &x, &y, &[("S", r2.as_str()), ("s", r7.as_str())], &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &r7, &x));
let d = read(inject(&base, &x, objects).as_bytes(), "stray.dxf").unwrap();
assert_eq!(states(&d), [("S".to_string(), 2047)]);
}
#[test]
fn view_snapshots_and_names_twice_in_another_case_stay_in_cadcrafts_record() {
let mut d = drawing();
for name in ["Plan", "*VIEW Front", "PLAN", "Wände", "WÄNDE", "", " "] {
d.layer_states.push(LayerState::new(name, d.layers.clone(), "A"));
}
let text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, states) =
recs.iter().find(|(k, gs)| k == "DICTIONARY" && gs.contains(&g("281", "1")) && gs.iter().any(|(c, v)| c == "3" && v == "Plan")).unwrap();
// (The DXF writes "ä" as \U+00E4.)
let keys: Vec<String> = states.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.replace("\\U+00E4", "ä")).collect();
assert_eq!(keys, ["Plan", "Wände"], "AutoCAD's dictionary holds the first of each name");
assert!(text.contains("CADCRAFT_LAYERSTATES"));
let back = read(text.as_bytes(), "v.dxf").unwrap();
// AutoCAD's states first, then CADCraft's own.
// (A blank name can't be a key of AutoCAD's dictionary: those stay in CADCraft's record too.)
let want: Vec<LayerState> = [0, 3, 1, 2, 4, 5, 6].iter().map(|&i| d.layer_states[i].clone()).collect();
assert_eq!(back.layer_states, want);
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "v.dwg").unwrap();
assert_eq!(read(&dwg, "v.dwg").unwrap().layer_states, want);
}
}
#[test]
fn a_layer_of_an_xref_gets_group_93() {
// AutoCAD 2024 writes 93 (0 for a newly attached xref) after the lineweight of an xref's layer
// only (measured with a self-built xref).
let mut d = drawing();
d.layers.push(Layer::new("XR|L1"));
d.layer_states.push(LayerState::new("X", d.layers.clone(), "0"));
let p = pairs(&write_dxf(&d));
let recs = records(&p);
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
let start = rec.iter().position(|(c, _)| c == "302").unwrap() + 1;
let mut with_93 = Vec::new();
let mut layer = String::new();
for (i, (c, v)) in rec.iter().enumerate().skip(start) {
match c.as_str() {
"330" => layer.clone_from(v),
"93" => {
assert_eq!((v.as_str(), rec[i - 1].0.as_str(), rec[i + 1].0.as_str()), ("0", "370", "331"));
with_93.push(layer.clone());
}
_ => {}
}
}
assert_eq!(with_93, [record_handle(&p, "LAYER", "XR|L1")]);
}
#[test]
fn named_plot_styles_are_written_by_placeholder() {
// In a drawing of named plot styles AutoCAD 2024 writes a layer's plot style as group 390, the
// handle of the style's placeholder object (measured); CADCraft reads it back by that handle.
let mut d = drawing();
d.header.set_i64("PSTYLEMODE", 0);
let a = d.layers.iter().position(|l| l.name == "A").unwrap();
d.layers[a].plot_style = "Thick".into();
d.layer_states.push(LayerState::new("N", d.layers.clone(), "0"));
// No layer uses Thick any more: its placeholder is written for the state.
d.layers[a].plot_style = "Normal".into();
let text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, names) = recs.iter().find(|(k, _)| k == "ACDBDICTIONARYWDFLT").unwrap();
let thick = names.windows(2).find(|w| w[0] == g("3", "Thick")).map(|w| w[1].1.clone()).unwrap();
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
assert!(rec.contains(&g("390", &thick)) && !rec.iter().any(|(c, _)| c == "1"), "{rec:?}");
let back = read(text.as_bytes(), "n.dxf").unwrap();
assert_eq!(back.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().plot_style, "Thick");
assert_eq!(back.layer_states, d.layer_states);
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "n.dwg").unwrap();
assert_eq!(read(&dwg, "n.dwg").unwrap().layer_states, d.layer_states);
}
}
#[test]
fn a_state_in_both_records_is_read_from_autocads() {
// A file of an earlier CADCraft keeps its states in CADCraft's record; AutoCAD then saves a state
// of the same name in its own dictionary: AutoCAD's is the one read.
let mut d = drawing();
d.layer_states.push(LayerState::new("S", d.layers.clone(), "A"));
d.layer_states.push(LayerState::new("*VIEW S", d.layers.clone(), "B"));
let text = write_dxf(&d);
assert!(text.contains("*VIEW S"));
let text = text.replace("*VIEW S", "S");
let back = read(text.as_bytes(), "both.dxf").unwrap();
assert_eq!(back.layer_states.iter().map(|s| (s.name.as_str(), s.current.as_str())).collect::<Vec<_>>(), [("S", "A")]);
}
#[test]
fn states_past_the_limit_are_left_out_and_the_rest_come_in_file_order() {
// A hostile file with one state more than the reader keeps (100 000): the last one in the file
// is left out, and the others come in file order, here the reverse of their names' order.
const LIMIT: u64 = 100_000;
let base = write_dxf(&drawing());
let p = pairs(&base);
let first = u64::from_str_radix(&fresh(&p, 0), 16).unwrap();
let h = |k: u64| format!("{:X}", first + k);
let (x, y) = (h(1), h(2));
let names: Vec<String> = (0..=LIMIT).map(|i| format!("S{:06}", LIMIT + 1 - i)).collect();
let records: Vec<String> = (0..=LIMIT).map(|i| h(3 + i)).collect();
let entries: Vec<(&str, &str)> = names.iter().map(String::as_str).zip(records.iter().map(String::as_str)).collect();
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
for r in &records {
objects.extend([g("0", "XRECORD"), g("5", r), g("330", &y), g("100", "AcDbXrecord")]);
objects.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
}
let d = read(inject(&base, &x, objects).as_bytes(), "many.dxf").unwrap();
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names.len(), 100_000);
assert_eq!((names.first().copied(), names.get(1).copied(), names.last().copied()), (Some("S100001"), Some("S100000"), Some("S000002")));
}
#[test]
fn a_record_twice_in_a_file_is_one_state() {
// A damaged file can hold an object twice under one handle: one state.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r7) = (h(1), h(2), h(4));
let mut objects = dictionaries(&p, &x, &y, &[("S7", &r7)], &[]);
objects.extend(s7(&p, &r7, &y));
objects.extend(s7(&p, &r7, &y));
let d = read(inject(&base, &x, objects).as_bytes(), "twice.dxf").unwrap();
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S7"]);
}
#[test]
fn group_92_without_the_true_colour_prefix_is_not_a_true_colour() {
// AutoCAD 2024 writes 92 only for a true colour, 0xC2RRGGBB (measured); a value with another
// high byte (not seen from AutoCAD) leaves the colour index of group 62.
let text = autocad_file().replace("92\n-1039526882", "92\n-1023410175");
let d = read(text.as_bytes(), "c3.dxf").unwrap();
assert_eq!(d.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(168));
}
+1
View File
@@ -32,6 +32,7 @@ mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_pattern_def;
mod helix_roundtrip;
mod layer_states_acad;
mod layout_limits_roundtrip;
mod layout_paper_units;
mod layout_plot_window;
+1 -1
View File
@@ -185,7 +185,7 @@ pub(super) fn layer_states() -> Case {
layer.on = false;
layer.locked = true;
}
drawing.layer_states.push(LayerState { name: "Saved".into(), layers });
drawing.layer_states.push(LayerState::new("Saved", layers, "0"));
Case { name: "drawing/layer-state".into(), drawing }
}
+15 -5
View File
@@ -492,11 +492,16 @@ const OBJECTS: &str = "
330 61
100 AcDbXrecord
280 1
91 0
91 2047
301 Plan
8 WALLS
90 0
290 0
302 0
330 11
90 8
62 1
370 -3
1 Normal
440 0
0 DICTIONARY
5 63
330 10
@@ -803,14 +808,19 @@ fn ucs_layer_states_and_block_descriptions_are_kept() {
assert_eq!((u.origin.x, u.origin.y, u.origin.z), (1.0, 2.0, 3.0));
assert_eq!((u.x_axis.y, u.y_axis.x), (1.0, -1.0));
assert_eq!(d.block("DOOR").map(|b| b.description.as_str()), Some("A door leaf"));
let states: Vec<(&str, Vec<&str>)> =
d.layer_states.iter().map(|s| (s.name.as_str(), s.layers.iter().map(|l| l.name.as_str()).collect())).collect();
assert_eq!(states, [("Plan", vec!["WALLS"])]);
for o in [&a, &b] {
// Layer states live in the LAYER table's extension dictionary.
// Layer states live in the LAYER table's extension dictionary, each layer named by its
// handle (as AutoCAD 2024 writes them; CADCraft reads and rewrites them).
let table = o.of("TABLE").into_iter().find(|t| s(t, 2) == "LAYER").expect("LAYER table");
let [xd] = group(table, "ACAD_XDICTIONARY").try_into().expect("LAYER table extension dictionary");
let (_, dict) = o.handle(&xd).expect("dictionary");
let (_, states) = o.entry(dict, "ACAD_LAYERSTATES").expect("ACAD_LAYERSTATES");
let (_, plan) = o.entry(states, "Plan").expect("layer state Plan");
assert_eq!((s(plan, 301), s(plan, 8)), ("Plan".into(), "WALLS".into()));
let layers = plan.iter().skip_while(|t| t.code != 302).filter(|t| t.code == 330).map(Tag::str).collect::<Vec<_>>();
assert_eq!((s(plan, 301), layers), ("Plan".into(), vec![h(o.named("LAYER", "WALLS"))]));
}
}
-472
View File
@@ -1,472 +0,0 @@
//! The current UCS survives saving and reopening (#1106): model space's in the header
//! ($UCSORG, $UCSXDIR, $UCSYDIR, $UCSNAME) and the shown VPORT, each layout's in its LAYOUT
//! object (groups 13, 16, 17 and 345 for a named UCS), through DXF and DWG.
use cadcraft_doc::*;
use cadcraft_geom::Vec3;
fn near3(a: Vec3, b: Vec3) -> bool {
(a - b).len() < 1e-9
}
/// The (code, value) pairs of every `kind` record in DXF text.
fn records(text: &str, kind: &str) -> Vec<Vec<(String, String)>> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out: Vec<Vec<(String, String)>> = Vec::new();
let mut inside = false;
for pair in lines.chunks(2) {
let [code, value] = pair else { break };
if *code == "0" {
inside = *value == kind;
if inside {
out.push(Vec::new());
}
} else if inside && let Some(rec) = out.last_mut() {
rec.push((code.to_string(), value.to_string()));
}
}
out
}
fn group<'a>(rec: &'a [(String, String)], code: &str) -> Option<&'a str> {
rec.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str())
}
/// The LAYOUT object of layout `name` (its group 1 after `100 AcDbLayout`; the first group 1 is
/// the page setup's).
fn layout_record(text: &str, name: &str) -> Vec<(String, String)> {
records(text, "LAYOUT")
.into_iter()
.find(|r| r.iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbLayout")).any(|(c, v)| c == "1" && v == name))
.unwrap_or_else(|| panic!("no LAYOUT {name}"))
}
fn num(rec: &[(String, String)], code: &str) -> f64 {
group(rec, code).and_then(|v| v.trim().parse().ok()).unwrap_or(f64::NAN)
}
/// The header variable `$name`'s groups in DXF text.
fn header_var(text: &str, name: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
let mut on = false;
for pair in lines.chunks(2) {
let [code, value] = pair else { break };
if *code == "9" {
on = *value == format!("${name}");
continue;
}
if *code == "0" {
on = false;
}
if on {
out.push((code.to_string(), value.to_string()));
}
}
out
}
const C30: f64 = 0.866_025_403_784_438_6;
/// A drawing whose model space is in a named UCS turned 30° at (100, 50, 0), and whose first
/// layout is in an unnamed one at (5, 5) turned 90°.
fn drawing() -> Drawing {
let mut d = Drawing::default();
let site = Ucs { name: "SITE".into(), origin: Vec3::new(100.0, 50.0, 0.0), x_axis: Vec3::new(C30, 0.5, 0.0), y_axis: Vec3::new(-0.5, C30, 0.0) };
d.ucss.push(site.clone());
d.header.set("UCSORG", HVal::Point(site.origin));
d.header.set("UCSXDIR", HVal::Point(site.x_axis));
d.header.set("UCSYDIR", HVal::Point(site.y_axis));
d.header.set_str("UCSNAME", "SITE");
d.layouts[0].ucs =
Some(Ucs { name: String::new(), origin: Vec3::new(5.0, 5.0, 0.0), x_axis: Vec3::new(0.0, 1.0, 0.0), y_axis: Vec3::new(-1.0, 0.0, 0.0) });
d
}
fn check(back: &Drawing) {
let h = &back.header;
assert!(near3(h.point("UCSORG").unwrap(), Vec3::new(100.0, 50.0, 0.0)));
assert!(near3(h.point("UCSXDIR").unwrap(), Vec3::new(C30, 0.5, 0.0)));
assert!(near3(h.point("UCSYDIR").unwrap(), Vec3::new(-0.5, C30, 0.0)));
assert_eq!(h.str("UCSNAME", ""), "SITE");
let l = back.layouts[0].ucs.clone().expect("the layout keeps its UCS");
assert!(near3(l.origin, Vec3::new(5.0, 5.0, 0.0)) && near3(l.x_axis, Vec3::new(0.0, 1.0, 0.0)) && l.name.is_empty(), "{l:?}");
assert!(back.layouts.iter().skip(1).all(|l| l.ucs.is_none()), "the other layouts stay in the World UCS");
}
#[test]
fn model_and_layout_ucs_survive_a_dxf_save() {
let d = drawing();
let text = cadcraft_io::write_dxf(&d);
// The header and the shown viewport both carry model space's UCS.
let org = header_var(&text, "UCSORG");
assert_eq!((num(&org, "10"), num(&org, "20"), num(&org, "30")), (100.0, 50.0, 0.0));
assert_eq!(group(&header_var(&text, "UCSNAME"), "2"), Some("SITE"));
let active = records(&text, "VPORT").into_iter().find(|r| group(r, "2").is_some_and(|n| n.eq_ignore_ascii_case("*ACTIVE"))).unwrap();
assert_eq!((num(&active, "110"), num(&active, "120")), (100.0, 50.0));
assert!((num(&active, "111") - C30).abs() < 1e-12 && group(&active, "65") == Some("1"));
// The layout object carries the layout's.
let lay = layout_record(&text, &d.layouts[0].name);
assert_eq!((num(&lay, "13"), num(&lay, "23"), num(&lay, "16"), num(&lay, "26")), (5.0, 5.0, 0.0, 1.0));
assert!(group(&lay, "345").is_none(), "unnamed: no UCS record");
check(&cadcraft_io::read_dxf(text.as_bytes()).unwrap());
}
#[test]
fn a_layouts_named_ucs_points_at_its_record() {
let mut d = drawing();
// The layout's UCS is SITE (its frame, by name).
let site_rec = d.ucss[0].clone();
d.layouts[0].ucs = Some(site_rec.clone());
let text = cadcraft_io::write_dxf(&d);
let site = records(&text, "UCS").into_iter().find(|r| group(r, "2") == Some("SITE")).and_then(|r| group(&r, "5").map(str::to_string)).unwrap();
let lay = layout_record(&text, &d.layouts[0].name);
assert_eq!(group(&lay, "345"), Some(site.as_str()));
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
assert_eq!(back.layouts[0].ucs.as_ref().unwrap().name, "SITE");
// Named SITE but moved since: not pointed at SITE (reopened, the name would bring SITE's frame
// with the moved one); the layout keeps its own frame unnamed.
let mut moved = d.clone();
moved.layouts[0].ucs = Some(Ucs { origin: site_rec.origin + Vec3::new(1.0, 0.0, 0.0), ..site_rec.clone() });
let text = cadcraft_io::write_dxf(&moved);
assert!(group(&layout_record(&text, &d.layouts[0].name), "345").is_none());
let u = cadcraft_io::read_dxf(text.as_bytes()).unwrap().layouts[0].ucs.clone().unwrap();
assert!(u.name.is_empty() && near3(u.origin, site_rec.origin + Vec3::new(1.0, 0.0, 0.0)), "{u:?}");
// A deleted named UCS isn't pointed at, and the layout keeps the axes unnamed.
let mut gone = back.clone();
gone.ucss.clear();
let text = cadcraft_io::write_dxf(&gone);
let lay = layout_record(&text, &d.layouts[0].name);
assert!(group(&lay, "345").is_none());
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
let u = back.layouts[0].ucs.clone().unwrap();
assert!(u.name.is_empty() && near3(u.x_axis, site_rec.x_axis));
}
/// Short but square layout axes are a usable UCS when read, so they are written as they are and
/// not replaced by the World UCS's (the writer and the reader share one rule).
#[test]
fn short_layout_axes_survive_a_save() {
let mut d = drawing();
let tiny = Ucs { name: String::new(), origin: Vec3::new(2.0, 3.0, 0.0), x_axis: Vec3::new(1e-7, 0.0, 0.0), y_axis: Vec3::new(0.0, 1e-7, 0.0) };
d.layouts[0].ucs = Some(tiny.clone());
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap();
let u = back.layouts[0].ucs.clone().expect("kept");
assert!(near3(u.x_axis, tiny.x_axis) && near3(u.y_axis, tiny.y_axis) && near3(u.origin, tiny.origin), "{u:?}");
}
/// Far from the World origin a named UCS's origin is still compared to round-off only: a move of
/// 0.05 at 100,000,000 is a different UCS, an exact save keeps the name.
#[test]
fn a_far_named_ucs_keeps_its_name_only_where_it_is() {
let far = Ucs { name: "FAR".into(), origin: Vec3::new(1e8, 0.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) };
let mut d = Drawing::default();
d.ucss.push(far.clone());
d.header.set("UCSORG", HVal::Point(far.origin));
d.header.set("UCSXDIR", HVal::Point(far.x_axis));
d.header.set("UCSYDIR", HVal::Point(far.y_axis));
d.header.set_str("UCSNAME", "FAR");
let read = |d: &Drawing| cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap().header.str("UCSNAME", "");
assert_eq!(read(&d), "FAR");
d.header.set("UCSORG", HVal::Point(Vec3::new(1e8 + 0.05, 0.0, 0.0)));
assert_eq!(read(&d), "", "moved 0.05: no longer FAR");
// Further out still: at 1e12 an exact save keeps the name and a 0.5 move drops it.
let mut d = d.clone();
let far = Ucs { origin: Vec3::new(1e12, 0.0, 0.0), ..far };
d.ucss = vec![far.clone()];
d.header.set("UCSORG", HVal::Point(far.origin));
assert_eq!(read(&d), "FAR");
d.header.set("UCSORG", HVal::Point(Vec3::new(1e12 + 0.5, 0.0, 0.0)));
assert_eq!(read(&d), "", "moved 0.5 at 1e12: no longer FAR");
}
/// DXF text with the value of group `code` in the first record `kind` holding `marker` (code,
/// value) replaced by `value`.
fn replace_group(text: &str, after: (&str, &str), code: &str, value: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let mut out = Vec::with_capacity(lines.len());
let mut armed = false;
let mut done = false;
for pair in lines.chunks(2) {
let [c, v] = pair else { break };
let (ct, vt) = (c.trim(), v.trim());
if !done && ct == after.0 && vt == after.1 {
armed = true;
}
let v = if armed && !done && ct == code {
done = true;
value.to_string()
} else {
v.to_string()
};
out.push(format!("{c}\n{v}"));
}
out.join("\n") + "\n"
}
/// Read from a file, a UCS name is kept only while its frame is that record's: a $UCSNAME, or a
/// layout's group 345, naming a UCS whose origin differs leaves the frame as it is, unnamed.
#[test]
fn a_stale_ucs_name_in_a_file_is_dropped_on_read() {
// Model space: $UCSNAME SITE, but $UCSORG moved away from SITE's origin.
let text = cadcraft_io::write_dxf(&drawing());
let moved = replace_group(&text, ("9", "$UCSORG"), "10", "101.0");
let back = cadcraft_io::read_dxf(moved.as_bytes()).unwrap();
assert_eq!(back.header.str("UCSNAME", ""), "", "SITE no longer");
assert!(near3(back.header.point("UCSORG").unwrap(), Vec3::new(101.0, 50.0, 0.0)), "the frame is kept");
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE", "unmoved, still SITE");
// A layout: its UCS is SITE (345 written), then its origin (group 13) moved in the file.
let mut d = drawing();
d.layouts[0].ucs = Some(d.ucss[0].clone());
let name = d.layouts[0].name.clone();
let text = cadcraft_io::write_dxf(&d);
assert!(group(&layout_record(&text, &name), "345").is_some());
let moved = replace_group(&text, ("1", &name), "13", "7.0");
let u = cadcraft_io::read_dxf(moved.as_bytes()).unwrap().layout(&name).unwrap().ucs.clone().unwrap();
assert!(u.name.is_empty() && (u.origin.x - 7.0).abs() < 1e-9, "{u:?}");
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().layout(&name).unwrap().ucs.as_ref().unwrap().name, "SITE");
}
/// The active VPORT names model space's UCS too: group 345 is the UCS record's handle while the
/// UCS is that named one, and absent while it is unnamed.
#[test]
fn the_active_vport_points_at_the_named_ucs() {
let active = |text: &str| records(text, "VPORT").into_iter().find(|r| group(r, "2") == Some("*Active")).unwrap();
let text = cadcraft_io::write_dxf(&drawing());
let site = records(&text, "UCS").into_iter().find(|r| group(r, "2") == Some("SITE")).and_then(|r| group(&r, "5").map(str::to_string)).unwrap();
assert_eq!(group(&active(&text), "345"), Some(site.as_str()));
let mut unnamed = drawing();
unnamed.header.set_str("UCSNAME", "");
assert!(group(&active(&cadcraft_io::write_dxf(&unnamed)), "345").is_none());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn model_and_layout_ucs_survive_a_dwg_save() {
let d = drawing();
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
let back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
check(&back);
// And a second trip.
let again = cadcraft_io::read(&cadcraft_io::write(&back, "x.dwg").unwrap(), "x.dwg").unwrap();
check(&again);
}
#[test]
fn a_drawing_in_the_world_ucs_is_written_as_before() {
let d = Drawing::default();
let text = cadcraft_io::write_dxf(&d);
assert!(header_var(&text, "UCSORG").is_empty(), "nothing set, nothing written");
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
assert!(back.layouts.iter().all(|l| l.ucs.is_none()));
assert!(back.header.point("UCSXDIR").is_none_or(|x| near3(x, Vec3::new(1.0, 0.0, 0.0))));
}
#[test]
fn a_tilted_ucs_is_kept_as_it_is() {
let mut d = Drawing::default();
d.header.set("UCSORG", HVal::Point(Vec3::new(0.0, 0.0, 10.0)));
d.header.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
d.header.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0)));
d.ucss.push(Ucs { name: "FRONT".into(), origin: Vec3::ZERO, x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 0.0, 1.0) });
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap();
assert!(near3(back.header.point("UCSYDIR").unwrap(), Vec3::new(0.0, 0.0, 1.0)));
assert!(near3(back.header.point("UCSORG").unwrap(), Vec3::new(0.0, 0.0, 10.0)));
assert!(near3(back.ucss[0].y_axis, Vec3::new(0.0, 0.0, 1.0)));
}
#[test]
fn broken_ucs_values_are_not_written_back() {
let mut d = Drawing::default();
d.header.set("UCSORG", HVal::Point(Vec3::new(f64::NAN, 1.0, 0.0)));
d.header.set("UCSXDIR", HVal::Point(Vec3::ZERO));
d.header.set("UCSYDIR", HVal::Point(Vec3::new(f64::INFINITY, 0.0, 0.0)));
d.layouts[0].ucs = Some(Ucs { name: "X".into(), origin: Vec3::new(f64::NAN, 0.0, 0.0), x_axis: Vec3::ZERO, y_axis: Vec3::ZERO });
let text = cadcraft_io::write_dxf(&d);
assert!(!text.to_ascii_lowercase().contains("nan") && !text.to_ascii_lowercase().contains("inf"), "no non-finite numbers written");
let x = header_var(&text, "UCSXDIR");
assert_eq!((num(&x, "10"), num(&x, "20")), (1.0, 0.0), "the World UCS's axes instead");
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
assert!(back.layouts[0].ucs.is_none());
}
/// Model space's UCS name is written only for a UCS the drawing has, with the axes it came with:
/// a name without its record, or beside axes replaced by the World UCS's, is left out of both
/// $UCSNAME and CADCraft's copy of it.
#[test]
fn a_ucs_name_without_its_ucs_is_not_written() {
let name_written = |d: &Drawing| {
let text = cadcraft_io::write_dxf(d);
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
(
group(&header_var(&text, "UCSNAME"), "2").unwrap_or_default().trim().to_string(),
text.contains("CADCRAFT_UCSNAME"),
back.header.str("UCSNAME", ""),
)
};
// Kept: SITE is in the UCS table and its axes are current.
assert_eq!(name_written(&drawing()), ("SITE".to_string(), true, "SITE".to_string()));
// No such record (as a file can say).
let mut ghost = drawing();
ghost.header.set_str("UCSNAME", "GHOST");
assert_eq!(name_written(&ghost), (String::new(), false, String::new()));
// The record is there, but the axes beside the name are unusable: written as the World UCS.
let mut broken = drawing();
broken.header.set("UCSXDIR", HVal::Point(Vec3::ZERO));
assert_eq!(name_written(&broken), (String::new(), false, String::new()));
// Usable but not SITE's frame (moved, or turned): restoring SITE would move the UCS, so the
// current one is unnamed.
let mut moved = drawing();
moved.header.set("UCSORG", HVal::Point(Vec3::new(101.0, 50.0, 0.0)));
assert_eq!(name_written(&moved), (String::new(), false, String::new()));
let mut turned = drawing();
turned.header.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
turned.header.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 1.0, 0.0)));
assert_eq!(name_written(&turned), (String::new(), false, String::new()));
}
#[test]
fn hostile_layout_ucs_groups_are_ignored() {
let d = Drawing::default();
let text = cadcraft_io::write_dxf(&d);
let name = d.layouts[0].name.clone();
// Rewrite the layout's UCS axes (X: groups 16/26, Y: 17/27) as nonsense, each with a dangling
// 345 handle: no length, Y along X, not a number.
let usable = |l: &cadcraft_doc::Layout| l.ucs.as_ref().is_none_or(|u| u.name.is_empty() && u.x_axis.cross(u.y_axis).len() > 1e-9);
for (case, [x16, x26, y17, y27], h) in [
("no length", ["0.0", "0.0", "0.0", "0.0"], "FFFF"),
("Y along X", ["1.0", "0.0", "2.0", "0.0"], "0"),
("not a number", ["nan", "0.0", "0.0", "1.0"], "ZZ"),
] {
let mut out = String::new();
let mut in_layout = false;
let mut lines = text.lines();
while let (Some(c), Some(v)) = (lines.next(), lines.next()) {
let (ct, vt) = (c.trim(), v.trim());
if ct == "0" {
in_layout = vt == "LAYOUT";
}
let v = match (in_layout, ct) {
(true, "16") => x16.to_string(),
(true, "26") => x26.to_string(),
(true, "17") => y17.to_string(),
(true, "27") => y27.to_string(),
_ => v.to_string(),
};
out.push_str(&format!("{c}\n{v}\n"));
if in_layout && ct == "76" {
out.push_str(&format!("345\n{h}\n"));
}
}
// Refusing the file is fine; reading it must leave no unusable UCS, saved and reopened too.
// Parallel axes are plain numbers: that file must read, so the rejection below runs.
let back = match cadcraft_io::read_dxf(out.as_bytes()) {
Ok(back) => back,
Err(e) if case == "Y along X" => panic!("{case}: {e}"),
Err(_) => continue,
};
let l = back.layout(&name).unwrap();
assert!(usable(l), "{case}: {:?}", l.ucs);
if case == "Y along X" {
assert!(l.ucs.is_none(), "parallel axes are rejected: {:?}", l.ucs);
}
let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&back).as_bytes()).unwrap();
assert!(usable(again.layout(&name).unwrap()), "{case} after save and reopen");
}
}
#[test]
fn a_stale_ucs_name_copy_is_not_brought_back() {
let text = cadcraft_io::write_dxf(&drawing());
// As another program would save it after changing the UCS: $UCSNAME cleared, the axes moved,
// CADCraft's copy of the old name still there.
let mut out = String::new();
let mut lines = text.lines().peekable();
let mut var = String::new();
while let (Some(c), Some(v)) = (lines.next(), lines.next()) {
if c.trim() == "9" {
var = v.trim().to_string();
}
let v = match (var.as_str(), c.trim()) {
("$UCSNAME", "2") => String::new(),
("$UCSXDIR", "10") => "0.0".into(),
("$UCSXDIR", "20") => "1.0".into(),
("$UCSYDIR", "10") => "-1.0".into(),
("$UCSYDIR", "20") => "0.0".into(),
_ => v.to_string(),
};
out.push_str(&format!("{c}\n{v}\n"));
}
let back = cadcraft_io::read_dxf(out.as_bytes()).unwrap();
assert_eq!(back.header.str("UCSNAME", ""), "", "the UCS is no longer SITE");
assert!(near3(back.header.point("UCSXDIR").unwrap(), Vec3::new(0.0, 1.0, 0.0)));
// While it still matches, the copy names it (what a DWG round trip relies on).
let mut same = String::new();
let mut lines = text.lines();
let mut var = String::new();
while let (Some(c), Some(v)) = (lines.next(), lines.next()) {
if c.trim() == "9" {
var = v.trim().to_string();
}
let v = if var == "$UCSNAME" && c.trim() == "2" { String::new() } else { v.to_string() };
same.push_str(&format!("{c}\n{v}\n"));
}
assert_eq!(cadcraft_io::read_dxf(same.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE");
}
/// A layout's UCS far from the World origin keeps its name (and group 345) on an exact save, and
/// loses both when the layout moves by 0.5 at 1e12, in the writer and in the reader.
#[test]
fn a_far_layout_ucs_keeps_its_name_only_where_it_is() {
let far = Ucs { name: "FAR".into(), origin: Vec3::new(1e12, 0.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) };
let mut d = Drawing::default();
d.ucss.push(far.clone());
d.layouts[0].ucs = Some(far.clone());
let name = d.layouts[0].name.clone();
let text = cadcraft_io::write_dxf(&d);
assert!(group(&layout_record(&text, &name), "345").is_some(), "exact save: pointed at FAR");
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().layouts[0].ucs.as_ref().unwrap().name, "FAR");
// Writer: the layout moved 0.5 since it was named FAR.
d.layouts[0].ucs = Some(Ucs { origin: Vec3::new(1e12 + 0.5, 0.0, 0.0), ..far.clone() });
let moved = cadcraft_io::write_dxf(&d);
assert!(group(&layout_record(&moved, &name), "345").is_none(), "moved 0.5 at 1e12: not FAR");
assert!(cadcraft_io::read_dxf(moved.as_bytes()).unwrap().layouts[0].ucs.as_ref().unwrap().name.is_empty());
// Reader: a file whose layout origin (group 13) moved but whose 345 still names FAR.
let stale = replace_group(&text, ("1", &name), "13", "1000000000000.5");
let u = cadcraft_io::read_dxf(stale.as_bytes()).unwrap().layouts[0].ucs.clone().unwrap();
assert!(u.name.is_empty(), "{u:?}");
}
/// The `*ACTIVE` VPORT record's group 74 (UCSICON setting) in DXF text.
fn active_ucsicon(text: &str) -> Option<String> {
let active = records(text, "VPORT").into_iter().find(|r| group(r, "2").is_some_and(|n| n.eq_ignore_ascii_case("*ACTIVE")))?;
group(&active, "74").map(str::to_string)
}
/// UCSICON is a setting of the drawing, kept in the active VPORT's group 74 (bit 1 the icon,
/// bit 2 at the origin): icon off comes back off after a DXF save, and it is no header variable.
#[test]
fn ucsicon_survives_a_dxf_round_trip() {
let mut d = Drawing::default();
d.header.set_i64("UCSICON", 0);
let text = cadcraft_io::write_dxf(&d);
assert_eq!(active_ucsicon(&text).as_deref(), Some("0"), "written to the active VPORT");
assert!(header_var(&text, "UCSICON").is_empty(), "not a header variable");
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
assert_eq!(back.header.i64("UCSICON", 3), 0);
// And a value with the origin bit only.
d.header.set_i64("UCSICON", 2);
let text = cadcraft_io::write_dxf(&d);
assert_eq!(active_ucsicon(&text).as_deref(), Some("2"));
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().header.i64("UCSICON", 3), 2);
}
/// A file whose `*ACTIVE` VPORT says 74 = 0 opens with the icon off.
#[test]
fn ucsicon_reads_from_the_active_vport_group_74() {
let dxf = "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n70\n1\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n12\n6.0\n22\n4.5\n40\n9.0\n41\n1.6\n74\n0\n0\nENDTAB\n0\nENDSEC\n0\nEOF\n";
let d = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap();
assert_eq!(d.header.i64("UCSICON", 3), 0);
let on = dxf.replace("74\n0\n", "74\n3\n");
assert_eq!(cadcraft_io::read_dxf(on.as_bytes()).unwrap().header.i64("UCSICON", 3), 3);
}
+4 -9
View File
@@ -534,21 +534,16 @@ fn paint_pointer_overlay(
let view = frame.view;
// Acquired tracking points and the polar / tracking paths under the cursor.
if app.canvas.cursor.is_some() {
draw_tracking(painter, &xf, &app.session.tracking.acquired, app.canvas.track.as_ref(), view.height * 4.0, app.session.input_ucs().rotation());
draw_tracking(painter, &xf, &app.session.tracking.acquired, app.canvas.track.as_ref(), view.height * 4.0);
}
if let (Some(hit), Some(_)) = (app.canvas.snap, app.canvas.cursor) {
draw_snap_marker(painter, xf.to_screen(hit.point), &hit);
}
draw_tiles(app, ui, tiles);
// UCS icon, ViewCube and viewport label.
if app.session.ucsicon_bits() & 1 != 0 {
let place = crate::viewcube::IconPlace::of(app, rect, xf.twist, |p| xf.to_screen(p));
draw_ucs_icon(painter, &place);
// Clickable only at the Command prompt: while a command runs, a pick or a snap at the UCS
// origin (where the icon may sit) reaches the drawing.
if app.session.running.is_none() && app.session.pending_window.is_none() {
crate::viewcube::ucs_icon(app, ui, rect, &place);
}
if app.ui.show_ucs_icon {
draw_ucs_icon(painter, rect);
crate::viewcube::ucs_icon(app, ui, rect);
}
if app.ui.show_viewcube && sheet.is_none() {
draw_viewcube(app, ui, rect);
+5 -16
View File
@@ -63,23 +63,9 @@ pub(super) fn draw_snap_marker(p: &egui::Painter, at: Pos2, hit: &SnapHit) {
p.galley(r.min + vec2(3.0, 1.0), galley, Color32::BLACK);
}
/// The whole degrees (0–359) a tracking tooltip shows for the path `from` → `to`, measured from
/// the current UCS's X axis at `ucs` radians.
pub(super) fn tooltip_angle(from: Vec2, to: Vec2, ucs: f64) -> i64 {
((from.angle_to(to) - ucs).to_degrees().round() as i64).rem_euclid(360)
}
/// Acquired tracking points (small `+`, `//` for a Parallel line), the dotted paths the cursor
/// is on and the tooltip naming them ("Endpoint: 5.0000 < 90°").
/// `ucs`: the current UCS's X axis (radians), which the tooltips measure angles from.
pub(super) fn draw_tracking(
p: &egui::Painter,
xf: &Xf,
acquired: &[snap::tracking::Acquired],
track: Option<&snap::tracking::Track>,
far: f64,
ucs: f64,
) {
pub(super) fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64) {
use snap::tracking::{Acquired, PathShape};
let t = Tokens::get();
let st = Stroke::new(1.0, t.snap);
@@ -114,7 +100,10 @@ pub(super) fn draw_tracking(
}
};
p.extend(Shape::dotted_line(&pts, t.snap, 6.0, 1.0));
let (distance, angle) = (cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4), tooltip_angle(path.from, tr.point, ucs));
let (distance, angle) = (
cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4),
(path.from.angle_to(tr.point).to_degrees().round() as i64).rem_euclid(360),
);
tips.push(if path.name == "Polar" {
crate::tf!("Polar: {distance} < {angle}°", distance = distance, angle = angle)
} else {
+1 -1
View File
@@ -11,7 +11,7 @@ fn prim_color32(prim: &cadcraft_render::DPrim, bg: Rgb) -> Color32 {
Color32::from_rgba_unmultiplied(c.0, c.1, c.2, prim.alpha())
}
pub(super) fn clip_infinite(xf: &Xf, base: Vec2, dir: Vec2, ray: bool) -> Option<[Pos2; 2]> {
fn clip_infinite(xf: &Xf, base: Vec2, dir: Vec2, ray: bool) -> Option<[Pos2; 2]> {
let wb = xf.world_bounds();
let far = (wb.width() + wb.height()) * 2.0 + base.dist(wb.center());
let a = if ray { base } else { base - dir * far };
+11 -21
View File
@@ -1,4 +1,3 @@
use super::draw::clip_infinite;
use super::{Bounds2, CadApp, Shape, Stroke, Tokens, Vec2, Xf};
/// Grid spacing adapted to the zoom: multiply the unit until lines are at least `min_px` apart.
@@ -35,20 +34,14 @@ pub(super) fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) {
let unit = if s.gridunit.x == 0.0 { s.snapunit.x } else { s.gridunit.x };
let minor = adaptive(unit, xf.scale, 8.0);
let major = minor * major_n;
// Keep the visible grid's checked ranges in the snap frame, then map its lines through
// the UCS and the view (including its twist); the painter clips them to the viewport.
let space = app.session.space();
let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0));
let gb = Bounds2::from_points(wb.corners().map(|p| (p - origin).rotate(-angle)));
let world = |p: Vec2| origin + p.rotate(angle);
let mut lines = Vec::new();
if let Some(((x0, x1), (y0, y1))) = grid_index_ranges(&gb, minor) {
// Snap-frame lines across the visible box.
if let Some(((x0, x1), (y0, y1))) = grid_index_ranges(&wb, minor) {
// World-aligned lines across the visible box (the painter clips them to the rect).
for i in x0..=x1 {
let x = i as f64 * minor;
let is_major = (x / major).round() * major - x == 0.0 || ((x / major) - (x / major).round()).abs() < 1e-6;
lines.push(Shape::line_segment(
[xf.to_screen(world(Vec2::new(x, gb.min.y))), xf.to_screen(world(Vec2::new(x, gb.max.y)))],
[xf.to_screen(Vec2::new(x, wb.min.y)), xf.to_screen(Vec2::new(x, wb.max.y))],
Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }),
));
}
@@ -56,20 +49,19 @@ pub(super) fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) {
let y = j as f64 * minor;
let is_major = ((y / major) - (y / major).round()).abs() < 1e-6;
lines.push(Shape::line_segment(
[xf.to_screen(world(Vec2::new(gb.min.x, y))), xf.to_screen(world(Vec2::new(gb.max.x, y)))],
[xf.to_screen(Vec2::new(wb.min.x, y)), xf.to_screen(Vec2::new(wb.max.x, y))],
Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }),
));
}
}
p.extend(lines);
}
// The current UCS's X and Y axes through its origin.
let u = app.session.input_ucs();
let o = u.origin.xy();
for (dir, color) in [(u.x.xy(), t.axis_x), (u.y.xy(), t.axis_y)] {
if let Some(seg) = clip_infinite(xf, o, dir, false) {
p.line_segment(seg, Stroke::new(1.0, color));
}
// Axes through the origin.
if (wb.min.y..=wb.max.y).contains(&0.0) {
p.line_segment([xf.to_screen(Vec2::new(wb.min.x, 0.0)), xf.to_screen(Vec2::new(wb.max.x, 0.0))], Stroke::new(1.0, t.axis_x));
}
if (wb.min.x..=wb.max.x).contains(&0.0) {
p.line_segment([xf.to_screen(Vec2::new(0.0, wb.min.y)), xf.to_screen(Vec2::new(0.0, wb.max.y))], Stroke::new(1.0, t.axis_y));
}
}
@@ -86,9 +78,7 @@ fn draw_iso_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) {
}
d *= 5.0;
}
// In the current UCS (SNAPBASE from its origin, SNAPANG from its X axis).
let space = app.session.space();
let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0));
let (origin, angle) = app.session.doc().map(cadcraft_engine::snap::grid_frame).unwrap_or((Vec2::ZERO, 0.0));
let lines = iso::grid_lines(xf.world_bounds(), d, origin, angle, s.gridmajor);
p.extend(
lines.into_iter().map(|l| {
-17
View File
@@ -1,23 +1,6 @@
use super::cursor::tooltip_angle;
use super::*;
use cadcraft_render::DPrim;
/// Tracking tooltips give angles in the current UCS: a path along a UCS turned 30° reads 0°,
/// one along World X reads 330°, and the World UCS reads world angles.
#[test]
fn tooltip_angles_are_measured_from_the_ucs_x_axis() {
let o = Vec2::new(2.0, 1.0);
let at = |deg: f64| o + Vec2::from_angle(deg.to_radians()) * 5.0;
assert_eq!(tooltip_angle(o, at(90.0), 0.0), 90);
assert_eq!(tooltip_angle(o, at(-45.0), 0.0), 315);
let ucs = 30f64.to_radians();
assert_eq!(tooltip_angle(o, at(30.0), ucs), 0);
assert_eq!(tooltip_angle(o, at(0.0), ucs), 330);
assert_eq!(tooltip_angle(o, at(120.0), ucs), 90);
// A non-finite angle shows a number, not a panic.
assert!((0..360).contains(&tooltip_angle(o, o, f64::NAN)));
}
fn list(handles: &[u64]) -> DisplayList {
let prim =
|h| DPrim { handle: Handle(h), color: Rgb(255, 255, 255), aci7: true, lw: 0.0, transparency: 0, kind: Kind::Polyline, start: 0, len: 0 };
+12 -29
View File
@@ -48,23 +48,16 @@ pub(super) fn draw_lock(p: &egui::Painter, c: Pos2, color: Color32) {
));
}
/// The UCS icon: its X and Y arms along the current UCS's axes, with a square at the corner for
/// the World UCS.
pub(super) fn draw_ucs_icon(p: &egui::Painter, at: &crate::viewcube::IconPlace) {
pub(super) fn draw_ucs_icon(p: &egui::Painter, rect: Rect) {
let t = Tokens::get();
let (o, x, y) = (at.origin, at.x, at.y);
let arm = crate::viewcube::ARM;
let o = pos2(rect.left() + 36.0, rect.bottom() - 34.0);
let st = Stroke::new(1.0, t.canvas_ink);
p.line_segment([o, o + x * arm], st);
p.line_segment([o, o + y * arm], st);
if at.world {
let h = 4.5;
let square = vec![o + (x + y) * h, o + (x - y) * h, o - (x + y) * h, o - (x - y) * h];
p.add(Shape::closed_line(square, st));
}
p.line_segment([o, o + vec2(60.0, 0.0)], st);
p.line_segment([o, o + vec2(0.0, -60.0)], st);
p.rect_stroke(Rect::from_center_size(o, vec2(9.0, 9.0)), 0.0, st, egui::StrokeKind::Middle);
let f = egui::FontId::proportional(13.0);
p.text(o + x * (arm + 10.0), egui::Align2::CENTER_CENTER, crate::tl!("X"), f.clone(), t.canvas_ink);
p.text(o + y * (arm + 10.0), egui::Align2::CENTER_CENTER, crate::tl!("Y"), f, t.canvas_ink);
p.text(o + vec2(70.0, 0.0), egui::Align2::LEFT_CENTER, crate::tl!("X"), f.clone(), t.canvas_ink);
p.text(o + vec2(0.0, -70.0), egui::Align2::CENTER_BOTTOM, crate::tl!("Y"), f, t.canvas_ink);
}
pub(super) fn viewport_label(p: &egui::Painter, rect: Rect) {
@@ -75,14 +68,15 @@ pub(super) fn viewport_label(p: &egui::Painter, rect: Rect) {
pub(super) fn draw_viewcube(app: &mut CadApp, ui: &mut egui::Ui, rect: Rect) {
let l = crate::viewcube::Layout::new(rect);
let (c, ring) = (l.center, l.ring);
let p = ui.painter_at(rect);
crate::viewcube::show(app, ui, &l);
// UCS pill: the current UCS's name and a down chevron, drawn as lines rather than a "⌄"
// glyph that a UI font may lack (it showed as a box, #1541).
let pill = l.pill;
// WCS pill: the label and a down chevron, drawn as lines rather than a "⌄" glyph that a UI
// font may lack (it showed as a box, #1541).
let pill = Rect::from_center_size(c + vec2(0.0, ring + 26.0), vec2(56.0, 16.0));
p.rect_filled(pill, 8.0, Color32::from_rgb(0x48, 0x50, 0x5c));
let ink = Tokens::DARK.canvas_ink;
let label = p.layout_no_wrap(ucs_pill_text(app), crate::theme::small(), ink);
let label = p.layout_no_wrap(crate::tl!("WCS").to_string(), crate::theme::small(), ink);
let (gap, chevron) = (4.0, 6.0);
let left = pill.center().x - (label.size().x + gap + chevron) / 2.0;
let mid = pill.center().y;
@@ -90,14 +84,3 @@ pub(super) fn draw_viewcube(app: &mut CadApp, ui: &mut egui::Ui, rect: Rect) {
let x = left + label.size().x + gap;
p.line(vec![pos2(x, mid - 1.5), pos2(x + chevron / 2.0, mid + 1.5), pos2(x + chevron, mid - 1.5)], Stroke::new(1.2, ink));
}
/// The ViewCube pill's label: WCS, or the current UCS's name (cut short); the menu arrow is drawn
/// beside it as lines (#1541).
fn ucs_pill_text(app: &CadApp) -> String {
let (u, name) = app.session.ucs_named();
if u.is_world() && name.is_empty() {
return crate::tl!("WCS").to_string();
}
let n = if name.is_empty() { crate::tl!("Unnamed").to_string() } else { name };
if n.chars().count() > 8 { n.chars().take(7).chain(std::iter::once('…')).collect() } else { n }
}
+1 -2
View File
@@ -381,9 +381,8 @@ pub fn status_bar(app: &mut CadApp, ui: &mut egui::Ui) {
];
let size = 20.0;
let rx = r.right() - 8.0 - toggles.len() as f32 * (size + 4.0);
// Coordinates, in the current UCS.
// Coordinates.
let coord = app.canvas.cursor.map(|c| {
let c = app.session.ucs_point(c);
let (lu, lp) = app.session.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4));
format!(
"{}, {}, {}",
+1 -2
View File
@@ -57,8 +57,7 @@ pub fn dyn_frame(app: &CadApp) -> Option<crate::dyninput::Frame> {
return None;
}
let p = app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts)?;
let ucs = app.session.input_ucs();
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, ucs })
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute })
}
/// Take Tab away from egui before it moves keyboard focus to the next widget (which would leave
+14 -59
View File
@@ -48,8 +48,6 @@ pub struct Frame {
pub cartesian: bool,
/// DYNPICOORDS = 1: second and next points are absolute instead of relative.
pub absolute: bool,
/// The UCS the boxes read and show values in (the engine reads the sent text in it too).
pub ucs: cadcraft_engine::ucs::UcsFrame,
}
impl Frame {
@@ -57,11 +55,10 @@ impl Frame {
pub fn default_format(&self) -> Format {
if self.base.is_some() && !self.cartesian { Format::Polar } else { Format::Cartesian }
}
/// Where the typed values are measured from, in UCS coordinates: the last point, or the UCS
/// origin.
/// Where the typed values are measured from.
pub fn origin(&self) -> Vec2 {
match self.base {
Some(b) if !self.absolute => self.ucs.to_ucs(b),
Some(b) if !self.absolute => b,
_ => Vec2::ZERO,
}
}
@@ -70,9 +67,9 @@ impl Frame {
self.base.is_some() && !self.absolute
}
/// The live (X, Y) or (distance, angle in radians) of `cursor` (a world point), in the UCS.
/// The live (X, Y) or (distance, angle in radians) of `cursor`.
pub fn live(&self, format: Format, cursor: Vec2) -> (f64, f64) {
let d = self.ucs.to_ucs(cursor) - self.origin();
let d = cursor - self.origin();
match format {
Format::Cartesian => (d.x, d.y),
Format::Polar => (d.len(), d.y.atan2(d.x)),
@@ -148,35 +145,32 @@ pub fn can_lock_second(text: &str, frame: &Frame) -> bool {
/// when Tab has locked the second one too (`second_locked`), which pins the cursor to the point.
pub fn constrain(entry: &Entry<'_>, frame: &Frame, p: Vec2, second_locked: bool) -> Vec2 {
let Some(v) = entry.first_locked() else { return p };
// In UCS coordinates; `p` and the result are world points.
let (o, u) = (frame.origin(), frame.ucs.to_ucs(p));
let o = frame.origin();
if second_locked && let Some(w) = entry.second_value() {
let q = match entry.format {
Format::Cartesian => o + Vec2::new(v, w),
Format::Polar => o + Vec2::from_angle(w) * v,
};
if q.is_finite() {
return frame.ucs.to_wcs(q);
return q;
}
}
let q = match entry.format {
Format::Cartesian => Vec2::new(o.x + v, u.y),
match entry.format {
Format::Cartesian => Vec2::new(o.x + v, p.y),
Format::Polar => {
let d = u - o;
let d = p - o;
let l = d.len();
let dir = if l > 1e-12 { d * (1.0 / l) } else { Vec2::X };
o + dir * v
}
};
frame.ucs.to_wcs(q)
}
}
/// The command-line text to send for a finished entry, or `None` to send the text as typed
/// (nothing split yet: a plain number stays direct distance entry). Empty boxes take the cursor's
/// value. Entries measured from the last point are sent with `@` when the prompt's base is the
/// session's last point (`last`, what `@` resolves against); otherwise, and for absolute entries,
/// the finished point is sent as `#x,y` (UCS coordinates), so what was previewed is exactly what
/// is placed.
/// the finished point is sent as `#x,y`, so what was previewed is exactly what is placed.
pub fn complete(entry: &Entry<'_>, frame: &Frame, cursor: Vec2, last: Vec2) -> Option<String> {
if !entry.split {
return None;
@@ -187,8 +181,7 @@ pub fn complete(entry: &Entry<'_>, frame: &Frame, cursor: Vec2, last: Vec2) -> O
if frame.relative() && frame.base == Some(last) {
return Some(match entry.format {
Format::Cartesian => format!("@{first},{second}"),
// `<<`: degrees from the UCS X axis counterclockwise, as previewed, whatever
// ANGBASE/ANGDIR say.
// `<<`: degrees from +X counterclockwise, as previewed, whatever ANGBASE/ANGDIR say.
Format::Polar => format!("@{first}<<{}", second.to_degrees()),
});
}
@@ -237,7 +230,7 @@ mod tests {
use super::*;
fn second_point(base: Vec2) -> Frame {
Frame { base: Some(base), cartesian: false, absolute: false, ..Frame::default() }
Frame { base: Some(base), cartesian: false, absolute: false }
}
fn sent(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option<Vec2> {
@@ -275,44 +268,6 @@ mod tests {
assert_eq!(tab_separator("rec", &polar), None);
}
/// `sent` with the engine reading the text in the frame's UCS, as the command line does.
fn sent_in(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option<Vec2> {
let e = parse(text, frame)?;
let t = complete(&e, frame, cursor, last)?;
let angles = cadcraft_engine::units::AngleSettings { ucs: frame.ucs.rotation(), ..Default::default() };
cadcraft_engine::prompt::parse_point_in(&t, last, &angles, &frame.ucs)
}
#[test]
fn the_boxes_read_and_show_values_in_the_ucs() {
// The UCS at (100, 50) turned 90°: UCS X is world +Y.
let ucs =
cadcraft_engine::ucs::UcsFrame::WORLD.with_origin(cadcraft_geom::Vec3::new(100.0, 50.0, 0.0)).rotated_z(std::f64::consts::FRAC_PI_2);
let first = Frame { ucs, ..Frame::default() };
assert!(close(sent_in("10,0", &first, Vec2::ZERO, Vec2::ZERO), Vec2::new(100.0, 60.0)), "absolute: from the UCS origin");
let base = Vec2::new(100.0, 60.0);
let f = Frame { base: Some(base), ucs, ..Frame::default() };
assert!(close(sent_in("5,0", &f, Vec2::ZERO, base), Vec2::new(100.0, 65.0)), "relative along the UCS axes");
assert!(close(sent_in("10<0", &f, Vec2::ZERO, base), Vec2::new(100.0, 70.0)), "angles from the UCS X axis");
assert!(close(sent_in("10<90", &f, Vec2::ZERO, base), Vec2::new(90.0, 60.0)));
// Not relative to the last point: sent as `#x,y` in the UCS, placed where it was previewed.
assert!(close(sent_in("5,0", &f, Vec2::ZERO, Vec2::new(-1.0, -1.0)), Vec2::new(100.0, 65.0)));
let abs = Frame { absolute: true, cartesian: true, ..f };
assert!(close(sent_in("10,5", &abs, Vec2::ZERO, base), Vec2::new(95.0, 60.0)));
// The live values are the cursor's, measured in the UCS.
let (x, y) = f.live(Format::Cartesian, Vec2::new(97.0, 70.0));
assert!((x - 10.0).abs() < 1e-9 && (y - 3.0).abs() < 1e-9, "{x} {y}");
let (d, a) = f.live(Format::Polar, Vec2::new(100.0, 70.0));
assert!((d - 10.0).abs() < 1e-9 && a.abs() < 1e-9, "{d} {a}");
// A locked value holds the cursor along the UCS axes, and Enter sends that point.
let e = parse("3,", &f).unwrap();
let held = constrain(&e, &f, Vec2::new(80.0, 99.0), false);
assert!(close(Some(held), Vec2::new(80.0, 63.0)), "{held:?}");
assert!(close(sent_in("3,", &f, Vec2::new(80.0, 99.0), base), Vec2::new(80.0, 63.0)));
let e = parse("4<", &f).unwrap();
assert!(close(Some(constrain(&e, &f, Vec2::new(100.0, 90.0), false)), Vec2::new(100.0, 64.0)));
}
#[test]
fn first_point_is_absolute() {
let f = Frame::default();
@@ -321,7 +276,7 @@ mod tests {
#[test]
fn absolute_setting_measures_from_the_origin() {
let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true, ..Frame::default() };
let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true };
assert!(close(sent("40,100", &f, Vec2::ZERO, Vec2::new(5.0, 5.0)), Vec2::new(40.0, 100.0)));
}
+2 -2
View File
@@ -309,8 +309,8 @@ mod tests {
for cartesian in [true, false] {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynpi_cartesian = cartesian;
// The UCS icon paints "X" and "Y" too: off (UCSICON, which the drawing keeps).
app.run("ucsicon", serde_json::json!({"on": false})).unwrap();
// The UCS icon paints "X" and "Y" too.
app.ui.show_ucs_icon = false;
let ctx = egui::Context::default();
crate::canvas::tests::painted_text(&mut app, &ctx, pos2(700.0, 450.0));
let at = app.canvas.xf.unwrap().to_screen(Vec2::ZERO) + vec2(130.0, -70.0);
-8
View File
@@ -1356,14 +1356,6 @@
Justify За шириною
Text color Колір тексту
Click the ruler to add a tab stop, right-click to remove one Натисніть на лінійку, щоб додати табуляцію; права кнопка видаляє її
3 Point 3 точки
New UCS Нова СКК
Origin Початок координат
UCS СКК
UCS Icon at Origin Піктограма СКК на початку координат
World Світова
Z Z
Unnamed Без назви
Select using two clicks only Вибирати лише двома клацаннями
Define each corner of the selection window with a separate click. Задайте кожен кут рамки вибору окремим клацанням.
Type an alias name. Введіть назву псевдоніма.
1 # CADCraft Ukrainian interface catalog — original translations by @dmatviichuk.
1356
1357
1358
1359
1360
1361
-7
View File
@@ -1503,13 +1503,6 @@ menu Dimension 标注
menu Draw 绘图
menu Modify 修改
menu View 视图
3 Point 三点
New UCS 新建 UCS
Origin 原点
UCS UCS
UCS Icon at Origin 原点处的 UCS 图标
World 世界
Z Z
Clip Xref 剪裁外部参照
Xref 外部参照
Xref Clip Frame 外部参照剪裁边框
Can't render this file because it contains an unexpected character in line 1472 and column 24.
+2
View File
@@ -103,6 +103,7 @@ pub struct UiState {
pub show_status_bar: bool,
pub show_command_line: bool,
pub show_viewcube: bool,
pub show_ucs_icon: bool,
pub show_layer_list: bool,
/// Keep the system cursor visible over the drawing area (a small crosshair at the centre of the
/// drawn one) instead of hiding it. Screen magnifiers (Windows Magnifier "follow the mouse
@@ -200,6 +201,7 @@ impl Default for UiState {
show_status_bar: true,
show_command_line: true,
show_viewcube: true,
show_ucs_icon: true,
show_layer_list: false,
system_cursor: false,
toolset_tab: "Drafting".into(),
+4 -14
View File
@@ -102,7 +102,6 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
("ui.toggle.cmdline", "Command Line", &["Window", "Command Line"], Some("Cmd+9")),
("ui.toggle.viewcube", "ViewCube", &["View", "ViewCube", "On"], None),
("ui.toggle.ucsicon", "UCS Icon", &["View", "UCS Icon", "On"], None),
("ui.toggle.ucsicon.origin", "UCS Icon at Origin", &["View", "UCS Icon", "Origin"], None),
("ui.theme.system", "Use System Setting", &["View", "Interface Theme", "Use System Setting"], None),
("ui.theme.light", "Light", &["View", "Interface Theme", "Light"], None),
("ui.theme.dark", "Dark", &["View", "Interface Theme", "Dark"], None),
@@ -308,16 +307,9 @@ fn run_ui_toggle_command(app: &mut CadApp, id: &str, params: &Value) -> Option<R
toggle(&mut app.ui.show_viewcube, params);
Ok(Value::Null)
}
// UCSICON's bits, through its command: 1 shown, 2 at the UCS origin.
"ui.toggle.ucsicon" | "ui.toggle.ucsicon.origin" => {
// The icon is a setting of the drawing: with none open there is nothing to toggle.
if app.session.doc().is_err() {
return Some(Err("No drawing open.".into()));
}
let (key, bit) = if id == "ui.toggle.ucsicon" { ("on", 1) } else { ("origin", 2) };
let mut on = app.session.ucsicon_bits() & bit != 0;
toggle(&mut on, params);
app.run("ucsicon", json!({ key: on }))
"ui.toggle.ucsicon" => {
toggle(&mut app.ui.show_ucs_icon, params);
Ok(Value::Null)
}
"ui.toggle.menubar" => {
toggle(&mut app.ui.in_window_menu, params);
@@ -700,9 +692,7 @@ pub fn tree(app: &CadApp) -> Vec<(String, Vec<Entry>)> {
}
for (id, label, menu, sc) in UI_COMMANDS {
if !menu.is_empty() {
// The UCS icon is a setting of the drawing: off the menu's reach when none is open.
let enabled = !id.starts_with("ui.toggle.ucsicon") || app.session.doc().is_ok();
add(menu, label, id, *sc, enabled);
add(menu, label, id, *sc, true);
}
}
if let Some((_, file)) = out.iter_mut().find(|(m, _)| m == "File") {
+28 -241
View File
@@ -1,14 +1,14 @@
//! The navigation overlays on the drawing area: the ViewCube (Top face, Home, compass ring and
//! the UCS menu) and the UCS icon.
//! the WCS menu) and the UCS icon.
//!
//! Every overlay registers a widget that senses clicks *and* drags, so egui hands the pointer to
//! the overlay instead of the canvas underneath (a click on the ViewCube must never also pick or
//! start a selection window in the drawing). What the overlays do goes through commands:
//! `zoom.extents` (Top face, Home), `ui.toggle.viewcube`, `ui.toggle.ucsicon`, `ucs`.
//! `zoom.extents` (Top face, Home), `ui.toggle.viewcube`, `ui.toggle.ucsicon`.
//!
//! CADCraft's model view is a 2D plan view: there is no view twist and no 3D view direction yet,
//! so the compass ring explains that instead of rotating. The UCS menu lists World and the
//! drawing's named UCSs.
//! CADCraft's model view is a 2D plan view of the World Coordinate System: there is no view
//! twist, no 3D view direction and no user coordinate system yet, so the compass ring explains
//! that instead of rotating, and the WCS menu lists the only coordinate system there is.
use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, pos2, vec2};
use serde_json::json;
@@ -42,7 +42,7 @@ impl Layout {
ring,
face: Rect::from_center_size(center, vec2(44.0, 44.0)),
home: Rect::from_center_size(center + vec2(-ring + 2.0, -ring + 2.0), vec2(20.0, 20.0)),
pill: Rect::from_center_size(center + vec2(0.0, ring + 26.0), vec2(84.0, 16.0)),
pill: Rect::from_center_size(center + vec2(0.0, ring + 26.0), vec2(56.0, 16.0)),
bounds: Rect::from_center_size(center, vec2(2.0 * (ring + 10.0), 2.0 * (ring + 10.0))),
}
}
@@ -131,8 +131,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, l: &Layout) {
if let Some((id, params)) = action {
let _ = app.run(id, params);
}
// The UCS pill (painted by the canvas, wide enough for a cut-short UCS name) opens the
// coordinate-system menu.
// The WCS pill (painted by the canvas) opens the coordinate-system menu.
let pill = ui.interact(l.pill, ui.scope_id().with("viewcube_wcs"), Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand);
let pill = pill.on_hover_text("Coordinate system");
ucs_menu(app, egui::Popup::menu(&pill));
@@ -154,164 +153,48 @@ fn paint_home(p: &egui::Painter, r: Rect, hot: bool) {
p.line_segment([c + vec2(-1.2, 2.5), c + vec2(1.2, 2.5)], st);
}
/// How long the UCS icon's arms are, in points.
pub const ARM: f32 = 60.0;
/// How far past an arm's end its X or Y label reaches, in points.
const LABEL: f32 = 16.0;
/// How close to an arm a pointer counts as on the icon, in points.
const HIT: f32 = 8.0;
/// Where the UCS icon is drawn: the point its arms start from, the screen directions of its X
/// and Y arms (unit vectors: the current UCS's axes seen in the plan view) and whether the UCS is
/// the World UCS (the icon then has a square at its corner).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IconPlace {
pub origin: Pos2,
pub x: egui::Vec2,
pub y: egui::Vec2,
pub world: bool,
}
impl IconPlace {
/// The World UCS's icon at the lower-left corner of the drawing area.
pub fn corner(canvas: Rect) -> IconPlace {
IconPlace { origin: pos2(canvas.left() + 36.0, canvas.bottom() - 34.0), x: vec2(1.0, 0.0), y: vec2(0.0, -1.0), world: true }
}
/// The icon for the current UCS: at its origin when UCSICON asks for that (ORigin) and the
/// whole icon fits there, else at the corner. `to_screen` maps a point of the space shown, and
/// `twist` is the view's twist (radians counterclockwise, `Xf::twist`).
pub fn of(app: &CadApp, canvas: Rect, twist: f64, to_screen: impl Fn(cadcraft_geom::Vec2) -> Pos2) -> IconPlace {
let u = app.session.input_ucs();
// An axis as the screen shows it: a twisted view (DVIEW TWist) turns the arms too.
let dir = |v: cadcraft_geom::Vec3, or: egui::Vec2| {
let t = if twist.is_finite() && twist != 0.0 { v.xy().rotate(twist) } else { v.xy() };
let d = vec2(t.x as f32, -(t.y as f32));
let l = d.length();
if l.is_finite() && l > 1e-6 { d / l } else { or }
};
let mut place = IconPlace::corner_turned(canvas, dir(u.x, vec2(1.0, 0.0)), dir(u.y, vec2(0.0, -1.0)), u.is_world());
// At the origin only where the screen shows the space the UCS belongs to (not from paper
// space into an active viewport).
let same_space = app.session.space() == app.session.layout_space();
if app.session.ucsicon_bits() & 2 != 0 && same_space {
let at = to_screen(u.origin.xy());
let reach = ARM + LABEL;
let inner = canvas.shrink(12.0);
if [at, at + place.x * reach, at + place.y * reach].iter().all(|p| p.x.is_finite() && p.y.is_finite() && inner.contains(*p)) {
place.origin = at;
}
}
place
}
/// The icon with arms along `x` and `y` at the lower-left corner: placed so the arms and their
/// labels take the corner the World UCS's icon does, whichever way they point.
pub fn corner_turned(canvas: Rect, x: egui::Vec2, y: egui::Vec2, world: bool) -> IconPlace {
let home = IconPlace::corner(canvas).origin;
let reach = ARM + LABEL;
let (ends_x, ends_y) = ([0.0, x.x * reach, y.x * reach], [0.0, x.y * reach, y.y * reach]);
// The World icon's arms run right and up from `home`: shift so the turned arms' left and
// bottom edges sit where those do.
let left = ends_x.iter().copied().fold(0.0f32, f32::min);
let bottom = ends_y.iter().copied().fold(0.0f32, f32::max);
let origin = pos2(home.x - left, home.y - bottom);
IconPlace { origin: if origin.x.is_finite() && origin.y.is_finite() { origin } else { home }, x, y, world }
}
/// The icon's arms out to their labels: the X arm and the Y arm, as screen segments.
pub fn arms(&self) -> [[Pos2; 2]; 2] {
let o = self.origin;
[[o, o + self.x * (ARM + 20.0)], [o, o + self.y * (ARM + 22.0)]]
}
/// Whether `p` is on the icon: within [`HIT`] of an arm (labels included), not merely in the
/// box around a turned arm.
pub fn hit(&self, p: Pos2) -> bool {
self.arms().iter().any(|[a, b]| {
let ab = *b - *a;
let t = if ab.length_sq() > 0.0 { ((p - *a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
(*a + ab * t - p).length() <= HIT
})
}
}
/// How the current UCS is named on screen.
fn ucs_label(app: &CadApp) -> String {
let (u, name) = app.session.ucs_named();
if u.is_world() && name.is_empty() {
"World Coordinate System".into()
} else if name.is_empty() {
"Unnamed UCS".into()
} else {
name
}
/// The UCS icon's arms (as drawn by the canvas at the lower-left corner): the X arm and the Y arm.
pub fn ucs_arms(canvas: Rect) -> [Rect; 2] {
let o = pos2(canvas.left() + 36.0, canvas.bottom() - 34.0);
[Rect::from_min_max(o + vec2(-8.0, -8.0), o + vec2(80.0, 8.0)), Rect::from_min_max(o + vec2(-8.0, -82.0), o + vec2(8.0, 8.0))]
}
/// Make the UCS icon clickable: hovering highlights it, a click (either button) opens the
/// coordinate-system menu.
pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect, place: &IconPlace) {
pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) {
let t = Tokens::get();
// The arms' boxes, but only a pointer near an arm takes clicks (a turned arm's box is mostly
// drawing). The widget stays every frame so its menu, once open, keeps its anchor.
let near = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| place.hit(p));
let sense = if near { Sense::click_and_drag() } else { Sense::hover() };
let [x, y] = place.arms().map(|[a, b]| Rect::from_two_pos(a, b).expand(HIT));
let rx = ui.interact(x, ui.scope_id().with("ucs_x"), sense);
let ry = ui.interact(y, ui.scope_id().with("ucs_y"), sense);
let mut resp = rx | ry;
if near {
resp = resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(format!("UCS icon: {}", ucs_label(app)));
}
if near && resp.hovered() {
let o = place.origin;
let [x, y] = ucs_arms(canvas);
let rx = ui.interact(x, ui.scope_id().with("ucs_x"), Sense::click_and_drag());
let ry = ui.interact(y, ui.scope_id().with("ucs_y"), Sense::click_and_drag());
let resp = (rx | ry).on_hover_cursor(CursorIcon::PointingHand).on_hover_text("UCS icon: World Coordinate System");
if resp.hovered() {
let o = pos2(x.left() + 8.0, x.center().y);
let st = Stroke::new(2.0, t.hover);
let p = ui.painter_at(canvas);
p.line_segment([o, o + place.x * ARM], st);
p.line_segment([o, o + place.y * ARM], st);
p.line_segment([o, o + vec2(60.0, 0.0)], st);
p.line_segment([o, o + vec2(0.0, -60.0)], st);
}
// Opened with `Bool(true)`: a pointer-anchored popup records its position only then.
let open = (resp.clicked() || resp.secondary_clicked()).then_some(egui::SetOpenCommand::Bool(true));
ucs_menu(app, egui::Popup::menu(&resp).open_memory(open).at_pointer_fixed());
}
/// The coordinate-system menu: World, the drawing's named UCSs (picking one makes it current,
/// through the UCS command) and the icon switch.
/// The coordinate-system menu: the WCS (the only coordinate system so far) and the icon switch.
fn ucs_menu(app: &mut CadApp, popup: egui::Popup<'_>) {
let (u, current) = app.session.ucs_named();
let names: Vec<String> = app.session.doc().map(|d| d.ucss.iter().map(|u| u.name.clone()).collect()).unwrap_or_default();
let mut action: Option<(&str, serde_json::Value)> = None;
let mut hide = false;
popup.show(|ui| {
if ui.radio(u.is_world() && current.is_empty(), "World (WCS)").clicked() {
action = Some(("ucs.world", json!({})));
ui.close();
}
for n in &names {
if ui.radio(current.eq_ignore_ascii_case(n), n.as_str()).clicked() {
action = Some(("ucs", json!({"option": "named", "action": "restore", "name": n})));
ui.close();
}
}
if !u.is_world() && current.is_empty() {
let _ = ui.radio(true, "Unnamed");
}
ui.radio(true, "World (WCS)").on_hover_text("CADCraft draws in the World Coordinate System; user coordinate systems aren't available yet.");
ui.separator();
if ui.button("Hide UCS Icon").clicked() {
action = Some(("ui.toggle.ucsicon", json!({"on": false})));
hide = true;
ui.close();
}
});
if let Some((id, params)) = action {
menu_action(app, id, params);
if hide {
let _ = app.run("ui.toggle.ucsicon", json!({"on": false}));
}
}
/// Run a coordinate-system menu pick. A failure is already in the command history:
/// [`CadApp::run`] echoes it (and the icon switch runs UCSICON through it).
fn menu_action(app: &mut CadApp, id: &str, params: serde_json::Value) {
let _ = app.run(id, params);
}
#[cfg(test)]
mod tests {
use super::*;
@@ -355,22 +238,6 @@ mod tests {
app.canvas.rect.unwrap_or(Rect::NOTHING)
}
/// A menu pick that fails (a tilted named UCS) tells the user once, not twice.
#[test]
fn a_failed_menu_pick_is_reported_once() {
let (mut app, _ctx) = app_and_ctx();
let tilted = cadcraft_engine::doc::Ucs {
name: "T".into(),
origin: cadcraft_engine::geom::Vec3::ZERO,
x_axis: cadcraft_engine::geom::Vec3::new(1.0, 0.0, 0.0),
y_axis: cadcraft_engine::geom::Vec3::new(0.0, 0.0, 1.0),
};
app.session.doc_mut().unwrap().ucss.push(tilted);
menu_action(&mut app, "ucs", json!({"option": "named", "action": "restore", "name": "T"}));
let told = app.session.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count();
assert_eq!(told, 1, "{:?}", app.session.log);
}
fn view(app: &CadApp) -> (f64, f64, f64) {
let v = app.session.state().map(|s| s.view()).unwrap_or_default();
(v.center.x, v.center.y, v.height)
@@ -414,91 +281,11 @@ mod tests {
assert!(app.session.pending_window.is_some(), "an empty-space click starts a selection window");
}
#[test]
fn the_ucs_icon_follows_the_ucs() {
let (mut app, _ctx) = app_and_ctx();
let c = canvas(&app);
// A plain mapping: the canvas centre is world (0, 0), one point per unit.
let to_screen = |p: cadcraft_geom::Vec2| pos2(c.center().x + p.x as f32, c.center().y - p.y as f32);
let world = IconPlace::of(&app, c, 0.0, to_screen);
assert!(world.world && (world.x - vec2(1.0, 0.0)).length() < 1e-6 && (world.y - vec2(0.0, -1.0)).length() < 1e-6);
// At the World origin (on screen, with ORigin on by default).
assert!((world.origin - c.center()).length() < 1e-3, "{:?} vs {:?}", world.origin, c.center());
// A view twisted 90° (DVIEW TWist) turns the arms with the drawing: world X points up.
let twisted = IconPlace::of(&app, c, std::f64::consts::FRAC_PI_2, to_screen);
assert!((twisted.x - vec2(0.0, -1.0)).length() < 1e-6 && (twisted.y - vec2(-1.0, 0.0)).length() < 1e-6, "{twisted:?}");
// A UCS turned 90° at (20, 10): the X arm points up the screen, the Y arm left.
app.run("ucs", json!({"option": "origin", "origin": [20, 10]})).unwrap();
app.run("ucs", json!({"option": "z", "angle": 90})).unwrap();
let p = IconPlace::of(&app, c, 0.0, to_screen);
assert!(!p.world);
assert!((p.x - vec2(0.0, -1.0)).length() < 1e-6 && (p.y - vec2(-1.0, 0.0)).length() < 1e-6, "{p:?}");
assert!((p.origin - pos2(c.center().x + 20.0, c.center().y - 10.0)).length() < 1e-3);
// Its click areas lie along the turned arms.
assert!(p.hit(p.origin + p.x * 40.0) && p.hit(p.origin + p.y * 40.0));
// Noorigin, or an origin off screen: the corner, the turned icon in the World icon's place.
let corner = IconPlace::corner_turned(c, p.x, p.y, false).origin;
app.run("ucsicon", json!({"origin": false})).unwrap();
assert_eq!(IconPlace::of(&app, c, 0.0, to_screen).origin, corner);
app.run("ucsicon", json!({"origin": true})).unwrap();
app.run("ucs", json!({"option": "origin", "origin": [1e6, 0]})).unwrap();
assert_eq!(IconPlace::of(&app, c, 0.0, to_screen).origin, corner);
app.run("ucs", json!({"option": "world"})).unwrap();
app.run("ucs", json!({"option": "origin", "origin": [1e6, 0]})).unwrap();
assert_eq!(IconPlace::of(&app, c, 0.0, to_screen).origin, IconPlace::corner(c).origin, "unturned: where it always was");
// The menu switch turns UCSICON off through its command.
app.run("ui.toggle.ucsicon", json!({"on": false})).unwrap();
assert_eq!(app.session.ucsicon_bits() & 1, 0);
app.run("ui.toggle.ucsicon", json!({})).unwrap();
assert_eq!(app.session.ucsicon_bits() & 1, 1, "a toggle without `on` flips it");
app.run("ui.toggle.ucsicon.origin", json!({"on": false})).unwrap();
assert_eq!(app.session.ucsicon_bits(), 1);
}
/// At the corner, a turned icon's arms and labels stay on the canvas at every angle, inside
/// the World icon's corner box.
#[test]
fn a_turned_corner_icon_stays_on_the_canvas() {
let c = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0));
let home = IconPlace::corner(c).origin;
let reach = ARM + LABEL;
let (box_left, box_bottom) = (home.x, home.y);
for deg in (0..360).step_by(15) {
let a = (deg as f32).to_radians();
// Screen y runs down: the Y arm is the X arm turned a quarter counterclockwise on screen.
let (x, y) = (vec2(a.cos(), -a.sin()), vec2(-a.sin(), -a.cos()));
let p = IconPlace::corner_turned(c, x, y, false);
for end in [p.origin, p.origin + x * reach, p.origin + y * reach] {
assert!(c.contains(end), "{deg}°: {end:?} off {c:?}");
assert!(end.x >= box_left - 1e-3 && end.y <= box_bottom + 1e-3, "{deg}°: {end:?}");
}
}
// Unturned, exactly where the World icon always was.
assert_eq!(IconPlace::corner_turned(c, vec2(1.0, 0.0), vec2(0.0, -1.0), true).origin, home);
}
/// Only a pointer near an arm is on the icon: on a 45° UCS the corner of the arm's box, well
/// away from the arm, is drawing.
#[test]
fn ucs_icon_hits_follow_the_arms_not_their_boxes() {
let s = std::f32::consts::FRAC_1_SQRT_2;
let p = IconPlace { origin: pos2(200.0, 200.0), x: vec2(s, -s), y: vec2(-s, -s), world: false };
assert!(p.hit(p.origin) && p.hit(p.origin + p.x * 50.0) && p.hit(p.origin + p.y * (ARM + 20.0)));
assert!(p.hit(p.origin + p.x * 30.0 + p.y * 7.0), "within reach of the X arm");
// The X arm's box spans 200..257 across; its far corner is 40 points from the arm.
let box_corner = pos2(200.0 + (ARM + 20.0) * s, 200.0);
assert!(!p.hit(box_corner), "{box_corner:?}");
assert!(!p.hit(p.origin + p.x * (ARM + 40.0)), "past the label");
assert!(!p.hit(pos2(f32::NAN, 0.0)));
}
#[test]
fn ucs_icon_and_wcs_pill_open_the_coordinate_system_menu() {
let (mut app, ctx) = app_and_ctx();
// Where the canvas drew it: at the World origin when that is on screen (UCSICON 3).
let xf = app.canvas.xf.expect("laid out");
let place = IconPlace::of(&app, canvas(&app), xf.twist, |p| xf.to_screen(p));
click(&mut app, &ctx, place.origin + place.x * 40.0, egui::PointerButton::Primary);
let [x, _] = ucs_arms(canvas(&app));
click(&mut app, &ctx, x.center(), egui::PointerButton::Primary);
assert!(menu_shown(&ctx), "UCS icon menu");
assert!(app.session.pending_window.is_none(), "the click stayed on the icon");
let l = Layout::new(canvas(&app));
+1 -1
View File
@@ -27,10 +27,10 @@ impl Canvas {
session.execute("view.set", &json!({"center": [100, 100], "height": 400})).unwrap();
session.settings.gridmode = false;
session.settings.dynmode = false;
session.execute("ucsicon", &json!({"on": false})).unwrap();
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
app.ui.show_command_line = false;
app.ui.show_ucs_icon = false;
app.ui.show_viewcube = false;
app.run("options", json!({"theme": "dark", "systemCursor": false, "PICKBOX": 4, "SELECTIONPREVIEW": 1})).unwrap();
let mut canvas = Self { app, ctx: Context::default(), previous_theme };
+1 -1
View File
@@ -69,7 +69,7 @@ reached", malformed source is a reader error, and every built-in checks its argu
`vl-string-search vl-string-subst vl-string-trim vl-string-left-trim vl-string-right-trim
vl-string-translate vl-string->list vl-list->string vl-prin1-to-string vl-princ-to-string
vl-symbol-name vl-symbol-value vl-filename-base vl-filename-extension vl-filename-directory`
- **Geometry:** `polar distance angle inters trans` (`trans` between the WCS (0), the current UCS (1), display coordinates (2, 3: the WCS in a plan view) and an object's OCS (an entity name or an extrusion direction); `getpoint` and friends answer in the current UCS and `command` takes UCS points, while entity lists stay in world coordinates)
- **Geometry:** `polar distance angle inters trans` (`trans` returns the point: no UCS yet)
- **Output and files:** `princ prin1 print prompt terpri alert open close read-line write-line
findfile`
- **Errors:** `*error*`, `vl-catch-all-apply vl-catch-all-error-p vl-catch-all-error-message`