Compare commits

..
49 Commits
Author SHA1 Message Date
Tanish Manku 198c36b406 Merge #2765: images refuse oversized data before decoding 2026-11-19 15:33:03 -07:00
Tanish Manku 2101a81d62 Merge #2821: hostile-input fixes for SVG import and AutoLISP step accounting
No textual conflict, but main's #2072 (Nov 18) and this PR both fixed the
transformed-ellipse axis: #2072 takes the eigenvector of B*B^T (a drawing-
plane direction), this PR the eigenvector of B^T*B mapped through B. The
clean merge mixed the two (B*B^T's eigenvector mapped through B again).
Kept #2072's computation and this PR's convention that `major` is the axis
from the centre: major = axis * s_max. #2072's test measured `major - centre`
(the old absolute-point convention); it now reads `major` itself.
2026-11-19 15:32:44 -07:00
Tanish Manku 2827ccb6c8 Merge #2820: SHX fonts: a points bound on the glyph cache 2026-11-19 15:31:26 -07:00
Tanish Manku 8ec1e9a0a5 Stack t1: #1276: the reader's band reservations end with the read
reserved_handles only bridges a record read before its section is placed.
Kept on the drawing it was cloned with every undo snapshot, one entry per
band handle a file names. Once every record is placed the objects keep their
handles from new ones themselves, so the reader empties it.
2026-11-19 15:30:55 -07:00
Tanish Manku b184454275 Stack t1: #1276: run the exhausted-handles DXF round trip (#1921)
The writer now numbers its records past the top of the range in the
reserved band, skipping the drawing's handles, so the save no longer
repeats the model space record's handle.
2026-11-19 15:30:10 -07:00
Tanish Manku 077c054d18 Stack t1: #1276: bound the writer's handle walk
W::next_handle looped until it found a free handle; with the wrap into the
reserved band it could only end by finding one. Bound it by the count of
handles in use, as Drawing::next_handle is. Not reachable in practice (it
needs four billion objects), so there is no test.
2026-11-19 15:29:58 -07:00
Tanish Manku 5eafcc93bb Stack t1: #1276: records added on save after the top handle take free handles
Kept objects and missing application ids are numbered above the largest
handle written. When a file's object holds FFFFFFFFFFFFFFFF that count
saturated, so every added record was written with the object's handle.
Number them past the top in the reserved band instead, skipping handles
already written, with the walk bounded by their count.
2026-11-19 15:29:48 -07:00
Tanish Manku 7c366f7b5a Merge #1276: a handle at the top of the range leaves new objects their own
Conflict in Drawing::new_handle/next_handle with #2514. The resolution keeps
both rules: next_handle (HANDSEED) skips the handles of the file's objects
CADCraft rewrites (foreign.handles, #2514), and in the reserved band above
HANDLE_LIMIT also every handle an object or a reserved file record holds
(#913, #1921); off the top of the range it continues at the bottom of the
band, and new_handle takes exactly what next_handle reports.

The scan over all spaces and block definitions runs only for a candidate in
the band: below it the seed is kept above every object's handle. The walk is
bounded by the count of held handles, counted only once a handle is skipped.
2026-11-19 15:29:11 -07:00
moandClaude Opus 5.5 a39d637814 Merge remote-tracking branch 'origin/main' into parsers-hostile
crates/io/src/svg_read.rs is taken from main (c07b6a2f, the craft-svg based reader) and every SVG fix of this branch is re-applied on top of it, since all of them sit in the conversion of craft-svg's neutral_document shapes into entities, which stays on the cadcraft side: in add_rounded, the ellipse's major axis is the image B*v of the leading eigenvector (relative to the centre, so a rotated ellipse keeps its turn and a sheared circle gets the axes of its image) and the near-orthogonal test scales with the trace instead of a floor of 1 (tiny sheared circle); in add, an entity whose coordinates or extents are not finite (finite, box_finite, bulges_finite) is left out after it is charged against the vertex budget, and counted for a read note of its own, made by notes() apart from the note on what isn't read yet. Nothing is dropped: craft-svg's neutral_document::visit and path_data::parse_path only refuse non-finite numbers as written, not relative steps or transforms that overflow them; the overflow checks of craft-libs#881 (paths.rs, smooth_segments_after_a_close_relative_root_sizes_and_overflowing_steps) cover craft-svg's own paths::import, which cadcraft does not use. Against main's svg_read.rs alone, svg_ellipse_major_axis_is_relative_to_its_centre, svg_rotated_ellipse_keeps_its_turn, svg_sheared_circle_has_the_axes_of_its_image, svg_tiny_sheared_circle_has_the_axes_of_its_image, svg_coordinates_that_overflow_are_left_out, svg_shapes_whose_extents_overflow_are_left_out, svg_too_large_shapes_are_noted_apart_from_unread_content and svg_shapes_become_entities_in_millimetres fail; with the fixes re-applied they pass unchanged. No test is changed or removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:28:18 -05:00
moandClaude Opus 5.5 dc7e5cdd6e Merge remote-tracking branch 'origin/main' into shx-hostile
Main's SHX compiler, container reader and glyph interpreter now come from
craft-shx (#3193, #3194, #3195), so this branch's changes to compile.rs,
parse.rs and program.rs are dropped here (they move to a craft-libs pull
request) and only the points-budgeted glyph cache in mod.rs remains. The
tests of the moved code are removed with it:
a_far_extended_subshape_cell_is_cut_off,
subshape_fan_out_past_the_point_and_step_bounds_is_cut_off,
a_name_is_looked_for_in_its_first_kilobyte_only,
a_name_the_reader_would_drop_does_not_compile,
all_65535_shape_numbers_compile_and_a_repeat_is_found and
a_doubled_minus_sign_is_not_a_number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:21:35 -05:00
midasmatterhorn e4f9b6aae3 io: the helper also checks the owner of the handle below the band 2026-11-15 22:03:05 +03:00
midasmatterhorn 140437e78e io: reserve a file's band handles before numbering handle-less entities
The handle pre-scan moves the seed past a file's ordinary handles, but
bump_handseed deliberately does not follow one at or above HANDLE_LIMIT
(#913). A handle-less entity read earlier is therefore numbered with the
band's first handle while the ENTITIES record that names it is still
unplaced; when the record is placed, EntityStore::push replaces the file's
entity with the generated handle.

Record the band handles the entity records of BLOCKS and ENTITIES name for
allocation, and have new_handle skip them. Reservation stays separate from
seed bumping: bump_handseed still ignores the reserved band, and a file's
band handles keep their identity.

Tests: a file whose handle-less model-space BLOCKS entity would take the
HANDLE_LIMIT handle of an ENTITIES record, with and without the CADCraft
seed record, keeps all three lines and their handles. Both fail without the
reservation (2 of 3 lines survive).
2026-11-14 18:40:40 +03:00
midasmatterhorn 528e2698fe io: reserve entity handles per section and give generated geometry free handles
Two holes in the handle bookkeeping, both found while checking the review:

- A CADCraft-marked file skips the handle pre-scan, so a handle-less entity
  in BLOCKS took a fresh handle the reader could hand out before a later
  ENTITIES record named the same handle; the second entity then replaced the
  first. Reserve the file's entity handles across BLOCKS and ENTITIES before
  anything is parsed, for marked files too. BLOCK and ENDBLK stay out, so
  structural handles do not move the saved seed.
- Generated dimension/arrowhead/table geometry read the writer's cursor
  directly. After the cursor skips an occupied handle its next value can be
  occupied too, so the generated records could reuse one of the drawing's
  handles; take them from next_handle, which skips every used handle.

Tests: a marked file with a handle-less block entity and an ENTITIES record
naming the same handle, and a drawing whose band handles make the writer wrap
while saving a dimension, both keep every handle distinct.
2026-11-14 17:18:05 +03:00
midasmatterhorn 764204540a engine: AUDIT finds ordinary handles behind a reserved-band one
A handle at or above HANDLE_LIMIT is deliberately not followed, but taking
the maximum over every handle let one such handle hide every ordinary one
behind it: the seed was never repaired past them and AUDIT reported a clean
drawing. Leave the reserved band out of the maximum, and cover a drawing
with both kinds of handle.
2026-11-14 17:17:20 +03:00
midasmatterhorn a516ce11eb io: a seed in the reserved band never hands out a handle an object holds
new_handle takes the first handle at or above the seed that no space or block
definition uses, wrapping into the band above HANDLE_LIMIT at the top of the
range. The writer's structural records skip the drawing's handles too, so a
file whose own handles sit at the bottom of the band is saved with distinct
records. AUDIT no longer reports the preserved top handles as a seed error its
own repair never fixes.
2026-11-13 00:03:08 +03:00
midasmatterhorn 03baa73ae5 Merge remote-tracking branch 'upstream/main' into pr-1276 2026-11-12 23:15:16 +03:00
moandClaude Opus 5.5 797c5df792 Merge remote-tracking branch 'origin/main' into parsers-hostile
main's #2741 makes nested callbacks share one allowance through
callback_used/callback_ceiling, which replaces this branch's own cap check in
call_sync. This branch's list-walk work counting, now also charged to
callback_used inside a callback, and the charging of a callback's work to its
caller's step are kept on top, through a callback_work field so that work is
not counted against callback_used twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 05:04:09 -05:00
wovadiandClaude Opus 5.5 736f56d320 Images: the full-path check is for builds that read files
`full_path` serves only the file read, which the web build doesn't have: it is
left out there, so the wasm check has no dead-code warning for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:33:17 +01:00
wovadi a9b93676a4 Merge remote-tracking branch 'origin/main' into fix/image-attach-limits 2026-11-10 16:20:05 +01:00
wovadiandClaude Opus 5.5 19fc1f20be Images: line breaks in data don't count toward its limit; full Windows paths get no hint
Review follow-ups on #2765:
- The length check before decoding counts the base64 characters, not the line
  breaks and spaces decoding skips, so MIME-wrapped data of a file just under
  256 MB is taken. The whole text is still bounded (6% over the limit), which
  also bounds what decoding sets aside.
- A full Windows path (a drive or a share), which Linux and macOS read as
  relative, no longer gets "save the drawing first, or give a full path".
- The test sends text that isn't base64, so only the check before decoding
  gives the size message, and it no longer builds 0.6 GB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:20:05 +01:00
moandClaude Opus 5.5 31866fcf05 Merge remote-tracking branch 'origin/main' into parsers-hostile
The relative-height cap in crates/fonts/src/mtext.rs is taken from main (#1036),
which bounds a compounding `\H…x;` to 1e-3..1e3 times the MTEXT's own height; the
MAX_HEIGHT cap and its test from f13a1f2e are dropped as redundant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 06:38:11 -05:00
moandClaude Opus 5.5 ed8555875a LISP: a routine is charged the work its slices did
The driver added the slice length at each yield, so one step walking a
long list or running a long synchronous callback was charged as 400000
steps and a blocking routine could pass its cap by that work. It now adds
the machine's used steps after every slice and stops a waiting blocking
routine once they pass the cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 10:40:50 -05:00
moandClaude Opus 5.5 6f862d7b4b SVG import: a tiny sheared ellipse keeps the axes of its image
The orthogonal-axes test now scales with the shape instead of using an
absolute floor, so a sub-micrometre sheared circle no longer takes one
of its skewed columns as the major axis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 10:06:20 -05:00
moandClaude Opus 5.5 b1a34dc0ef SVG import: a rotated or sheared ellipse keeps the orientation of its image
The major axis was the leading eigenvector of the basis's Gram matrix scaled
to the semi-major length, but that eigenvector is a direction in the
ellipse's parameter space, not in the drawing, so a rotated ellipse came in
axis-aligned. The major axis is now that direction mapped through the basis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:33:59 -05:00
moandClaude Opus 5.5 f24da7a85b SVG import: shapes too large to represent are noted as invalid, apart from what isn't read yet
A shape whose coordinates or extents overflow was listed under "CADCraft
doesn't read these yet", as if support were missing; the file itself is at
fault. Such shapes now get a read note of their own saying they were left out
as invalid, and the note on unread content keeps its wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:59:25 -05:00
moandClaude Opus 5.5 6a240a7076 SVG import: the finiteness check names every entity kind, so a new one must be decided
`finite` ended in a wildcard that passed any other kind unchecked, so a kind
the reader came to make later would skip the check silently. The kinds the
reader doesn't make are now listed, and a new `EntityKind` variant fails to
compile until it is placed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:58:18 -05:00
moandClaude Opus 5.5 f903621540 LISP: the long-list slice test measures the walk's charge, not the time it takes
The test ran `(while t (length l))` through the session and passed on main as
well, where the first slice walked the list for its whole budget before
yielding. It now builds a 32768-cell list in one run and gives a single
`(length l)` a 1000-step slice: the slice yields after the walk and the run
reports more than 32768 steps, where counting the walk as one step finished
`length` inside the slice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:57:57 -05:00
moandClaude Opus 5.5 063cbef279 SVG import: a shape whose extents overflow is left out too, not only one whose coordinates do
A circle with a finite centre and radius can still reach past the largest
number (`<circle cx="1" r="1"/>` under `scale(1e308)`), and so can an ellipse
whose box is wider than its axis or a polyline arc between finite vertices;
their bounds came out infinite or silently cut short. Such a shape is now left
out and counted in the read note like one with overflowing coordinates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:19:56 -05:00
moandClaude Opus 5.5 51f38b4eda SVG import: a shape left out for overflowing coordinates still counts against the vertex budget
The finiteness check came before the vertex charge, so a left-out shape cost
nothing, and a file of paths flattening to non-finite vertices did all that
work where the 8,000,000-vertex budget used to stop it. Each shape is now
charged first and then checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:15:23 -05:00
moandClaude Opus 5.5 348d767b93 LISP: each synchronous callback's cap counts only its own steps
Work the caller had queued before a callback (its list walks, and the charged
steps of the callbacks before it in the same step) was drained into the
callback's own count, so a `vl-sort` comparison counted every earlier
comparison too and the per-callback cap held for the whole sort. That work is
now set aside when a callback starts and charged back with the callback's own
steps, so the enclosing run still sees all of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:15:23 -05:00
moandClaude Opus 5.5 82779b50d0 SHX fonts: shape source with a name over 1,024 bytes is an error
The reader drops a record whose name runs on past 1,024 bytes, so such a source compiled into
a file without that shape. The error names the line of the definition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:09:13 -05:00
moandClaude Opus 5.5 09d2e06862 SHX fonts: a glyph outlined by two threads at once is counted in the cache once
Both missed the cache, both outlined, and the second insert replaced the first entry while
its points were added again, so the point bound cleared the cache early. The later thread
now takes the entry already there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:08:22 -05:00
moandClaude Opus 5.5 16e0fa5293 SVG import: an ellipse's major axis is relative to its centre, not a point
`Ellipse::major` is a vector from the centre everywhere else (the DXF reader
and writer keep group 11 as the DXF Reference defines it, and rendering takes
its length as the radius), but the SVG reader stored the absolute point
centre + axis, so every ellipse away from the origin, and every circle under a
non-uniform transform, came in with the wrong axis length and direction. The
existing shapes test measured `major - center` and so passed with the absolute
point; it now reads `major` as the vector.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 00:21:17 -05:00
moandClaude Opus 5.5 f13a1f2e39 MTEXT: a relative height code grows no further than the largest absolute one
`\H1000x;` multiplied the current height each time it was read, so a run of
them made the height infinite and the laid-out strokes and bounds infinite or
NaN. A relative height now stops at the 1e6 an absolute `\H` may set (or the
height it starts from, when that is larger).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 00:16:17 -05:00
moandClaude Opus 5.5 44b0399aa6 LISP: a step's list walking and callback steps count against the slice, so a routine always yields
A machine step counted as one whatever it did: `(while t (length l))` over a
long list walked 400000 lists per slice and never gave the interface a frame,
and a callback retrying an endless inner callback gave each try a fresh cap
(10000^3 steps at three levels). List cells walked and the steps of synchronous
callbacks now count as steps of the step that made them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 00:16:17 -05:00
moandClaude Opus 5.5 bb91014ebd SHX fonts: shape source finds a repeated shape number with a set, not a scan
Each definition was compared with every one before it: 65,535 shapes (an 821 KB source)
took 2.8 s to compile. The error still names the line of the repeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 b439879181 SHX fonts: look for a shape name's terminator in its first 1,024 bytes only
Big font index entries may point anywhere, so their records may overlap: 65,535 entries over
one 64 KB run without a NUL were each searched to the end, 4 G bytes and 1.7 s to read a
576 KB file (83 ms now). A record whose name runs on is dropped, as one without a terminator
was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 5154f5757b SHX fonts: bound a font's glyph cache by its points as well as its glyphs
The cache was bounded only by count (16,384 glyphs), so a font whose glyphs are all at the
point bound could keep 2 GB alive for as long as it stays loaded. It is now also cleared
before it holds more than 2^20 points (16 MB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 661e5e2dd9 SHX fonts: bound a glyph to 8,192 points and 32,768 steps
Every character of a text may draw a glyph's full budget, so the budget is what a small
hostile font multiplies: with 50,000 points and 200,000 steps an 11 KB font drew a
1,000-character line in 3 s and 1.7 GB, and a 21 KB one took 6.4 s to measure 2,000
characters. The new bounds still leave 128 full circles or 16 shapes of the format's
2,000 bytes per glyph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 225407ca61 SHX fonts: an extended big font subshape cell is held to the coordinate bound
The cell offset of code 7,0 moved the pen without the check every other move has: nested
255-unit cells put it 255^n units away, and a location pushed there and popped became the
advance (1e33) or a stroke's first point past the bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 01c003e407 SHX fonts: a shape source number with a doubled minus sign is an error, not an overflow
`--9223372036854775808` (or `-0-8000000000000000`) parsed its digits to i64::MIN and then
negated it, which panics with overflow checks on; any other doubled minus read as the
magnitude, so `*BIGFONT 4,--9223372036854775807` pushed escape ranges until 8 GB failed to
allocate (a 92-million count from a 161-byte source took 512 MB). Magnitudes must be
0..=0xFFFF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:53:42 -05:00
moandClaude Opus 5.5 50644fb0c4 SVG import: shapes whose coordinates overflow to infinity or NaN are left out and noted
Finite numbers still overflow through transforms and relative path steps
(`M1e308 0 l1e308 0`, `scale(1e308)`), and the reader added the entities with
infinite or NaN coordinates, which break extents and rendering and change on a
DXF save. Such a shape is now skipped and counted in the read note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:46:54 -05:00
zwork 23c55fc1a8 io: drop the renumbering plumbing the handle fix no longer needs 2026-11-04 17:51:09 +03:00
zwork 1a1d8404b6 io: a handle near the top of the range keeps its identity
Merged current main, which keeps a file's handles exactly as written: the
branch no longer renumbers them. A seed above HANDLE_LIMIT is not followed,
so new objects are allocated from the reserved range and never replace the
file's own object (#913). Round-trip handles near 2^64 survive a save.
2026-11-04 17:50:39 +03:00
wovadiandClaude Opus 5.5 f998f2f663 Images: check the decoded size of data too
Review follow-up on #2765: the longest base64 text allowed can hold one or two
bytes more than the 256 MB limit (it is not a multiple of three), so the decoded
bytes are checked against the limit as well. The length check before decoding
stays, to bound the allocation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:35:33 +01:00
wovadiandClaude Opus 5.5 f91d5ad38f Images: refuse oversized data before decoding, and say what to do with a relative path in an unsaved drawing
Follow-up to #2505: imageattach checks the length of base64 data against the
256 MB image limit before decoding it, and a relative path in an unsaved drawing
reports "save the drawing first, or give a full path".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:52:45 +01:00
midasmatterhorn aaaf654872 io: a group, sortents table or dimension link follows the entity the reader renumbered 2026-10-29 22:42:19 +03:00
midasmatterhorn cfc4fc5e88 Merge remote-tracking branch 'upstream/main' into fix-1276
# Conflicts:
#	crates/io/src/dxf_read.rs
2026-10-29 22:37:45 +03:00
midasmatterhorn bcac20dd5f io: a handle at the top of the range leaves new objects their own 2026-10-15 00:25:48 +03:00
74 changed files with 1331 additions and 3999 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,
+76 -14
View File
@@ -44,6 +44,11 @@ pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
/// Handles at or above this are not followed: a file may name one (an object's handle, or its
/// `$HANDSEED`), and the four billion handles above the limit stay free for the drawing's own
/// growth. A file's handles keep their identity, however high they are (#913, #939).
pub const HANDLE_LIMIT: u64 = u64::MAX - 0xFFFF_FFFF;
/// File data CADCraft doesn't model, kept for saving (#528).
pub mod dynblock;
pub mod foreign;
@@ -127,13 +132,13 @@ pub struct Drawing {
pub scales: Vec<AnnoScale>,
/// Next free handle.
pub handseed: u64,
/// Handles a file's records hold in the reserved band, recorded while reading before the
/// record is placed: [`Drawing::new_handle`] skips them meanwhile. [`Drawing::bump_handseed`]
/// does not follow them (#913). Emptied once the file is read; never written to a file.
pub reserved_handles: BTreeSet<u64>,
/// 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>,
@@ -204,8 +209,8 @@ impl Drawing {
parametric: Parametric::default(),
scales: imperial_scales(),
handseed: 0x100,
reserved_handles: BTreeSet::new(),
hidden_objects: BTreeSet::new(),
ucs_previous: Vec::new(),
read_notes: Vec::new(),
refedit: None,
skipped_records: BTreeMap::new(),
@@ -214,26 +219,83 @@ impl Drawing {
}
}
/// Allocate a fresh handle. It skips the handles the drawing's file gave the objects CADCraft
/// writes itself ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a
/// file CADCraft wrote numbers them above its `$HANDSEED` (#495).
/// Allocate a fresh handle: [`Drawing::next_handle`], with the seed moved past it. Past the
/// top of the range the drawing goes on growing in the reserved band (#913).
pub fn new_handle(&mut self) -> Handle {
let h = self.next_handle();
self.handseed = h.0.saturating_add(1);
self.handseed = h.0.checked_add(1).unwrap_or(HANDLE_LIMIT);
h
}
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it.
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it:
/// the first one at or above the seed that nothing holds. It skips
/// - the handles the drawing's file gave the objects CADCraft writes itself
/// ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a file
/// CADCraft wrote numbers them above its `$HANDSEED` (#495);
/// - handles an object or a file record being read holds in the reserved band above
/// [`HANDLE_LIMIT`]. A hostile or damaged file may name a `$HANDSEED` there, and a file
/// object may hold that same handle; the seed does not follow a file's handles in the band,
/// so taking it as-is would hand the file's object's handle to a new object and
/// `EntityStore` would replace it (#913, #1921);
/// - handle 0, which a file reads as "no handle".
///
/// Off the top of the range it goes on at the bottom of the band.
///
/// Cost: below the band the reader and [`Drawing::bump_handseed`] keep the seed above every
/// handle an object holds (AUDIT repairs a drawing where that fails), and reserved handles are
/// all in the band, so there only `foreign.handles` is looked up. The scan of every space and
/// block definition runs only for a candidate in the band. Every handle skipped is a distinct
/// one something holds, so the walk ends within one step more than the count of held handles.
pub fn next_handle(&self) -> Handle {
let held = |h: u64| {
h == 0
|| self.foreign.handles.contains_key(&Handle(h))
|| (h >= HANDLE_LIMIT && (self.reserved_handles.contains(&h) || self.handle_in_use(Handle(h))))
};
let mut h = self.handseed;
while self.foreign.handles.contains_key(&Handle(h)) && h < u64::MAX {
h = h.saturating_add(1);
// Counted only once a handle is skipped, so the usual first-try answer costs nothing.
let mut steps_left: Option<usize> = None;
while held(h) {
let left = steps_left.get_or_insert_with(|| self.held_handle_count());
let Some(rest) = left.checked_sub(1) else { break };
*left = rest;
h = h.checked_add(1).unwrap_or(HANDLE_LIMIT);
}
Handle(h)
}
/// Whether an object in any space or block definition already holds `h`.
fn handle_in_use(&self, h: Handle) -> bool {
self.model.contains(h) || self.layouts.iter().any(|l| l.entities.contains(h)) || self.blocks.values().any(|b| b.entities.contains(h))
}
/// An upper bound on how many handles [`Drawing::next_handle`] can find held, plus handle 0.
fn held_handle_count(&self) -> usize {
let spaces = self.layouts.iter().map(|l| l.entities.len()).chain(self.blocks.values().map(|b| b.entities.len()));
spaces
.fold(self.model.len(), usize::saturating_add)
.saturating_add(self.foreign.handles.len())
.saturating_add(self.reserved_handles.len())
.saturating_add(1)
}
/// Record a handle a file's record holds in the reserved band, before the record is placed in
/// the drawing, so [`Drawing::new_handle`] does not hand it to an object read earlier (#1276).
///
/// Only handles at or above [`HANDLE_LIMIT`] are recorded: below it [`Drawing::bump_handseed`]
/// already moves the seed past them. The reservation stays separate from the seed because the
/// writer's growth lives above the limit and a file's handles there are not followed (#913).
pub fn reserve_handle(&mut self, h: Handle) {
if h.0 >= HANDLE_LIMIT {
self.reserved_handles.insert(h.0);
}
}
/// Make sure future handles don't collide with `h` (after loading a file).
///
/// A handle at or above [`HANDLE_LIMIT`] is the file's own and stays as it is: it is not
/// followed, so a new object is never given the top handle and the file's object is never
/// replaced (#913). The handles above the limit are the drawing's room to grow.
pub fn bump_handseed(&mut self, h: Handle) {
if h.0 >= self.handseed {
self.handseed = h.0.saturating_add(1);
if h.0 >= self.handseed && h.0 < HANDLE_LIMIT {
self.handseed = h.0 + 1;
}
}
+1 -18
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 }
}
}
+28
View File
@@ -726,6 +726,34 @@ fn new_handles_skip_the_files_object_handles() {
assert_eq!(d.new_handle(), Handle(next + 3));
}
/// In the reserved band a new handle skips the file's kept object handles (#2514) and the handles
/// objects hold in model space, a layout and a block definition, or that a file record reserved
/// (#913); off the top of the range it goes on at the bottom of the band. HANDSEED reports the
/// handle `new_handle` takes.
#[test]
fn new_handles_in_the_reserved_band_skip_every_held_handle_and_wrap() {
let mut d = Drawing::new_metric();
let top = u64::MAX;
d.model.push(Entity::new(Handle(top - 4), line((0.0, 0.0), (1.0, 0.0))));
let mut sheet = Layout::new("Sheet", 1);
sheet.entities.push(Entity::new(Handle(top - 3), line((0.0, 0.0), (1.0, 0.0))));
d.layouts.push(sheet);
let mut b = Block::new("B");
b.entities.push(Entity::new(Handle(top - 2), line((0.0, 0.0), (1.0, 0.0))));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
std::sync::Arc::make_mut(&mut d.foreign).handles.insert(Handle(top - 1), ("LAYER".into(), "0".into()));
d.reserve_handle(Handle(top));
d.model.push(Entity::new(Handle(HANDLE_LIMIT), line((0.0, 0.0), (1.0, 0.0))));
d.handseed = top - 5;
assert_eq!(d.new_handle(), Handle(top - 5));
assert_eq!(d.next_handle(), Handle(HANDLE_LIMIT + 1), "a held handle was offered");
assert_eq!(d.new_handle(), Handle(HANDLE_LIMIT + 1));
assert_eq!(d.handseed, HANDLE_LIMIT + 2);
// Handle 0 means "no handle" in a file; a seed there moves on.
d.handseed = 0;
assert_eq!(d.new_handle(), Handle(1));
}
/// Several spellings of one DIM field apply once, the last in the map's order, and none is rejected.
#[test]
fn dim_style_spellings_of_one_field_apply_once() {
+7 -1
View File
@@ -319,8 +319,14 @@ fn all_handles(d: &Drawing) -> HashSet<Handle> {
}
/// The next handle is above every handle in use, so new objects never take an existing one.
///
/// A handle at or above [`cadcraft_doc::HANDLE_LIMIT`] is the file's own and is deliberately not
/// followed: the seed never moves past it, and new objects take free handles in the band above
/// the limit. Reporting it would repeat the same repair on every audit, so it is not an issue.
/// Such a handle is left out of the maximum too, or the largest handle would hide every ordinary
/// one behind it and the seed would never be repaired past them.
fn handseed(d: &mut Drawing, out: &mut Vec<Issue>) {
let Some(max) = each_entity(d).map(|e| e.handle).max() else { return };
let Some(max) = each_entity(d).map(|e| e.handle).filter(|h| h.0 < cadcraft_doc::HANDLE_LIMIT).max() else { return };
if max.0 >= d.handseed {
out.push(issue(
"handseed",
-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(),
}
}
+31 -3
View File
@@ -18,8 +18,13 @@ use crate::{Result, Session};
/// Most image files loaded per drawing.
const MAX_IMAGE_FILES: usize = 1000;
/// Largest image file read (bytes).
#[cfg(not(target_arch = "wasm32"))]
const MAX_IMAGE_BYTES: u64 = 256 << 20;
/// Longest base64 text taken for `data`: what a file of [`MAX_IMAGE_BYTES`] encodes to.
const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
/// Longest `data` text with the line breaks and spaces base64 may carry (MIME breaks every 76
/// characters, under 3% more): the characters past [`MAX_IMAGE_BASE64`] are counted only up to
/// here, which also bounds what decoding sets aside.
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
const MAX_LOADED_BYTES: u64 = 2 << 30;
/// Most image files decoded at the same time when a drawing opens.
@@ -70,11 +75,22 @@ fn paths(d: &Drawing) -> Vec<String> {
paths
}
/// Whether `path` is a full path here, or on Windows where a drawing may have been written (a
/// drive, `C:\maps\a.png`, or a share, `\\server\maps`), which other systems read as relative.
#[cfg(not(target_arch = "wasm32"))]
fn full_path(path: &str) -> bool {
let b = path.trim().as_bytes();
std::path::Path::new(path.trim()).is_absolute() || b.starts_with(b"\\\\") || matches!(b, [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic())
}
/// The contents of the image file saved as `path` in a drawing at `host`.
fn read_file(path: &str, host: Option<&str>) -> std::result::Result<Vec<u8>, String> {
#[cfg(not(target_arch = "wasm32"))]
{
let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?;
let file = super::blocks::xref::find_file(path, host).ok_or_else(|| {
// An unsaved drawing has no folder for a relative path to be relative to.
if host.is_none() && !full_path(path) { "file not found (save the drawing first, or give a full path)" } else { "file not found" }
})?;
let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
if len > MAX_IMAGE_BYTES {
return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20));
@@ -304,7 +320,19 @@ fn pixels(s: &Session, p: &Value, path: &str) -> Result<Arc<Raster>> {
let bytes = match p.get("data") {
Some(data) => {
let text = data.as_str().ok_or_else(|| bad(ID, "`data` must be base64 text"))?;
base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?
// Refused before decoding, which would hold all of it in memory. Line breaks and
// spaces, which decoding skips, don't count.
let len = u64::try_from(text.len()).unwrap_or(u64::MAX);
let digits = || u64::try_from(text.bytes().filter(|b| !matches!(b, b'\n' | b'\r' | b' ')).count()).unwrap_or(u64::MAX);
if len > MAX_IMAGE_TEXT || (len > MAX_IMAGE_BASE64 && digits() > MAX_IMAGE_BASE64) {
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
}
let bytes = base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?;
// The longest text allowed can still hold a byte or two more than the limit.
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_IMAGE_BYTES {
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
}
bytes
}
None => {
if let Some(loaded) = s.doc()?.rasters.get(path) {
+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());
}
+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 }))
}
-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).
-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).
+14 -16
View File
@@ -139,6 +139,9 @@ pub struct LispState {
/// Interpreter steps all synchronous callbacks have run, nested ones included. A callback's
/// allowance counts what ran since it started, so the callbacks it calls spend its steps.
pub(crate) callback_used: u64,
/// Work synchronous callbacks did inside the running step, already counted in `callback_used`:
/// the step is charged it without charging the enclosing callback a second time.
pub(crate) callback_work: u64,
/// The `callback_used` value the callback running now (and so every one it calls) must not
/// pass: the lowest of its own and its callers' allowances.
pub(crate) callback_ceiling: Option<u64>,
@@ -383,6 +386,14 @@ impl Session {
let uid = run.uid;
self.lisp_flush(&mut env, false);
self.lisp_env_put(uid, env);
// The work the slice did, which one step can take far past the slice. After a panic
// `used` is still the previous slice's; the run ends with the error anyway.
run.steps = run.steps.saturating_add(run.machine.used);
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
return;
}
match outcome {
Outcome::Done(v) => {
self.lisp.run = Some(run);
@@ -395,13 +406,7 @@ impl Session {
return;
}
Outcome::Wait(Need::Yield) => {
run.steps = run.steps.saturating_add(SLICE);
if run.blocking {
if run.steps > BLOCKING_CAP {
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
return;
}
self.lisp.run = Some(run);
continue;
}
@@ -558,7 +563,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 +574,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 +756,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
+41 -8
View File
@@ -175,17 +175,19 @@ pub struct Machine {
stack: Vec<Frame>,
state: State,
need: Option<Need>,
/// Steps the last [`Machine::run`] took, with the work done inside them.
pub(crate) used: u64,
}
impl Machine {
/// A machine evaluating `forms` in turn.
pub fn forms(forms: Vec<Value>) -> Machine {
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None }
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None, used: 0 }
}
/// A machine calling `f` with `args`.
pub fn calling(f: Value, args: Vec<Value>) -> Machine {
Machine { stack: Vec::new(), state: State::Call(f, args), need: None }
Machine { stack: Vec::new(), state: State::Call(f, args), need: None, used: 0 }
}
/// Give the value a [`Need`] waited for, and carry on.
@@ -193,12 +195,31 @@ impl Machine {
self.state = State::Ret(v);
}
/// Run until done, waiting, or `budget` steps.
/// Run until done, waiting, or `budget` steps. A step that walks a long list (`length`) or
/// runs a synchronous callback counts that work too, so one slice stays short.
pub fn run(&mut self, ctx: &mut Ctx<'_>, budget: u64) -> Outcome {
let mut n = 0u64;
let outcome = self.run_counted(ctx, budget, &mut n);
// The last step's work too, so nothing is left for the next run.
self.used = n.saturating_add(Machine::take_step_work(ctx));
outcome
}
/// The work the last step did besides itself: the lists it walked, which count against a
/// callback's allowance too, and the callbacks it ran, which were counted there as they ran.
fn take_step_work(ctx: &mut Ctx<'_>) -> u64 {
let walked = super::value::take_work();
let callbacks = std::mem::take(&mut ctx.s.lisp.callback_work);
if ctx.depth > 0 {
ctx.s.lisp.callback_used = ctx.s.lisp.callback_used.saturating_add(walked);
}
walked.saturating_add(callbacks)
}
fn run_counted(&mut self, ctx: &mut Ctx<'_>, budget: u64, n: &mut u64) -> Outcome {
loop {
n += 1;
if n > budget {
*n = n.saturating_add(1).saturating_add(Machine::take_step_work(ctx));
if *n > budget {
return Outcome::Wait(Need::Yield);
}
// Charge a callback's step as it runs, so callbacks it calls see what it already spent.
@@ -651,6 +672,10 @@ impl Ctx<'_> {
return Ok(v);
}
let cap = self.s.lisp.limits.callback_steps;
// Work the caller queued before this call (its list walks, earlier callbacks of the same
// step) is not this callback's: set it aside and hand it back with this callback's.
let pending = super::value::take_work();
let pending_callbacks = std::mem::take(&mut self.s.lisp.callback_work);
let start = self.s.lisp.callback_used;
// This callback may run until `callback_used` reaches `ceiling`: `cap` steps from now, or
// sooner where a caller's allowance ends, so callbacks nested in callbacks share one
@@ -658,13 +683,20 @@ impl Ctx<'_> {
let outer = self.s.lisp.callback_ceiling;
let ceiling = start.saturating_add(cap).min(outer.unwrap_or(u64::MAX));
self.s.lisp.callback_ceiling = Some(ceiling);
let r = self.drive_callback(f, args, ceiling);
let mut spent: u64 = 0;
let r = self.drive_callback(f, args, ceiling, &mut spent);
self.s.lisp.callback_ceiling = outer;
super::value::charge_work(pending);
// Its steps, nested callbacks' included, are work done inside the caller's one step: they
// count against the caller's slice and every enclosing callback's. They are in
// `callback_used` already, so they reach the caller apart from its list walks.
self.s.lisp.callback_work = pending_callbacks.saturating_add(spent);
r
}
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`.
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64) -> Result<Value, LispError> {
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`, adding
/// the work each slice did to `spent`.
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64, spent: &mut u64) -> Result<Value, LispError> {
let cap = self.s.lisp.limits.callback_steps;
let mut m = Machine::calling(f.clone(), args);
let mut sub = Ctx { s: &mut *self.s, env: &mut *self.env, depth: self.depth + 1 };
@@ -680,6 +712,7 @@ impl Ctx<'_> {
}
let slice = remaining.min(SYNC_SLICE);
let outcome = m.run(&mut sub, slice);
*spent = spent.saturating_add(m.used);
match outcome {
// The steps were charged as they ran; finishing past the shared allowance is a failure too.
Outcome::Done(_) if sub.s.lisp.callback_used > ceiling => {
+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)
}
+106
View File
@@ -247,6 +247,112 @@ fn synchronous_callback_loop_is_an_error_not_a_hang() {
assert_eq!(ok(&mut s, "(vl-sort '(3 1 2) '<)"), "(1 2 3)");
}
/// A step that walks a long list counts its work: one `length` of 32768 cells is past a 1000-step
/// slice, so the slice yields after it.
#[test]
fn walking_a_long_list_counts_against_the_slice() {
use super::eval::{Ctx, Machine, Need, Outcome};
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut env = super::Env::default();
let mut ctx = Ctx { s: &mut s, env: &mut env, depth: 0 };
// Built before the measured run, so only the `length` is counted.
let mut build = Machine::forms(super::read::read_all("(setq l '(1)) (repeat 15 (setq l (append l l)))").unwrap());
assert!(matches!(build.run(&mut ctx, u64::MAX), Outcome::Done(_)));
let mut m = Machine::forms(super::read::read_all("(length l)").unwrap());
// Counted as one step, the walk left the few steps of `(length l)` well inside the slice.
assert!(matches!(m.run(&mut ctx, 1_000), Outcome::Wait(Need::Yield)), "the walk was not charged");
assert!(m.used > 32_768, "{}", m.used);
match m.run(&mut ctx, u64::MAX) {
Outcome::Done(v) => assert_eq!(to_text(&v, true), "32768"),
_ => panic!("the length did not finish"),
}
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// A routine is charged the work its slice did, not the slice's length: one `length` of 2^19
/// cells is far past a 400000-step slice.
#[test]
fn a_routine_is_charged_the_work_of_its_slice() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
ok(&mut s, "(setq l '(1)) (repeat 19 (setq l (append l l))) nil");
let r = s.lisp_eval("(length l) (repeat 10 (setq x 1))", false, false, Vec::new()).unwrap();
assert!(r.is_none(), "the routine gave the interface a frame");
assert!(s.lisp_busy());
let steps = s.lisp.run.as_ref().map(|r| r.steps).unwrap_or(0);
assert!(steps >= 1 << 19, "{steps}");
for _ in 0..100 {
if !s.lisp_busy() {
break;
}
s.lisp_tick();
}
assert!(!s.lisp_running());
ok(&mut s, "(setq l nil)");
}
/// A run's last step walking a long list is charged to that run, not left for the next one: here
/// it fails after the walk (a list of numbers isn't a list of strings), so no step follows it.
#[test]
fn the_last_steps_list_walk_is_charged_to_its_run() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut env = super::Env::default();
env.globals.insert(super::value::Sym::new("L"), Value::list(vec![Value::Int(1); 100_000]));
let mut m = super::eval::Machine::forms(super::read::read_all("(acad_strlsort l)").unwrap());
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
assert!(matches!(m.run(&mut ctx, u64::MAX), super::eval::Outcome::Error(_)));
assert!(m.used > 100_000, "{}", m.used);
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// Nested callbacks share one cap: an inner endless callback retried by an outer one stops.
#[test]
fn nested_callback_steps_count_against_the_outer_callback() {
let mut s = session();
s.lisp.limits.callback_steps = 10_000;
// Each level retried the endless level inside it with a fresh cap: 10000^3 steps, a hang.
let code = "(defun g (a b) (while t)) \
(defun f (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'g)))) \
(defun h (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'f)))) \
(vl-sort '(1 2) 'h)";
assert_eq!(eval(&mut s, code), Err("callback stopped after 10000 steps".into()));
// A callback's own steps count once, however many slices it runs in: three slices do three
// times the work of one.
let counts: Vec<u64> = [400_000, 1_200_000]
.into_iter()
.map(|cap| {
s.lisp.limits.callback_steps = cap;
ok(&mut s, "(setq n 0)");
assert!(eval(&mut s, "(vl-remove-if '(lambda (x) (while t (setq n (1+ n)))) '(1))").is_err());
ok(&mut s, "n").parse().unwrap()
})
.collect();
assert!(counts[1] * 10 >= counts[0] * 29, "{counts:?}");
}
/// The callback cap holds for each callback: a sort's comparisons together take more steps than
/// it, and all their work still reaches the enclosing run.
#[test]
fn each_callback_has_its_own_cap_and_its_work_reaches_the_caller() {
let mut s = session();
s.lisp.limits.callback_steps = 1_000;
let mut env = super::Env::default();
env.globals.insert(super::value::Sym::new("L"), Value::list((0..300).rev().map(Value::Int)));
let mut m = super::eval::Machine::forms(super::read::read_all("(vl-sort l (function (lambda (a b) (< a b))))").unwrap());
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
let v = match m.run(&mut ctx, u64::MAX) {
super::eval::Outcome::Done(v) => v,
super::eval::Outcome::Error(e) => panic!("the sort failed: {e:?}"),
super::eval::Outcome::Wait(_) => panic!("the sort waited"),
};
assert_eq!(to_text(&v, true), to_text(&Value::list((0..300).map(Value::Int)), true));
// Over a thousand comparisons of several steps each, together well past the cap.
assert!(m.used > 3_000, "{}", m.used);
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}
/// A zero-step callback limit prevents even the first callback side effect.
#[test]
fn a_zero_callback_budget_does_not_run_the_callback() {
-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}");
}
}
+17 -1
View File
@@ -64,6 +64,8 @@ thread_local! {
static STRING_BYTES: Cell<(u64, u64)> = const { Cell::new((0, STRING_BUDGET)) };
/// The running slice's cap on live cons cells.
static CELL_LIMIT: Cell<usize> = const { Cell::new(MAX_CELLS) };
/// Work done inside the current machine step: list cells walked, steps of synchronous callbacks.
static WORK: Cell<u64> = const { Cell::new(0) };
}
/// Start a slice of a run on this thread: it fails when more than `limit` cells are alive.
@@ -76,6 +78,16 @@ pub fn check_cells() -> Result<(), LispError> {
if live_cells() > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) }
}
/// Count `n` units of work done inside one machine step ([`super::eval::Machine::run`] charges them as steps).
pub fn charge_work(n: u64) {
WORK.with(|c| c.set(c.get().saturating_add(n)));
}
/// The work counted since the last call.
pub fn take_work() -> u64 {
WORK.with(|c| c.replace(0))
}
/// Start a slice of a run on this thread: it has made `used` bytes of its `budget`.
pub fn set_string_budget(used: u64, budget: u64) {
STRING_BYTES.with(|c| c.set((used, budget)));
@@ -262,7 +274,10 @@ impl Value {
loop {
match v {
Value::Nil => return true,
Value::Cons(c) => v = c.cdr.clone(),
Value::Cons(c) => {
charge_work(1);
v = c.cdr.clone();
}
_ => return false,
}
}
@@ -318,6 +333,7 @@ impl Iterator for ListIter {
fn next(&mut self) -> Option<Value> {
match std::mem::take(&mut self.next) {
Value::Cons(c) => {
charge_work(1);
self.next = c.cdr.clone();
Some(c.car.clone())
}
+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 } => {
+10 -33
View File
@@ -114,10 +114,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 +350,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 +361,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 +377,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 +392,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
View File
@@ -125,10 +125,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
@@ -197,7 +193,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}");
+36
View File
@@ -329,3 +329,39 @@ fn auditctl_generates_adt_report_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_handle_in_the_reserved_band_is_not_repaired_on_every_audit() {
// A file object above HANDLE_LIMIT keeps its handle, and the seed deliberately does not move
// past it (#913). AUDIT must not report that policy as an error its own repair never fixes.
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
let mut d = Drawing::new_imperial();
d.space_mut(&Space::Model).unwrap().push(Entity { handle: band, common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
d.handseed = band.0;
for _ in 0..3 {
let r = cadcraft_engine::audit::check(&d);
assert!(r.issues.iter().all(|i| i.kind != "handseed"), "{}", r.message());
}
let mut repaired = d.clone();
let r = cadcraft_engine::audit::repair(&mut repaired);
assert!(r.iter().all(|i| i.kind != "handseed"), "{r:?}");
assert_eq!(repaired.handseed, band.0, "the seed moved past the file's own handle");
}
#[test]
fn an_ordinary_handle_behind_a_reserved_band_one_is_still_repaired() {
// The largest handle is in the reserved band, which the seed deliberately does not follow.
// An ordinary handle above the seed must still be found behind it: it is the one the seed
// has to move past, and skipping the check would leave AUDIT reporting a clean drawing.
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
let mut d = Drawing::new_imperial();
let store = d.space_mut(&Space::Model).unwrap();
store.push(Entity { handle: Handle(20), common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
store.push(Entity { handle: band, common: Common::default(), kind: line((2.0, 0.0), (3.0, 0.0)) });
d.handseed = 10;
let r = cadcraft_engine::audit::repair(&mut d);
assert!(r.iter().any(|i| i.kind == "handseed" && i.message.contains("(14)")), "the ordinary handle was hidden: {r:?}");
assert_eq!(d.handseed, 21, "the seed was not moved past the ordinary handle");
let r = cadcraft_engine::audit::repair(&mut d.clone());
assert!(r.iter().all(|i| i.kind != "handseed"), "the repair does not stick: {r:?}");
}
+45
View File
@@ -142,6 +142,51 @@ fn bad_input_is_refused_and_changes_nothing() {
assert_eq!(listed(&mut s), json!([]));
}
/// `data` longer than the largest image file encodes to is refused before it is decoded.
#[test]
fn oversized_data_is_refused_before_decoding() {
hooks();
const LIMIT: u64 = 256 << 20;
let mut s = Session::new();
// Not base64 at all: only the check before decoding tells it is too long ("not valid base64"
// otherwise), and nothing is decoded.
let too_long = "!".repeat(usize::try_from(LIMIT.div_ceil(3) * 4 + 1).unwrap());
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": too_long })).unwrap_err().to_string();
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
// Line breaks don't count: base64 wrapped as MIME writes it is taken.
let wrapped: String = base64_encode(&png()).as_bytes().chunks(76).map(|c| format!("{}\r\n", String::from_utf8_lossy(c))).collect();
s.execute("imageattach", &json!({ "path": "wrapped.png", "data": wrapped })).unwrap();
s.execute("undo", &json!({})).unwrap();
// The longest text allowed, holding one byte more than the limit, is refused once decoded.
let groups = usize::try_from(LIMIT / 3).unwrap();
let one_over = format!("{}AAA=", "AAAA".repeat(groups));
assert_eq!(u64::try_from(one_over.len()).unwrap(), LIMIT.div_ceil(3) * 4, "as long as the text for the limit itself");
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": one_over })).unwrap_err().to_string();
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
assert!(images(&s).is_empty());
}
/// A relative path in an unsaved drawing has nothing to be relative to, and the error says so.
#[test]
fn a_relative_path_in_an_unsaved_drawing_says_what_to_do() {
hooks();
let mut s = Session::new();
let e = s.execute("imageattach", &json!({ "path": "missing.png" })).unwrap_err().to_string();
assert!(e.contains("save the drawing first, or give a full path"), "{e}");
let dir = folder("unsaved");
let full = dir.join("missing.png");
let e = s.execute("imageattach", &json!({ "path": full.to_string_lossy() })).unwrap_err().to_string();
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{e}");
// A full Windows path, read as relative elsewhere, is a full path all the same.
for windows in [r"C:\nowhere\a.png", "D:/nowhere/a.png", r"\\server\maps\a.png"] {
let e = s.execute("imageattach", &json!({ "path": windows })).unwrap_err().to_string();
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{windows}: {e}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_image_among_many_objects_keeps_its_pixels() {
// More objects than one build task takes: the display list is built in parts and joined,
+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);
-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:?}");
}
+19 -6
View File
@@ -56,11 +56,17 @@ pub struct ShxGlyph {
pub advance: Vec2,
}
/// Glyphs cached per font, keyed by (shape, vertical).
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
/// Glyphs cached per font, keyed by (shape, vertical), and their points in all.
#[derive(Default)]
struct GlyphCache {
glyphs: HashMap<(u16, bool), Option<Arc<ShxGlyph>>>,
points: usize,
}
/// Most glyphs cached per font (a big font has thousands; text uses a few hundred).
const MAX_CACHED_GLYPHS: usize = 16_384;
/// Most points cached per font (16 MB; a glyph may hold thousands of points).
const MAX_CACHED_POINTS: usize = 1 << 20;
/// A parsed SHX file.
pub struct ShxFont {
@@ -203,15 +209,22 @@ impl ShxFont {
}
let vertical = vertical && self.dual;
let key = (number, vertical);
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).get(&key) {
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&key) {
return g.clone();
}
let g = program::outline(self, number, vertical).ok().map(Arc::new);
let points = g.as_ref().map_or(0, |g| g.strokes.iter().map(Vec::len).sum::<usize>());
let mut c = self.cache.write().unwrap_or_else(PoisonError::into_inner);
if c.len() >= MAX_CACHED_GLYPHS {
c.clear();
// Another thread may have outlined it in the meantime: its points are counted already.
if let Some(g) = c.glyphs.get(&key) {
return g.clone();
}
c.insert(key, g.clone());
if c.glyphs.len() >= MAX_CACHED_GLYPHS || c.points.saturating_add(points) > MAX_CACHED_POINTS {
c.glyphs.clear();
c.points = 0;
}
c.points = c.points.saturating_add(points);
c.glyphs.insert(key, g.clone());
g
}
}
+16
View File
@@ -309,6 +309,22 @@ fn hostile_files_never_panic() {
assert!(compile("").is_err());
}
#[test]
fn the_glyph_cache_is_bounded_by_points() {
// Hostile: every glyph at the point bound, so 16,384 cached glyphs would hold 2 GB.
let mut src = format!("*2,1,HUNDRED\n{}0\n*3,3,V\n011,019,0\n", "7,3,".repeat(100));
for n in 10..=200 {
src.push_str(&format!("*{n},1,HEAVY\n{}0\n", "7,2,".repeat(40)));
}
let f = font(&src);
for n in 10..=200 {
assert!(f.glyph(n, false).is_some());
}
let c = f.cache.read().unwrap();
let cached: usize = c.glyphs.values().flatten().map(|g| g.strokes.iter().map(Vec::len).sum::<usize>()).sum();
assert!(cached <= MAX_CACHED_POINTS && cached == c.points, "{cached}");
}
/// Register a compiled test font under `name` (each test its own names: the table is shared).
fn reg(name: &str, src: &str) {
register(name, &compile(src).unwrap()).unwrap();
-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;
+34 -6
View File
@@ -1062,11 +1062,10 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
alive_memo
});
// New handles for the written kept objects, above every written handle and the seed.
let mut next = seed(tags).max(max_handle(tags).saturating_add(1));
let mut fresh = Fresh::new(tags);
let mut alive: HashMap<String, String> = HashMap::new();
for o in f.objects.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) {
alive.insert(o.handle.hex(), format!("{next:X}"));
next = next.saturating_add(1);
alive.insert(o.handle.hex(), format!("{:X}", fresh.take()));
}
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 };
@@ -1389,19 +1388,18 @@ fn add_appids(out: &mut Vec<Tag>) {
return;
}
// New handles above the seed, which is then moved past them.
let mut next = seed(out).max(max_handle(out).saturating_add(1));
let mut fresh = Fresh::new(out);
let mut add = Vec::new();
for app in &missing {
add.extend([
Tag::s(0, "APPID"),
Tag::s(5, format!("{next:X}")),
Tag::s(5, format!("{:X}", fresh.take())),
Tag::s(330, table_h.clone()),
Tag::s(100, "AcDbSymbolTableRecord"),
Tag::s(100, "AcDbRegAppTableRecord"),
Tag::s(2, (*app).clone()),
Tag::i(70, 0),
]);
next = next.saturating_add(1);
}
let end_at = end.start;
if let Some(count) = out.get_mut(t.start + 1..t.end).and_then(|b| b.iter_mut().find(|x| x.code == 70)) {
@@ -1420,6 +1418,36 @@ fn seed(tags: &[Tag]) -> u64 {
seed_index(tags).and_then(|i| tags.get(i)).and_then(|t| Handle::parse_hex(&t.str())).map_or(0, |h| h.0)
}
/// New handles for records added to written tags: above the seed and every handle written, and
/// never one a record already holds. A file may hold the top handle (#913): then counting on from
/// it would give every added record that same handle, so past the top of the range the numbering
/// goes on in the reserved band above [`cadcraft_doc::HANDLE_LIMIT`], skipping the handles there.
struct Fresh {
next: u64,
used: HashSet<u64>,
}
impl Fresh {
fn new(tags: &[Tag]) -> Self {
let used: HashSet<u64> =
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).collect();
let above = used.iter().max().map_or(0, |h| h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT));
Fresh { next: seed(tags).max(above), used }
}
/// The next free handle. Each handle skipped is one a record holds, so the walk is bounded
/// by their count (and handle 0, which means "none").
fn take(&mut self) -> u64 {
for _ in 0..self.used.len().saturating_add(2) {
let h = self.next;
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
if h != 0 && self.used.insert(h) {
return h;
}
}
self.next
}
}
/// The largest handle of a record (groups 5 and 105).
fn max_handle(tags: &[Tag]) -> u64 {
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).max().unwrap_or(0)
+32 -6
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>)>,
@@ -104,11 +102,36 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
// a polygon mesh) would otherwise get handles that records further on still have. A file
// CADCraft wrote names its own next handle, above which its rebuilt records are numbered
// (#495), so it is left to that.
// (#495), so for it only the entity records are reserved. Handles in the reserved band are
// reserved for allocation rather than followed (#913): a handle-less entity read before the
// section that names one is placed would otherwise be given it and replace the record (#1276).
let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY));
for t in secs.iter().filter(|_| !ours).flat_map(|s| s.tags.iter()).filter(|t| t.code == 5 || t.code == 105) {
if let Some(h) = Handle::parse_hex(t.str().trim()) {
d.bump_handseed(h);
if ours {
// Its table and object records are numbered above its seed and rebuilt on save (#495),
// so only its entities are reserved. Reading is section by section: an entity that has
// no handle, or repeats one within its section, gets a fresh handle, and that must not
// be one an entity of a later section still names. `BLOCK` and `ENDBLK` are structural
// records, not entities, and are left out so they don't move the saved seed.
for (kind, tags) in secs.iter().filter(|s| s.name == "BLOCKS" || s.name == "ENTITIES").flat_map(|s| records(&s.tags)) {
if matches!(kind.as_str(), "BLOCK" | "ENDBLK") {
continue;
}
if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(t.str().trim())) {
d.bump_handseed(h);
d.reserve_handle(h);
}
}
} else {
for s in &secs {
let entity_section = s.name == "BLOCKS" || s.name == "ENTITIES";
for t in s.tags.iter().filter(|t| t.code == 5 || t.code == 105) {
if let Some(h) = Handle::parse_hex(t.str().trim()) {
d.bump_handseed(h);
if entity_section {
d.reserve_handle(h);
}
}
}
}
}
let mut skipped = std::collections::BTreeMap::new();
@@ -150,6 +173,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
crate::dxf_raw::read(&secs, &mut d);
crate::dxf_clip::read(&mut d);
d.skipped_records = skipped;
// Every record is placed now, and an object holding a reserved handle keeps it from new
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
d.reserved_handles.clear();
Ok(d)
}
+1
View File
@@ -55,6 +55,7 @@ pub(super) fn parse_entities(
}
if let Some((c, mut k)) = kindent {
let h = match handle {
// A file's handles keep their identity, however high they are (#913, #939).
Some(h) => {
d.bump_handseed(h);
h
+3 -57
View File
@@ -1,7 +1,7 @@
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)]
@@ -22,8 +22,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).
@@ -72,18 +70,11 @@ 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)));
}
}
_ => {}
}
@@ -103,49 +94,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 +191,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.
@@ -276,7 +223,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 {
-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;
+35 -13
View File
@@ -3,13 +3,13 @@
//! the newer DIMSTYLE groups, and from 2007 in UTF-8 text (the caller picks the text encoding) and
//! MULTILEADER entities (older files get LEADER + MTEXT).
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
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};
@@ -39,20 +39,33 @@ use sections::tags_for;
struct W {
t: Vec<Tag>,
next: u64,
/// Handles the drawing's objects already hold: structural records skip them, so writing a
/// file whose own handles sit near the top of the range never repeats a handle (#913).
used: HashSet<u64>,
/// Upper-case plot style name → its `ACDBPLACEHOLDER` handle (group 390 of layers and objects).
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>>,
}
/// Where the writer's own records (tables, objects, dictionaries) start numbering: above every
/// object handle and the drawing's seed, with headroom for handles the drawing allocates next.
fn structural_start(d: &Drawing) -> u64 {
let highest = entity_handles(d).max().unwrap_or(0);
d.handseed.max(0x100).max(highest.saturating_add(1)).saturating_add(0x1000)
}
/// Every handle an object holds, plus the drawing's next one.
fn entity_handles(d: &Drawing) -> impl Iterator<Item = u64> + '_ {
let model = d.model.iter().map(|e| e.handle.0);
let layouts = d.layouts.iter().flat_map(|l| l.entities.iter()).map(|e| e.handle.0);
let blocks = d.blocks.values().flat_map(|b| b.entities.iter()).map(|e| e.handle.0);
model.chain(layouts).chain(blocks).chain(std::iter::once(d.handseed))
}
impl W {
fn s(&mut self, c: i32, v: impl Into<String>) {
self.t.push(Tag::s(c, v));
@@ -76,10 +89,20 @@ impl W {
format!("{:X}", self.next_handle())
}
/// A new handle for a record the drawing doesn't hold (as [`W::h`]).
///
/// Skips every handle in use, so a file object carrying a handle above the seed (the
/// reserved band) is not handed out again, and wraps into that band if the writer runs off
/// the top of the range. Each handle skipped is one in use, so the walk is bounded by their
/// count.
fn next_handle(&mut self) -> u64 {
let h = self.next;
self.next = self.next.saturating_add(1);
h
for _ in 0..self.used.len().saturating_add(1) {
let h = self.next;
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
if self.used.insert(h) {
return h;
}
}
self.next
}
/// A `102 {NAME` … `102 }` group of handles.
fn group(&mut self, name: &str, code: i32, handles: &[&str]) {
@@ -157,11 +180,10 @@ fn bridge_markers(tags: &mut [Tag]) {
pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec<Tag>) {
let mut w = W {
t: Vec::new(),
next: d.handseed.max(0x100).saturating_add(0x1000),
next: structural_start(d),
used: entity_handles(d).collect(),
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 -2
View File
@@ -19,10 +19,9 @@ pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
let mut ov = W {
t: Vec::new(),
next: 0,
used: std::collections::HashSet::new(),
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: HashMap::new(),
};
let mut sah = false;
+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}"));
-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,27 +138,6 @@ 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");
}
+15 -57
View File
@@ -3,13 +3,14 @@ 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::header::{code_page, header_vars};
use super::layout::{paper_views, record_head, sheet_first, table_head, 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,
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, HashSet, Layout, MLeaderStyle, PageSetup,
Space, TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
};
use super::{entity_handles, structural_start};
struct TableWritePlan<'a> {
d: &'a Drawing,
@@ -163,8 +164,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 +174,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 {
@@ -253,15 +246,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, used: HashSet::new(), 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 +386,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 +468,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 +533,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 +548,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,
},
);
@@ -954,11 +917,10 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
// Structural handles start above every entity handle.
let mut w = W {
t: Vec::new(),
next: d.handseed.max(0x100).saturating_add(0x1000),
next: structural_start(d),
used: entity_handles(d).collect(),
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: hatch_reactors(d),
};
// Pre-allocate handles for block records.
@@ -1016,10 +978,6 @@ 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));
}
@@ -1137,11 +1095,11 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
for (n, h, b) in &user_blocks {
block(&mut w, (n, &b.description), h, b.base, if b.anonymous { 1 } else { 0 }, &mut b.entities.iter().map(|e| e.as_ref()), false);
}
// Generated geometry entities (dimension, arrowhead and table blocks) need handles.
// Generated geometry entities (dimension, arrowhead and table blocks) need handles; take
// them from the writer's allocator, which skips the drawing's own handles.
for (_, _, ents) in dim_defs.iter_mut().chain(arrow_defs.iter_mut()).chain(table_defs.iter_mut()) {
for e in ents.iter_mut().filter(|e| e.handle.0 == 0) {
e.handle = Handle(w.next);
w.next = w.next.saturating_add(1);
e.handle = Handle(w.next_handle());
}
}
for (n, h, ents) in &dim_defs {
+122 -16
View File
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
use cadcraft_color::Color;
use cadcraft_doc::{Circle, Common, Drawing, Ellipse, EntityKind, Layer, Line, LwPolyline, Space};
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3};
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3, bulge_to_arc};
use crate::{IoError, Result};
@@ -70,6 +70,8 @@ struct Parser {
verts_left: usize,
/// What was left out, by kind ([`LeftOut`]).
left_out: BTreeMap<LeftOut, usize>,
/// Shapes left out because their coordinates or extents overflow: invalid, not unsupported.
too_large: usize,
}
/// Drawn content the reader leaves out, named in the drawing's read note.
@@ -105,16 +107,23 @@ impl Parser {
elements: 0,
verts_left: MAX_TOTAL_VERTS,
left_out: BTreeMap::new(),
too_large: 0,
}
}
/// The read note on what was left out, if anything was.
fn note(&self) -> Option<String> {
if self.left_out.is_empty() {
return None;
/// The read notes on what was left out: what isn't read yet, then what is invalid.
fn notes(&self) -> Vec<String> {
let mut notes = Vec::new();
if !self.left_out.is_empty() {
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
notes.push(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")));
}
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
Some(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")))
match self.too_large {
0 => {}
1 => notes.push("SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent".into()),
n => notes.push(format!("SVG: {n} shapes were left out as invalid: their coordinates or size are too large to represent")),
}
notes
}
fn parse(&mut self, text: &str) -> Result<()> {
@@ -150,7 +159,7 @@ impl Parser {
};
self.left_out.insert(kind, count);
}
self.drawing.read_notes.extend(self.note());
self.drawing.read_notes.extend(self.notes());
Ok(())
}
@@ -218,12 +227,18 @@ impl Parser {
}
// Charge the vertices this entity retains against the shared document budget, so repeated
// flattened arcs/curves cannot amplify a compact path into unbounded geometry (CWE-400).
// A shape left out below was generated all the same, so it is charged too.
let verts = match &kind {
EntityKind::LwPolyline(p) => p.vertices.len(),
EntityKind::Spline(s) => s.control.len(),
_ => 1,
};
self.verts_left = self.verts_left.checked_sub(verts).ok_or_else(|| IoError::Format("SVG: too much generated geometry".into()))?;
// Finite numbers can still overflow through transforms and relative steps (`l1e308 0` twice).
if !finite(&kind) {
self.too_large += 1;
return Ok(());
}
let common = Common { layer: self.layer.clone(), ..Common::default() };
self.drawing.add(&Space::Model, common, kind).map(|_| ()).map_err(parse_err)
}
@@ -231,7 +246,10 @@ impl Parser {
/// A circle or ellipse through a transform. A circle stays a `CIRCLE` under rotations,
/// uniform scales and reflections; anything else becomes an `ELLIPSE` holding the axes
/// of the transformed shape — a linear map sends the unit circle to an ellipse whose
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`.
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`. With `B = [bx by]` the
/// ellipse is `center + B·(cos t, sin t)`; `B·Bᵀ` lives in the drawing plane, so its leading
/// eigenvector is the major axis's direction. `major` is that axis from the centre, as
/// [`Ellipse::major`] is everywhere else.
fn add_rounded(&mut self, center_user: Vec2, rx: f64, ry: f64) -> Result<()> {
let center = self.map(center_user);
let bx = self.map_vec(Vec2::new(rx, 0.0));
@@ -253,18 +271,15 @@ impl Parser {
if s_max <= f64::EPSILON {
return Ok(());
}
let axis = if xy.abs() <= 1e-12 * trace.max(1.0) {
let axis = if xy.abs() <= 1e-12 * trace {
if yy > xx { Vec2::new(0.0, 1.0) } else { Vec2::new(1.0, 0.0) }
} else {
let v = Vec2::new(xy, l_max - xx);
let l = len(v);
if l <= f64::EPSILON {
return Ok(());
}
v / l
// |v| ≥ |xy| > 1e-12·trace ≥ 0 here, so the division is never by zero.
v / len(v)
};
let ratio = (l_min.max(0.0).sqrt() / s_max).clamp(1e-9, 1.0);
let major = center + axis * s_max;
let major = axis * s_max;
self.add(EntityKind::Ellipse(Ellipse { center: v3(center), major: v3(major), ratio, start: 0.0, end: std::f64::consts::TAU }))
}
@@ -380,6 +395,79 @@ impl Parser {
}
}
/// Every coordinate of an entity the reader makes is finite, and so are its extents: a finite
/// centre and radius can still reach past the largest number.
fn finite(kind: &EntityKind) -> bool {
match kind {
EntityKind::Line(l) => l.a.is_finite() && l.b.is_finite(),
EntityKind::Circle(c) => {
c.center.is_finite()
&& c.radius.is_finite()
&& cadcraft_geom::Circle::new(c.center.xy(), c.radius).bounds().corners().iter().all(|p| p.is_finite())
}
EntityKind::Ellipse(e) => {
// Half the box is `hypot` of the major axis and the minor axis (`ratio` times it, turned).
let (m, r) = (e.major.xy(), e.ratio);
e.center.is_finite() && e.major.is_finite() && e.ratio.is_finite() && box_finite(e.center.xy(), m.x.hypot(r * m.y), m.y.hypot(r * m.x))
}
EntityKind::LwPolyline(p) => p.vertices.iter().all(|v| v.p.is_finite() && v.bulge.is_finite()) && bulges_finite(p),
EntityKind::Spline(s) => s.control.iter().all(|p| p.is_finite()),
// The SVG reader doesn't make these.
EntityKind::Point(_)
| EntityKind::Arc(_)
| EntityKind::Polyline3d(_)
| EntityKind::Helix(_)
| EntityKind::Ray(_)
| EntityKind::XLine(_)
| EntityKind::Text(_)
| EntityKind::MText(_)
| EntityKind::AttDef(_)
| EntityKind::Insert(_)
| EntityKind::Dimension(_)
| EntityKind::MLine(_)
| EntityKind::Leader(_)
| EntityKind::MLeader(_)
| EntityKind::Hatch(_)
| EntityKind::Solid(_)
| EntityKind::Trace(_)
| EntityKind::Face3d(_)
| EntityKind::PolyfaceMesh(_)
| EntityKind::Region(_)
| EntityKind::Viewport(_)
| EntityKind::Image(_)
| EntityKind::Wipeout(_)
| EntityKind::Table(_)
| EntityKind::Tolerance(_)
| EntityKind::Unknown(_) => true,
}
}
/// The box `centre ± (hx, hy)` is finite.
fn box_finite(c: Vec2, hx: f64, hy: f64) -> bool {
[c.x - hx, c.x + hx, c.y - hy, c.y + hy].iter().all(|v| v.is_finite())
}
/// Every arc segment of the polyline (a bulge between finite vertices) has a finite centre and
/// radius, and the quadrant points it passes through are finite.
fn bulges_finite(p: &LwPolyline) -> bool {
let n = p.vertices.len();
p.vertices.iter().enumerate().all(|(i, v)| {
let next = if i + 1 < n {
p.vertices.get(i + 1)
} else if p.closed {
p.vertices.first()
} else {
None
};
let Some((arc, _)) = next.and_then(|w| bulge_to_arc(v.p, w.p, v.bulge)) else { return true };
arc.center.is_finite()
&& arc.radius.is_finite()
&& (0..4)
.map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2)
.all(|a| !arc.contains_angle(a) || Vec2::polar(arc.center, arc.radius, a).is_finite())
})
}
/// One `M …` run of a `d` attribute.
struct Subpath {
start: Vec2,
@@ -471,4 +559,22 @@ mod tests {
assert_eq!(arc_of("M10 10 a20 20 0 1 0 20 20"), (true, false, spaced.2));
assert!(arc_of("M10 10 a20 20 0 10-20 20").0);
}
#[test]
fn extents_past_the_largest_number_are_not_finite() {
let ellipse = |c: Vec2, major: Vec2| EntityKind::Ellipse(Ellipse { center: v3(c), major: v3(major), ratio: 1.0, start: 0.0, end: 0.0 });
assert!(!finite(&ellipse(Vec2::new(1e308, 0.0), Vec2::new(1e308, 0.0))));
assert!(finite(&ellipse(Vec2::new(5e307, 0.0), Vec2::new(5e307, 0.0))));
// Turned, its box is wider than its axis: `centre ± major` is finite, the box isn't.
assert!(!finite(&ellipse(Vec2::new(6e307, 0.0), Vec2::new(9e307, 9e307))));
assert!(finite(&ellipse(Vec2::ZERO, Vec2::new(9e307, 9e307))));
// Half circles between the same finite points: bulging up passes 1.8e308, down doesn't.
let half = |bulge: f64| {
let (a, b) = (Vec2::new(0.0, 1.5e308), Vec2::new(1e308, 1.5e308));
let vertices = vec![PolyVertex::with_bulge(a, bulge), PolyVertex::new(b)];
EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false })
};
assert!(!finite(&half(-1.0)));
assert!(finite(&half(1.0)));
}
}
+117 -1
View File
@@ -2915,12 +2915,75 @@ fn svg_shapes_become_entities_in_millimetres() {
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.radius - 2.0).abs() < 1e-9 && (c.center.x - 10.0).abs() < 1e-9 && (c.center.y - 5.0).abs() < 1e-9, "{c:?}");
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x - e.center.x, e.major.y - e.center.y);
let major = Vec2::new(e.major.x, e.major.y);
assert!((major.len() - 4.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let l = first(&d, |k| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None });
assert!((l.a.y - 10.0).abs() < 1e-9 && (l.b.y).abs() < 1e-9, "{l:?}");
}
#[test]
fn svg_ellipse_major_axis_is_relative_to_its_centre() {
// Away from the origin: the major axis was stored as the absolute point centre + axis.
let svg = format!("{SVG_PAGE}<ellipse cx=\"15\" cy=\"2\" rx=\"2\" ry=\"1\"/><circle cx=\"15\" cy=\"2\" r=\"1\"/></svg>");
let d = read(svg.as_bytes(), "ellipse.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse", "Circle"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
assert!((e.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9, "{e:?}");
assert!((e.major.x.abs() - 2.0).abs() < 1e-9 && e.major.y.abs() < 1e-9 && e.major.z == 0.0, "{e:?}");
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9 && (c.radius - 1.0).abs() < 1e-9, "{c:?}");
}
#[test]
fn svg_rotated_ellipse_keeps_its_turn() {
// The page maps SVG (x, y) to (x, 10 - y); undo that, then rotate by -30°, to get back to the ellipse's own frame.
let svg = format!("{SVG_PAGE}<ellipse cx=\"0\" cy=\"0\" rx=\"20\" ry=\"10\" transform=\"rotate(30)\"/></svg>");
let d = read(svg.as_bytes(), "rotated.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
assert!((major.len() - 20.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let (s, c) = 30f64.to_radians().sin_cos();
let want = Vec2::new(20.0 * c, -20.0 * s);
assert!((major - want).len() < 1e-9 || (major + want).len() < 1e-9, "{e:?}");
let (ux, uy) = (e.center.x + major.x, 10.0 - (e.center.y + major.y));
let (x, y) = (c * ux + s * uy, -s * ux + c * uy);
assert!(((x / 20.0).powi(2) + (y / 10.0).powi(2) - 1.0).abs() < 1e-9, "{e:?}");
}
#[test]
fn svg_sheared_circle_has_the_axes_of_its_image() {
// matrix(1 0 1 1 0 0) is B = [[1, 1], [0, 1]]; the page then flips Y at one millimetre per unit.
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1 0 1 1 0 0)\"/></svg>");
let d = read(svg.as_bytes(), "sheared.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
let s_max = ((3.0 + 5f64.sqrt()) / 2.0).sqrt();
let s_min = ((3.0 - 5f64.sqrt()) / 2.0).sqrt();
assert!((major.len() - s_max).abs() < 1e-9 * s_max, "{e:?}");
assert!((e.ratio - s_min / s_max).abs() < 1e-9, "{e:?}");
let (ux, uy) = (major.x, -major.y);
let pre = Vec2::new(ux - uy, uy);
assert!((pre.len() - 1.0).abs() < 1e-9, "B⁻¹·major = {pre:?}, {e:?}");
assert!(major.x.abs() > 1e-3 && major.y.abs() > 1e-3, "{e:?}");
}
#[test]
fn svg_tiny_sheared_circle_has_the_axes_of_its_image() {
// Columns (1, 0.5)·1e-6 and (1, -0.5)·1e-6: far from orthogonal, though their dot product is tiny.
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1e-6 0.5e-6 1e-6 -0.5e-6 0 0)\"/></svg>");
let d = read(svg.as_bytes(), "tiny.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x, e.major.y);
assert!(major.y.abs() <= 1e-9 * major.x.abs(), "{e:?}");
let want = 2f64.sqrt() * 1e-6;
assert!((major.len() - want).abs() < 1e-9 * want, "{e:?}");
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
}
#[test]
fn svg_path_lines_curves_and_arcs() {
let svg = format!("{SVG_PAGE}<path d=\"M1 1 L5 1 C6 1 7 2 8 3\"/><path d=\"M0 0 A5 5 0 0 1 10 0 Z\"/></svg>");
@@ -3137,6 +3200,59 @@ fn svg_hostile_input_errors_without_panicking() {
assert!(deep.is_err(), "200 nested groups are refused, not walked");
}
#[test]
fn svg_coordinates_that_overflow_are_left_out() {
// Every number is finite; relative steps and transforms overflow them to infinity or NaN.
let svg = format!(
"{SVG_PAGE}<path d=\"M1e308 0 l1e308 0\"/><rect x=\"1e308\" width=\"1e308\" height=\"1\"/>\
<g transform=\"scale(1e308)\"><line x1=\"1e308\" y1=\"0\" x2=\"1\" y2=\"1\"/><circle r=\"1e308\"/></g>\
<g transform=\"scale(1e308,1)\"><ellipse rx=\"1e308\" ry=\"1\"/><path d=\"M0 0 C1e308 0 1 1 2 2\"/></g>\
<line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>"
);
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Line"]);
assert_eq!(d.read_notes, ["SVG: 6 shapes were left out as invalid: their coordinates or size are too large to represent"]);
}
#[test]
fn svg_shapes_whose_extents_overflow_are_left_out() {
// A finite centre and radius whose sum overflows; the same scale on smaller values stays
// representable.
let svg = format!("{SVG_PAGE}<g transform=\"scale(1e308)\"><circle cx=\"1\" cy=\"0\" r=\"1\"/><circle cx=\"0.5\" cy=\"0\" r=\"0.5\"/></g></svg>");
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Circle"]);
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.radius - 5e307).abs() < 1e293, "{}", c.radius);
assert_eq!(d.read_notes, ["SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"]);
}
/// A shape too large to represent is invalid, not something CADCraft doesn't read yet: it gets a
/// note of its own.
#[test]
fn svg_too_large_shapes_are_noted_apart_from_unread_content() {
let svg = format!("{SVG_PAGE}<text x=\"0\" y=\"5\">one</text><path d=\"M1e308 0 l1e308 0\"/><line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>");
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Line"]);
assert_eq!(
d.read_notes,
[
"SVG: CADCraft doesn't read these yet, so they were left out: 1 text",
"SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"
]
);
}
#[test]
fn svg_shapes_left_out_still_count_against_the_vertex_budget() {
// Each arc flattens to 10,000 chords under the non-uniform scale, and the doubled translation
// overflows to infinity, so each is left out; 820 of them make more than the 8,000,000 vertices
// a file may generate.
let arcs = "A1e9 1e9 0 0 1 2e9 0 A1e9 1e9 0 0 1 0 0 ".repeat(410);
let svg = format!("{SVG_PAGE}<g transform=\"translate(1e308 0) translate(1e308 0) scale(2 1)\"><path d=\"M0 0 {arcs}\"/></g></svg>");
let err = read(svg.as_bytes(), "huge.svg").err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("SVG: too much generated geometry"), "{err}");
}
#[test]
fn svg_no_geometry_yields_an_empty_drawing() {
let svg = format!("{SVG_PAGE}</svg>");
+360
View File
@@ -0,0 +1,360 @@
//! A hostile or damaged file can name a handle at the top of the range: an object's own handle,
//! or its `$HANDSEED`. A file's handles keep their identity, so a new object must take a free
//! handle instead of replacing the file's own object (#913).
#![cfg(not(target_arch = "wasm32"))]
use cadcraft_doc::{Common, DimKind, Dimension, Drawing, Entity, EntityKind, Handle, Line, Space};
use cadcraft_geom::Vec3;
const TOP: &str = "FFFFFFFFFFFFFFFF";
const NEAR_TOP: &str = "FFFFFFFFFFFEFFFF";
fn read(text: &str) -> Drawing {
cadcraft_io::read_dxf(text.as_bytes()).unwrap()
}
fn line(x: f64, y: f64) -> EntityKind {
EntityKind::Line(Line { a: Vec3::new(x, y, 0.0), b: Vec3::new(x + 1.0, y, 0.0) })
}
/// One line, with `entity_handle` when given, under a `$HANDSEED` of `seed`.
fn dxf(entity_handle: Option<&str>, seed: &str) -> String {
let handle = entity_handle.map(|h| format!("5\n{h}\n")).unwrap_or_default();
format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n{seed}\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n{handle}8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n"
)
}
fn distinct(d: &Drawing) -> Vec<Handle> {
d.model.iter().map(|e| e.handle).collect()
}
#[test]
fn an_object_at_the_top_of_the_handle_range_is_not_replaced_by_a_new_one() {
let mut d = read(&dxf(Some(TOP), TOP));
assert_eq!(d.model.len(), 1);
// The file's handle is its own; the new object takes a free handle below it.
assert!(d.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's handle was renumbered");
d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
assert_eq!(d.model.len(), 2, "the file's line was replaced by the new one");
let handles = distinct(&d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
}
#[test]
fn a_seed_at_the_top_of_the_handle_range_cannot_be_followed_twice() {
let mut d = read(&dxf(None, TOP));
let a = d.add(&Space::Model, Common::default(), line(0.0, 10.0)).unwrap();
let b = d.add(&Space::Model, Common::default(), line(0.0, 20.0)).unwrap();
assert_ne!(a, b, "two objects were given the same handle");
assert_eq!(d.model.len(), 3, "the second line replaced the first");
}
#[test]
fn an_ordinary_high_handle_keeps_its_identity() {
// Far below the top of the range a file's handles are its own: they stay as they are.
let h = "FFFFFFFF";
let mut d = read(&dxf(Some(h), h));
assert!(d.entity(Handle::parse_hex(h).unwrap()).is_some(), "the file's handle was renumbered");
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
assert!(n.0 > Handle::parse_hex(h).unwrap().0, "a new handle below the file's own");
}
#[test]
fn a_handle_just_below_the_top_survives_a_save() {
// Main keeps a file's handles exactly as written, even near the top of the range: handles
// are how other objects and other programs refer to an entity (#939's round-trip tests).
let mut d = read(&dxf(Some(NEAR_TOP), NEAR_TOP));
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
let bytes = cadcraft_io::write(&d, "near-top.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert!(r.entity(Handle::parse_hex(NEAR_TOP).unwrap()).is_some(), "the file's handle did not survive the save");
assert!(r.entity(n).is_some(), "the new handle did not survive the save");
}
#[test]
fn nine_objects_drawn_after_a_saturated_seed_save_and_reopen_distinct() {
// The nine-entity case from #2237: a saturated $HANDSEED, ordinary entity handles. Drawing
// after the load gives every object its own handle, and a save/reopen keeps them apart.
let mut d = read(&dxf(None, TOP));
for i in 0..9 {
d.add(&Space::Model, Common::default(), line(f64::from(i), 40.0)).unwrap();
}
let bytes = cadcraft_io::write(&d, "nine.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert_eq!(r.model.len(), 10, "the file's line and the nine drawn ones");
let handles = distinct(&r);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
}
/// The first handle in the reserved band above [`HANDLE_LIMIT`].
const BAND: &str = "FFFFFFFF00000000";
#[test]
fn a_seed_in_the_reserved_band_does_not_hand_out_the_files_handle() {
// #913's remaining case: a file says its next handle is FFFFFFFF00000000 and an object holds
// that handle. Following the seed once would hand the object's handle to the new object, and
// `EntityStore` would replace the file's line.
let mut d = read(&dxf(Some(BAND), BAND));
assert_eq!(d.model.len(), 1);
let n = d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
assert_ne!(n, Handle::parse_hex(BAND).unwrap(), "the new object took the file object's handle");
assert_eq!(d.model.len(), 2, "the file's line was replaced");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
let bytes = cadcraft_io::write(&d, "band-seed.dxf").unwrap();
let r = cadcraft_io::read_dxf(&bytes).unwrap();
let handles = distinct(&r);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
assert_eq!(r.model.len(), 2, "a line did not survive the save");
}
#[test]
fn a_save_does_not_give_a_structural_record_an_objects_handle() {
// The writer numbers its own records from `seed + 0x1000`; with the seed at the bottom of the
// reserved band that lands on the file's own handle. The file must keep one record per handle.
let object = "FFFFFFFF00001000";
let d = read(&dxf(Some(object), "FFFFFFFEFFFFFFFF"));
let bytes = cadcraft_io::write(&d, "band-structural.dxf").unwrap();
let tags = craft_dxf::parse(&bytes).unwrap();
// Record handles start with the TABLES section; before it the HEADER's `$HANDSEED` is the
// next free handle, not a record's.
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
assert_eq!(written.iter().filter(|h| h.as_str() == object).count(), 1, "the object's handle was not written exactly once");
let r = cadcraft_io::read_dxf(&bytes).unwrap();
assert!(r.entity(Handle::parse_hex(object).unwrap()).is_some(), "the file's object is gone");
}
/// A CADCraft-marked file with a handle-less block entity and an `ENTITIES` record that names
/// the handle the reader would give it. The marker means the reader skips the handle pre-scan,
/// so the two sections must still reserve against each other.
fn marked_file_with_handle_less_block_entity() -> String {
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
0\nENDBLK\n8\n0\n\
0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n5\n100\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n\
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
0\nENDSEC\n0\nEOF\n"
.to_string()
}
#[test]
fn a_marked_files_sections_reserve_handles_against_each_other() {
// The block entity has no handle of its own, so the reader gives it one; a later ENTITIES
// record must not be given the same handle, or one entity silently replaces the other.
let d = read(&marked_file_with_handle_less_block_entity());
assert_eq!(d.model.len(), 2, "one entity replaced the other");
let handles = distinct(&d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the ENTITIES line is gone");
}
/// A file whose BLOCKS holds a handle-less model-space entity and whose ENTITIES names the
/// last handle below the reserved band and the first handle in it. With `marked` the file names
/// CADCraft's own seed record, which narrows the reader's handle pre-scan to the entity sections.
fn file_with_reserved_band_entities(marked: bool) -> String {
let below = format!("{:X}", cadcraft_doc::HANDLE_LIMIT - 1);
let band = format!("{:X}", cadcraft_doc::HANDLE_LIMIT);
let objects = if marked {
"0\nSECTION\n2\nOBJECTS\n\
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
0\nENDSEC\n"
} else {
""
};
format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
0\nSECTION\n2\nBLOCKS\n\
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
0\nENDBLK\n8\n0\n\
0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n5\n{below}\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
0\nLINE\n5\n{band}\n8\n0\n10\n20.0\n20\n0.0\n30\n0.0\n11\n21.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n{objects}0\nEOF\n"
)
}
/// All three lines survive with their own handles: the handle-less block entity could not take
/// the reserved-band handle of the file's own ENTITIES record.
fn assert_three_lines_survive(d: &Drawing) {
assert_eq!(d.model.len(), 3, "one entity replaced another");
let handles = distinct(d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the line below the band is gone");
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 20.0)), "the line in the band is gone");
// The band's explicit handle stays with the record that names it.
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
let owner = d.model.iter().find(|e| e.handle == band).expect("the band handle was renumbered");
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 20.0), "the band handle moved to another line");
// The handle just below the band is the file's too, and it stays with its own record.
let below = Handle(cadcraft_doc::HANDLE_LIMIT - 1);
let owner = d.model.iter().find(|e| e.handle == below).expect("the below-band handle was renumbered");
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 10.0), "the below-band handle moved to another line");
}
#[test]
fn reserved_band_handles_in_entities_are_not_handed_to_a_handle_less_block_entity() {
// The handle below the reserved band is the file's, so the reader's next handle is the first
// handle in the band, which an ENTITIES record already owns. The seed cannot follow it
// (#913), so the handle is reserved for allocation instead: the handle-less model-space
// block entity must not take it and replace the file's line.
assert_three_lines_survive(&read(&file_with_reserved_band_entities(true)));
}
#[test]
fn reserved_band_handles_are_reserved_without_the_cadcraft_seed_record() {
// The same reservation holds when the pre-scan reads every section's handles: a handle in
// the band is the file's own there too, and still must not be given away.
assert_three_lines_survive(&read(&file_with_reserved_band_entities(false)));
}
#[test]
fn reservations_end_with_the_read_and_placed_objects_still_keep_their_handles() {
// The reservations only bridge the gap until a record is placed; a drawing does not carry
// them on (every undo step copies the drawing). The placed objects keep new ones off.
let mut d = read(&file_with_reserved_band_entities(true));
assert!(d.reserved_handles.is_empty(), "the reader's reservations outlived the read");
for i in 0..3 {
d.add(&Space::Model, Common::default(), line(f64::from(i), 50.0)).unwrap();
}
assert_eq!(d.model.len(), 6, "a new object replaced one of the file's");
assert_three_lines_survive_among(&d);
}
fn assert_three_lines_survive_among(d: &Drawing) {
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
assert!(d.model.iter().any(|e| e.handle == band && matches!(&e.kind, EntityKind::Line(l) if l.a.x == 20.0)), "the band line lost its handle");
let handles = distinct(d);
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
}
#[test]
fn generated_geometry_never_takes_a_handle_an_object_holds() {
// The drawing's own handles sit in the reserved band and the seed is at the top of the
// range, so the writer's structural numbering wraps into the band. Every other band handle
// is taken, so without a check the generated dimension block's entities land on an occupied
// one: the saved file would repeat a handle.
let mut d = Drawing::new_imperial();
d.handseed = u64::MAX - 1;
{
let model = d.space_mut(&Space::Model).unwrap();
for i in 0..200u64 {
let handle = Handle(cadcraft_doc::HANDLE_LIMIT + 1 + 2 * i);
model.push(Entity { handle, common: Common::default(), kind: line(i as f64, 0.0) });
}
model.push(Entity {
handle: Handle(0x200),
common: Common::default(),
kind: EntityKind::Dimension(Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(0.0, 1.0, 0.0),
text_mid: Vec3::new(1.0, 1.0, 0.0),
p13: Vec3::ZERO,
p14: Vec3::new(2.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 2.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: serde_json::Map::new(),
assoc: Vec::new(),
marks: Default::default(),
}),
});
}
let bytes = cadcraft_io::write(&d, "generated.dxf").unwrap();
let tags = craft_dxf::parse(&bytes).unwrap();
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle");
}
/// A line at the top handle with another application's xdata, and that application's object kept
/// from the file: a dictionary in the named object dictionary holding an XRECORD.
fn top_line_with_kept_objects() -> String {
let groups: &[(i32, &str)] = &[
(0, "SECTION"),
(2, "ENTITIES"),
(0, "LINE"),
(5, TOP),
(8, "0"),
(10, "0"),
(20, "0"),
(11, "10"),
(21, "0"),
(1001, "OTHER_APP"),
(1000, "tagged"),
(0, "ENDSEC"),
(0, "SECTION"),
(2, "OBJECTS"),
(0, "DICTIONARY"),
(5, "C"),
(330, "0"),
(100, "AcDbDictionary"),
(3, "OTHER_APP"),
(350, "50"),
(0, "DICTIONARY"),
(5, "50"),
(330, "C"),
(100, "AcDbDictionary"),
(281, "1"),
(3, "DATA"),
(360, "51"),
(0, "XRECORD"),
(5, "51"),
(330, "50"),
(100, "AcDbXrecord"),
(280, "1"),
(1, "kept"),
(0, "ENDSEC"),
(0, "EOF"),
];
groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
#[test]
fn records_added_on_save_after_the_top_handle_take_free_handles() {
// The writer adds the kept objects (and any application id the xdata needs) after its own
// records, numbered above the largest handle written. That is the file's line at the top of
// the range: counting on from it would give every added record the line's handle.
let d = read(&top_line_with_kept_objects());
let bytes = cadcraft_io::write(&d, "kept-top.dxf").unwrap();
let text = String::from_utf8_lossy(&bytes);
assert!(text.contains("\nkept"), "the kept XRECORD was not written");
let tags = craft_dxf::parse(&bytes).unwrap();
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
let unique: std::collections::HashSet<&String> = written.iter().collect();
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
assert_eq!(written.iter().filter(|h| h.as_str() == TOP).count(), 1, "the line's handle was not written exactly once");
let r = read(&String::from_utf8_lossy(&bytes));
assert!(r.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's line is gone");
}
@@ -26,7 +26,6 @@ fn preserves_or_refuses(path: &str, binary: bool) {
}
#[test]
#[ignore = "Confirmed DXF data loss: exhausted generated handles produce a successful save that reopens with no model entities"]
fn dxf_exhausted_handles_are_preserved_or_refused() {
for binary in [false, true] {
preserves_or_refuses("memory.dxf", binary);
@@ -16,8 +16,8 @@ fn import(transform: &str) -> (f64, f64) {
_ => None,
})
.unwrap();
let (dx, dy) = (e.major.x - e.center.x, e.major.y - e.center.y);
(dy.atan2(dx), e.ratio)
// `major` is the axis from the centre (#2821).
(e.major.y.atan2(e.major.x), e.ratio)
}
/// Major-axis angle and ratio of the image of the ellipse under the 2x2 map `[a c; b d]`, with
-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`