mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-26 21:30:06 +00:00
Compare commits
200
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3ed0682ab | ||
|
|
b1340f0697 | ||
|
|
b3bc4a7618 | ||
|
|
e66cdcec29 | ||
|
|
e59031a441 | ||
|
|
e0d64c676d | ||
|
|
a46923c96d | ||
|
|
61f4632e60 | ||
|
|
28fd71600c | ||
|
|
6525de811e | ||
|
|
daa6bf9063 | ||
|
|
b4ad0f3800 | ||
|
|
5096e1503f | ||
|
|
bcfc9a0786 | ||
|
|
9df34c448c | ||
|
|
edbdf0dd8f | ||
|
|
60ca94cd7a | ||
|
|
02bc55aaaa | ||
|
|
66d92125f1 | ||
|
|
40c4c7dac1 | ||
|
|
bb3b0cd5cd | ||
|
|
efa617fcd5 | ||
|
|
19290804a1 | ||
|
|
bb375992f4 | ||
|
|
f2d1845aee | ||
|
|
2c4ab18255 | ||
|
|
a37797484d | ||
|
|
900ed557f1 | ||
|
|
d7ea0ede4c | ||
|
|
0e3a58418f | ||
|
|
6a3199d5a4 | ||
|
|
c352afc399 | ||
|
|
292b6bc7ce | ||
|
|
45b20c6470 | ||
|
|
fbea6d1ffc | ||
|
|
22ba34c123 | ||
|
|
331c867476 | ||
|
|
bddbf390f7 | ||
|
|
5f24b4b667 | ||
|
|
6b403674ed | ||
|
|
2485c2e758 | ||
|
|
2ca9557d2c | ||
|
|
ea66defc0d | ||
|
|
2e9fe9462c | ||
|
|
4c1ea7d320 | ||
|
|
d290fc886f | ||
|
|
12eef22768 | ||
|
|
7c8f8ada92 | ||
|
|
ba344a894b | ||
|
|
b861b6c0a5 | ||
|
|
c9260d1b59 | ||
|
|
d2587c694e | ||
|
|
a06b236f0c | ||
|
|
4a4b1e2339 | ||
|
|
b5481e3bbf | ||
|
|
7244d2bc96 | ||
|
|
d8aa2c60dc | ||
|
|
b38215b7cf | ||
|
|
d955a3ccfc | ||
|
|
b55abde2a8 | ||
|
|
a3640199b6 | ||
|
|
91966ccc9d | ||
|
|
1fb86ec415 | ||
|
|
f99ae6956c | ||
|
|
b844248903 | ||
|
|
1cff8cd681 | ||
|
|
09944da2a4 | ||
|
|
433e51abc4 | ||
|
|
53d1790348 | ||
|
|
f4c3018003 | ||
|
|
239f8a32f0 | ||
|
|
9d214d6e88 | ||
|
|
d26d9ca01f | ||
|
|
c9286726ab | ||
|
|
138f447988 | ||
|
|
e425c71c44 | ||
|
|
c3f691264a | ||
|
|
aac7ae1cf2 | ||
|
|
849e6fd5c4 | ||
|
|
9e5889b782 | ||
|
|
3439895ec3 | ||
|
|
c089fdff1a | ||
|
|
ad1446c302 | ||
|
|
7eb9401f08 | ||
|
|
69a040acc6 | ||
|
|
2282d11b37 | ||
|
|
d659315743 | ||
|
|
5bff714e00 | ||
|
|
c4f139ac50 | ||
|
|
9ea307ede8 | ||
|
|
c125e9ebb8 | ||
|
|
ddee4e5bec | ||
|
|
092ab07e66 | ||
|
|
5195d9e5c8 | ||
|
|
4f4a3e94b6 | ||
|
|
68de3797cc | ||
|
|
b6ee77e3ac | ||
|
|
180ff4471d | ||
|
|
8fe5682b63 | ||
|
|
bc976e9bde | ||
|
|
b781f04784 | ||
|
|
c40fc740ab | ||
|
|
fb20f102df | ||
|
|
ee13c648df | ||
|
|
62a1a23288 | ||
|
|
12b7742384 | ||
|
|
927a417255 | ||
|
|
fc838dce98 | ||
|
|
a1142566b8 | ||
|
|
db8f6cc6e4 | ||
|
|
4b76e4a305 | ||
|
|
17888ad5c6 | ||
|
|
0edd056e8e | ||
|
|
74c183415b | ||
|
|
67c78743dd | ||
|
|
45300ee3a2 | ||
|
|
d6dc7131c3 | ||
|
|
96e62b4632 | ||
|
|
e20f5ed590 | ||
|
|
6133dc60bb | ||
|
|
8b1adcd8d5 | ||
|
|
19dcf74419 | ||
|
|
b573490901 | ||
|
|
5f4c2ed819 | ||
|
|
203ed93f51 | ||
|
|
20a9ac7433 | ||
|
|
22b2f7a5a9 | ||
|
|
ca3ff7997f | ||
|
|
a113667951 | ||
|
|
8af4b8a61b | ||
|
|
223beb2fb8 | ||
|
|
20463574de | ||
|
|
b44d5c3588 | ||
|
|
35462869e6 | ||
|
|
cf90a60626 | ||
|
|
1d16e82a49 | ||
|
|
8ecf3e6cac | ||
|
|
02dfd37d14 | ||
|
|
43207db68e | ||
|
|
69b214743d | ||
|
|
3c9b4be339 | ||
|
|
762b64268b | ||
|
|
c2b2545d0a | ||
|
|
c36cc6af34 | ||
|
|
03c8bac609 | ||
|
|
a9a3b35c91 | ||
|
|
6c81995e03 | ||
|
|
99ae84f39c | ||
|
|
04b56c4f4a | ||
|
|
cbf79599e2 | ||
|
|
de9f9ccc93 | ||
|
|
25afec0fa9 | ||
|
|
1b16f3caeb | ||
|
|
8178e578c2 | ||
|
|
fe1c3eeeab | ||
|
|
93e2255722 | ||
|
|
5513565da9 | ||
|
|
9a6f025c47 | ||
|
|
06491fc757 | ||
|
|
897f53c7b3 | ||
|
|
97b531eaae | ||
|
|
b872742e42 | ||
|
|
b91fa88224 | ||
|
|
3e8f468fe3 | ||
|
|
cc69082a85 | ||
|
|
e6f2ea0405 | ||
|
|
d56ead7ca4 | ||
|
|
dc07a1032d | ||
|
|
6c2d37983e | ||
|
|
45f9b5653e | ||
|
|
d79185ed8d | ||
|
|
6d3f63752b | ||
|
|
3944717ca2 | ||
|
|
c319cd7ae4 | ||
|
|
a303ff433c | ||
|
|
f126a24c42 | ||
|
|
55d8db69dc | ||
|
|
b3ff5505c5 | ||
|
|
bc36b99152 | ||
|
|
d8c37cc6c1 | ||
|
|
8391c1f0de | ||
|
|
7941757ed3 | ||
|
|
d325681051 | ||
|
|
e5dd7290e9 | ||
|
|
000dbb4383 | ||
|
|
508c28654d | ||
|
|
b57647de0a | ||
|
|
12e56da913 | ||
|
|
a819d82028 | ||
|
|
9ce57972c8 | ||
|
|
f49355f6c2 | ||
|
|
99e973f71f | ||
|
|
230d5107fb | ||
|
|
23a973edfa | ||
|
|
95429bb286 | ||
|
|
54e34b02ba | ||
|
|
9a1bd48a26 | ||
|
|
e57786e726 | ||
|
|
4d3ceea73b | ||
|
|
38e98e43c0 |
+1
-1
@@ -87,7 +87,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
|
||||
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
|
||||
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
|
||||
|
||||
|
||||
Generated
+1272
-86
File diff suppressed because it is too large
Load Diff
+36
-32
@@ -14,11 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
# internal
|
||||
cadcraft-geom = { path = "crates/geom" }
|
||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
cadcraft-color = { path = "crates/color" }
|
||||
cadcraft-doc = { path = "crates/doc" }
|
||||
cadcraft-constraints = { path = "crates/constraints" }
|
||||
@@ -28,19 +28,19 @@ cadcraft-io = { path = "crates/io" }
|
||||
cadcraft-engine = { path = "crates/engine" }
|
||||
cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
# Delimited text (CSV/TSV) parsing (shared Craft library).
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
@@ -74,8 +74,12 @@ encoding_rs = "0.8.35"
|
||||
quick-xml = "0.42"
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -85,7 +89,7 @@ egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
web-time = "1.1"
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -117,23 +121,23 @@ debug = 0
|
||||
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
|
||||
# (Cargo ignores dependency-local patches).
|
||||
[patch.crates-io]
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -89,9 +89,15 @@
|
||||
line, prompts with clickable `[Keywords]`, AutoComplete, object snaps, polar tracking, ortho,
|
||||
direct distance entry, window and crossing selection, grips, and right-click-to-repeat behave
|
||||
the way decades of drafting habit expect.
|
||||
- **Open files.** DXF is read and written natively (ASCII and binary, R12 through 2018), and DWG
|
||||
files (R13 through 2018) open and save through the open-source acadrust library. Export to SVG
|
||||
and PNG today.
|
||||
- **Open files.** DXF is read natively (R12 through 2018, with binary support from R13) and
|
||||
written as 2000 through 2018 (ASCII and binary). DWG files (R13 through 2018; R13 and R14
|
||||
untested, 2018 tested only on synthetic files) open through the open-source acadrust library
|
||||
and save as 2000 through 2018. New drawings default to
|
||||
2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format
|
||||
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled
|
||||
drawings; drawings with a file keep their own version, subject to supported-version mapping
|
||||
and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
|
||||
saves. Export to SVG and PNG today.
|
||||
- **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS
|
||||
(universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser.
|
||||
- **Built for agents.** Every menu item, tool and prompt is a command. Agents can type at the
|
||||
@@ -114,7 +120,7 @@ numbers):
|
||||
| Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour |
|
||||
| Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font |
|
||||
| Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks |
|
||||
| Files | DXF read (R12–2018, ASCII and binary) and write (R2000), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library) and write (R2000); PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) |
|
||||
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled drawings; drawings with a file keep their own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
|
||||
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
|
||||
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
|
||||
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
|
||||
|
||||
@@ -60,6 +60,7 @@ fn install_io() {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
|
||||
@@ -154,6 +154,9 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io
|
||||
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
|
||||
io.errln(format_args!("{m}"));
|
||||
}
|
||||
for note in cadcraft_engine::cmd::file::dwg_notes(d) {
|
||||
io.errln(format_args!("{note}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first
|
||||
//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A DXF with a 256-element linetype and a line drawn with it.
|
||||
fn dxf() -> String {
|
||||
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n");
|
||||
for i in 0..256 {
|
||||
s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" });
|
||||
}
|
||||
s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_dwg_notes_the_linetypes_it_cuts() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = dir.join("long.dxf");
|
||||
std::fs::write(&source, dxf()).unwrap();
|
||||
let source = source.to_str().unwrap();
|
||||
let notes =
|
||||
|out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::<Vec<_>>();
|
||||
|
||||
let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]);
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
assert!(
|
||||
matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
|
||||
let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]);
|
||||
assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
mod cli;
|
||||
mod drafting_spacing;
|
||||
mod help;
|
||||
// DWG output needs craft-dwg's bridge.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod ltype_dwg_note;
|
||||
mod mcp_connect;
|
||||
mod pdf_import;
|
||||
mod skipped_records;
|
||||
|
||||
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -54,11 +54,12 @@ mod web {
|
||||
if let Some(bridge) = &self.2 {
|
||||
bridge.report_dirty(&self.0);
|
||||
}
|
||||
self.0.close_path(ctx);
|
||||
}
|
||||
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
|
||||
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
self.0.before_input(ctx);
|
||||
}
|
||||
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
@@ -134,6 +135,7 @@ mod web {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
@@ -166,6 +168,7 @@ mod web {
|
||||
canvas,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
|
||||
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
|
||||
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
|
||||
let control = crate::api::install(cc.egui_ctx.clone());
|
||||
|
||||
@@ -94,7 +94,7 @@ mod tests {
|
||||
let mut ui = UiState::default();
|
||||
let before = serde_json::to_value(&ui).unwrap();
|
||||
let mut invalid = ui.clone();
|
||||
invalid.docking.layout.root = None;
|
||||
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
|
||||
assert!(save(&invalid).is_err());
|
||||
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
|
||||
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
|
||||
|
||||
@@ -41,22 +41,18 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
|
||||
craft-ui = { workspace = true, features = ["native-windows"] }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
|
||||
# controls and under floating panels.
|
||||
craft-window = { workspace = true }
|
||||
muda = { version = "0.21", default-features = false }
|
||||
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
|
||||
# (system_animations.rs). Already in Cargo.lock through muda.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
|
||||
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
|
||||
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
|
||||
# The same winit eframe uses (the storytold fork, patched in the workspace).
|
||||
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
|
||||
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
|
||||
|
||||
+26
-37
@@ -61,9 +61,6 @@ struct App {
|
||||
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
|
||||
#[cfg(target_os = "macos")]
|
||||
menus_in_window: bool,
|
||||
/// The `movable` flag last set on the main window.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
@@ -141,17 +138,18 @@ impl eframe::App for App {
|
||||
if std::mem::take(&mut self.cad.quit_requested) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
self.cad.close_path(ctx);
|
||||
}
|
||||
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
|
||||
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
|
||||
/// runtime.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
follow_desktop(raw, self.desktop_theme.current());
|
||||
self.cad.raw_input_hook(ctx, raw);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
self.cad.before_input(ctx);
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
self.cad.guarded_ui(ui);
|
||||
#[cfg(target_os = "macos")]
|
||||
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
|
||||
}
|
||||
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
|
||||
/// crash leaves them for recovery).
|
||||
@@ -199,6 +197,7 @@ pub fn install_io() {
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -302,17 +301,15 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
|
||||
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
|
||||
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
|
||||
/// its render pass ([`stencil_bits`]).
|
||||
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
|
||||
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
|
||||
let viewport = egui::ViewportBuilder::default()
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_inner_size([1600.0, 1000.0])
|
||||
.with_min_inner_size(MIN_INNER_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_app_id(os_window::app_id());
|
||||
eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_inner_size([1600.0, 1000.0])
|
||||
.with_min_inner_size(MIN_INNER_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false)
|
||||
.with_app_id(os_window::app_id()),
|
||||
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
|
||||
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
|
||||
// restored window on the monitors that are connected now.
|
||||
persist_window: true,
|
||||
@@ -553,6 +550,9 @@ fn main() -> eframe::Result {
|
||||
if stencil == 0 {
|
||||
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
|
||||
}
|
||||
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
|
||||
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
|
||||
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
|
||||
let persistence_path = vars
|
||||
.portable_storage_file
|
||||
.clone()
|
||||
@@ -562,7 +562,7 @@ fn main() -> eframe::Result {
|
||||
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
|
||||
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
|
||||
persistence_path: persistence_path.clone(),
|
||||
..window_options(restores_window(persistence_path.as_deref()), stencil)
|
||||
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
@@ -585,22 +585,12 @@ fn main() -> eframe::Result {
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
|
||||
if forced_x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
|
||||
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
|
||||
// close request for the window instead, so it asks first, as the close button does.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||
b.with_close_requested_on_terminate(true);
|
||||
}));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -613,6 +603,7 @@ fn main() -> eframe::Result {
|
||||
os_window::name_for(os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
|
||||
let mut app = CadApp::new(Session::empty(), services());
|
||||
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
|
||||
// it, so nothing after `run_native` can be relied on there.
|
||||
@@ -675,7 +666,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
app.session.set_lisp_support_dir(Some(support));
|
||||
}
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
|
||||
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
|
||||
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
|
||||
}
|
||||
@@ -726,8 +717,6 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
menus_in_window: vars.no_native_menu == Switch::On,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events,
|
||||
}))
|
||||
}),
|
||||
@@ -765,7 +754,7 @@ mod tests {
|
||||
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
|
||||
#[test]
|
||||
fn the_first_launch_opens_centred() {
|
||||
let o = window_options(false, STENCIL_BITS);
|
||||
let o = window_options(false, STENCIL_BITS, None);
|
||||
assert!(o.centered, "centred on launch");
|
||||
assert!(o.persist_window, "the window state is saved for the next launch");
|
||||
}
|
||||
@@ -773,7 +762,7 @@ mod tests {
|
||||
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
|
||||
#[test]
|
||||
fn a_saved_window_reopens_where_it_was() {
|
||||
let o = window_options(true, STENCIL_BITS);
|
||||
let o = window_options(true, STENCIL_BITS, None);
|
||||
assert!(!o.centered, "centring would move a restored window");
|
||||
assert!(o.persist_window);
|
||||
}
|
||||
@@ -798,8 +787,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_window_carries_the_chosen_stencil_bits() {
|
||||
for bits in [0, STENCIL_BITS] {
|
||||
assert_eq!(window_options(false, bits).stencil_buffer, bits);
|
||||
assert_eq!(window_options(true, bits).stencil_buffer, bits);
|
||||
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
|
||||
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
|
||||
}
|
||||
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
|
||||
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
|
||||
|
||||
@@ -15,6 +15,9 @@ pub struct NativeMenu {
|
||||
items: HashMap<String, (String, String, MenuItem)>,
|
||||
submenus: Vec<(String, Submenu)>,
|
||||
predefined: Vec<(&'static str, PredefinedMenuItem)>,
|
||||
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
|
||||
/// muda's predefined Quit ends the process through `terminate:` without asking.
|
||||
quit: MenuItem,
|
||||
language: &'static str,
|
||||
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
|
||||
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
|
||||
@@ -58,7 +61,6 @@ impl NativeMenu {
|
||||
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
|
||||
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
|
||||
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
|
||||
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
|
||||
];
|
||||
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
|
||||
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
|
||||
@@ -69,6 +71,8 @@ impl NativeMenu {
|
||||
let _ = app_menu.append(&PredefinedMenuItem::separator());
|
||||
}
|
||||
}
|
||||
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
|
||||
let _ = app_menu.append(&quit);
|
||||
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
|
||||
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
|
||||
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
|
||||
@@ -85,6 +89,7 @@ impl NativeMenu {
|
||||
items,
|
||||
submenus,
|
||||
predefined,
|
||||
quit,
|
||||
language,
|
||||
last_refresh: f64::NEG_INFINITY,
|
||||
recent: app.ui.recent_files.clone(),
|
||||
@@ -114,7 +119,9 @@ impl NativeMenu {
|
||||
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
|
||||
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
|
||||
while let Ok(ev) = self.events.try_recv() {
|
||||
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
|
||||
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
|
||||
ctx.request_repaint();
|
||||
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
|
||||
if cmd == "ui.discord" {
|
||||
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
|
||||
} else {
|
||||
@@ -133,6 +140,7 @@ impl NativeMenu {
|
||||
for (label, item) in &self.predefined {
|
||||
item.set_text(i18n::tr(language, label));
|
||||
}
|
||||
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
|
||||
for (label, submenu) in &self.submenus {
|
||||
submenu.set_text(i18n::tr_menu(language, label));
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@ mod tests {
|
||||
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
|
||||
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
|
||||
ui.docking = app.ui.docking;
|
||||
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
|
||||
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
|
||||
ui.show_toolsets = false;
|
||||
store.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
|
||||
@@ -263,9 +263,9 @@ mod tests {
|
||||
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
|
||||
assert!(!reloaded.show_toolsets);
|
||||
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
|
||||
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
|
||||
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
|
||||
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
|
||||
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
|
||||
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
@@ -293,8 +293,8 @@ mod tests {
|
||||
assert_eq!(ui.toolset_tab, "Modeling");
|
||||
assert_eq!(ui.history_lines, 4);
|
||||
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
|
||||
assert_eq!(ui.docking.layout, default_workspace().layout);
|
||||
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
|
||||
assert_eq!(ui.docking.layout(), default_workspace().layout());
|
||||
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,4 @@ allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -238,8 +238,9 @@ mod tests {
|
||||
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
|
||||
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
|
||||
}
|
||||
// An unclamped (periodic) spline has no ends.
|
||||
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
|
||||
assert!(spline_end(&closed, false).is_none());
|
||||
// An unclamped spline has no ends: one whose control points wrap round.
|
||||
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
|
||||
let closed = GSpline::fit_with(&fit, true, cadcraft_geom::FitOptions { knots: cadcraft_geom::KnotParam::Uniform, ..Default::default() });
|
||||
assert!(closed.wraps() && spline_end(&closed, false).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
+22
-14
@@ -105,9 +105,12 @@ pub struct Drawing {
|
||||
pub foreign: std::sync::Arc<foreign::Foreign>,
|
||||
/// Layers in table order; [`Drawing::layer`] looks them up by name.
|
||||
pub layers: NamedList<Layer>,
|
||||
pub linetypes: Vec<Linetype>,
|
||||
pub text_styles: Vec<TextStyle>,
|
||||
pub dim_styles: Vec<DimStyle>,
|
||||
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
|
||||
pub linetypes: NamedList<Linetype>,
|
||||
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
|
||||
pub text_styles: NamedList<TextStyle>,
|
||||
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
|
||||
pub dim_styles: NamedList<DimStyle>,
|
||||
pub mleader_styles: Vec<MLeaderStyle>,
|
||||
pub table_styles: Vec<TableStyle>,
|
||||
/// Multiline styles (MLSTYLE); STANDARD is always there.
|
||||
@@ -117,7 +120,8 @@ pub struct Drawing {
|
||||
pub model: EntityStore,
|
||||
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
|
||||
pub model_page: Option<PageSetup>,
|
||||
pub layouts: Vec<Layout>,
|
||||
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
|
||||
pub layouts: NamedList<Layout>,
|
||||
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
||||
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
|
||||
pub active_layout: Option<String>,
|
||||
@@ -204,16 +208,17 @@ impl Drawing {
|
||||
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype::continuous(),
|
||||
],
|
||||
text_styles: vec![TextStyle::default()],
|
||||
dim_styles: vec![DimStyle::default()],
|
||||
]
|
||||
.into(),
|
||||
text_styles: vec![TextStyle::default()].into(),
|
||||
dim_styles: vec![DimStyle::default()].into(),
|
||||
mleader_styles: vec![MLeaderStyle::default()],
|
||||
table_styles: vec![TableStyle::default()],
|
||||
mline_styles: vec![MLineStyle::default()],
|
||||
blocks: NamedMap::default(),
|
||||
model: EntityStore::new(),
|
||||
model_page: None,
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
|
||||
active_layout: None,
|
||||
views: Vec::new(),
|
||||
vports: Vec::new(),
|
||||
@@ -323,17 +328,19 @@ impl Drawing {
|
||||
}
|
||||
/// The first layer named `name`, without case, to change.
|
||||
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
|
||||
let i = self.layers.position_by_name(name)?;
|
||||
self.layers.get_mut(i)
|
||||
self.layers.by_name_mut(name)
|
||||
}
|
||||
/// The first linetype named `name`, without case.
|
||||
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
|
||||
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.linetypes.by_name(name)
|
||||
}
|
||||
/// The first text style named `name`, without case.
|
||||
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
|
||||
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.text_styles.by_name(name)
|
||||
}
|
||||
/// The first dimension style named `name`, without case.
|
||||
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
|
||||
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.dim_styles.by_name(name)
|
||||
}
|
||||
|
||||
/// The DIM* variables in the header that differ from the current dimension style, as
|
||||
@@ -405,8 +412,9 @@ impl Drawing {
|
||||
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
|
||||
self.blocks.by_name(name)
|
||||
}
|
||||
/// The first layout named `name`, without case.
|
||||
pub fn layout(&self, name: &str) -> Option<&Layout> {
|
||||
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.layouts.by_name(name)
|
||||
}
|
||||
|
||||
/// Add a layer if missing; returns whether it was created.
|
||||
|
||||
+86
-14
@@ -1,10 +1,12 @@
|
||||
//! The layer and block tables, whose names are looked up without case through an index instead of a
|
||||
//! scan once a table is large and looked up often.
|
||||
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles
|
||||
//! and layouts), whose names are looked up without case through an index instead of a scan once a
|
||||
//! table is large and looked up often.
|
||||
//!
|
||||
//! [`Drawing::layer`](crate::Drawing::layer) and [`Drawing::block`](crate::Drawing::block) run for
|
||||
//! every entity while a drawing is read, measured and drawn. Scanning the table on each made a file
|
||||
//! of N layers, or of N blocks and N references to blocks it does not have, cost N² name
|
||||
//! comparisons: tens of seconds to open at a few tens of thousands (#1924, F-04).
|
||||
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
|
||||
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
|
||||
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
|
||||
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
|
||||
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
|
||||
//!
|
||||
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
|
||||
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
|
||||
@@ -105,14 +107,21 @@ pub trait Named {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
impl Named for crate::Layer {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
/// Entries named by their `name` field.
|
||||
macro_rules! named_by_field {
|
||||
($($t:ty),*) => {$(
|
||||
impl Named for $t {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout);
|
||||
|
||||
/// A list of named entries in their own order (the drawing's layers). It reads and changes as a
|
||||
/// `Vec`; [`NamedList::by_name`] finds the first entry of a name without case.
|
||||
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
|
||||
/// dimension styles and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the
|
||||
/// first entry of a name without case.
|
||||
pub struct NamedList<T> {
|
||||
list: Vec<T>,
|
||||
index: Lazy<usize>,
|
||||
@@ -131,6 +140,12 @@ impl<T: Named> NamedList<T> {
|
||||
pub fn by_name(&self, name: &str) -> Option<&T> {
|
||||
self.position_by_name(name).and_then(|i| self.list.get(i))
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case, to change (which drops the index).
|
||||
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
|
||||
let i = self.position_by_name(name)?;
|
||||
self.get_mut(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for NamedList<T> {
|
||||
@@ -318,8 +333,8 @@ impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::MIN_INDEXED;
|
||||
use crate::{Block, Drawing, Layer};
|
||||
use super::{MIN_INDEXED, Named, NamedList};
|
||||
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
|
||||
|
||||
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
|
||||
/// added (a miss).
|
||||
@@ -331,6 +346,63 @@ mod tests {
|
||||
d.layers.index.index.get().is_some()
|
||||
}
|
||||
|
||||
fn indexed<T>(list: &NamedList<T>) -> bool {
|
||||
list.index.index.get().is_some()
|
||||
}
|
||||
|
||||
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
|
||||
/// name without case), by pointer, for the list's names and `extra`.
|
||||
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
|
||||
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
|
||||
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
|
||||
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
|
||||
/// order finds (the first of a name without case): while they scan, once the table is indexed,
|
||||
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
|
||||
/// changed the first of a name and dropped the index.
|
||||
#[test]
|
||||
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
|
||||
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
|
||||
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
|
||||
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
|
||||
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
|
||||
let check = |d: &Drawing, extra: &[&str]| {
|
||||
check_list(&d.linetypes, |n| d.linetype(n), extra);
|
||||
check_list(&d.text_styles, |n| d.text_style(n), extra);
|
||||
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
|
||||
check_list(&d.layouts, |n| d.layout(n), extra);
|
||||
};
|
||||
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
|
||||
// The first round scans until the index is built; the second reads only the index.
|
||||
check(&d, &["dash", "missing"]);
|
||||
assert!(all_indexed(&d));
|
||||
check(&d, &["dash", "missing"]);
|
||||
|
||||
// The first of a name changes, and the later one of that name is found after it.
|
||||
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
|
||||
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
|
||||
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
|
||||
check(&d, &["SEVEN", "n7"]);
|
||||
assert!(all_indexed(&d));
|
||||
// A miss changes nothing and keeps the index.
|
||||
assert!(d.dim_styles.by_name_mut("none").is_none());
|
||||
assert!(indexed(&d.dim_styles));
|
||||
check(&d, &["dash"]);
|
||||
}
|
||||
|
||||
fn blocks_indexed(d: &Drawing) -> bool {
|
||||
d.blocks.index.index.get().is_some()
|
||||
}
|
||||
|
||||
@@ -988,3 +988,60 @@ fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// Table entries for the cost tests below.
|
||||
const NAMED: usize = 40_000;
|
||||
|
||||
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
|
||||
/// about 50 bytes and not a length check, as in a crafted file.
|
||||
fn long_name(kind: &str, tail: &str) -> String {
|
||||
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
|
||||
}
|
||||
|
||||
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
|
||||
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
|
||||
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
|
||||
}
|
||||
|
||||
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
|
||||
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
|
||||
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
|
||||
/// comparisons (#1924).
|
||||
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
|
||||
let started = std::time::Instant::now();
|
||||
for i in 0..NAMED {
|
||||
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
|
||||
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
|
||||
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
|
||||
}
|
||||
|
||||
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
|
||||
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
|
||||
#[test]
|
||||
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
|
||||
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
|
||||
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
|
||||
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
|
||||
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
|
||||
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
|
||||
|
||||
@@ -19,6 +19,7 @@ mod edit;
|
||||
mod leader;
|
||||
mod linear;
|
||||
mod mleader;
|
||||
mod qleader;
|
||||
mod radial;
|
||||
|
||||
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
|
||||
@@ -27,6 +28,7 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
|
||||
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
|
||||
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
|
||||
use mleader::{MLeaderM, run_leader, run_mleader};
|
||||
use qleader::{QLeaderM, run_qleader};
|
||||
use radial::{RadialM, run_diameter, run_radius};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -93,6 +95,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.alias(&["lead"])
|
||||
.params("{points: [[x,y]...], text?}")
|
||||
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
|
||||
CommandSpec::new("qleader", "Quick Leader", run_qleader)
|
||||
.alias(&["le"])
|
||||
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
|
||||
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
|
||||
CommandSpec::new("dimstyle.update", "Update", run_update)
|
||||
.menu(&["Dimension", "Update"])
|
||||
.params("{handles?}")
|
||||
|
||||
@@ -42,8 +42,13 @@ pub(super) struct LeaderM {
|
||||
}
|
||||
|
||||
/// What follows the leader.
|
||||
enum Annotation {
|
||||
pub(super) enum Annotation {
|
||||
Text(Vec<String>),
|
||||
/// QLEADER's text: its lines and its width.
|
||||
Quick {
|
||||
lines: Vec<String>,
|
||||
width: f64,
|
||||
},
|
||||
/// A copy of a text or multiline text: its contents, height, width and style.
|
||||
Copy(MText),
|
||||
None,
|
||||
@@ -263,13 +268,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
|
||||
}
|
||||
|
||||
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
|
||||
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
|
||||
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
|
||||
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
|
||||
let z = sizes(s);
|
||||
// The side the leader runs to: right unless its last segment runs left.
|
||||
let dir = if end.x < before.x { -1.0 } else { 1.0 };
|
||||
let mut vertices = pts.to_vec();
|
||||
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
|
||||
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
|
||||
let d = end - before;
|
||||
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
|
||||
// the leader ends half the text height lower.
|
||||
@@ -310,6 +315,23 @@ fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Ann
|
||||
columns: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Quick { lines, width } => {
|
||||
// The middle of the first line level with the end on the right, of the last line on
|
||||
// the left, whatever DIMTAD.
|
||||
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
|
||||
Some(s.add_entity(EntityKind::MText(MText {
|
||||
insert: v3(end + Vec2::new(dir * z.gap, lift)),
|
||||
height: z.text,
|
||||
width,
|
||||
attach,
|
||||
rotation: 0.0,
|
||||
style: z.text_style,
|
||||
contents: lines.join("\\P"),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Copy(m) => {
|
||||
let lift = if z.above { z.gap } else { 0.0 };
|
||||
let attach = if dir > 0.0 { 4 } else { 6 };
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
|
||||
//! synthetic drawings): up to three points, a text width, then lines of text.
|
||||
//!
|
||||
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
|
||||
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
|
||||
//! as wide as the width given: with the middle of its first line level with the end when the
|
||||
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
|
||||
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::leader::{Annotation, add_leader};
|
||||
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
|
||||
use crate::cmd::size_param;
|
||||
|
||||
/// QLEADER's default number of leader points.
|
||||
const MAX_POINTS: usize = 3;
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq)]
|
||||
enum Ask {
|
||||
#[default]
|
||||
Points,
|
||||
Width,
|
||||
FirstLine,
|
||||
NextLine,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct QLeaderM {
|
||||
ask: Ask,
|
||||
pts: Vec<Vec2>,
|
||||
width: f64,
|
||||
lines: Vec<String>,
|
||||
}
|
||||
|
||||
impl Interactive for QLeaderM {
|
||||
fn name(&self) -> &'static str {
|
||||
"QLEADER"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let last = self.pts.last().copied();
|
||||
match self.ask {
|
||||
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
|
||||
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
|
||||
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
|
||||
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
|
||||
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
|
||||
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match self.ask {
|
||||
Ask::Points => match i {
|
||||
Input::Point(p) => {
|
||||
self.pts.push(p);
|
||||
if self.pts.len() == MAX_POINTS {
|
||||
self.ask = Ask::Width;
|
||||
}
|
||||
}
|
||||
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
|
||||
// Enter after one point: no leader.
|
||||
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
|
||||
Input::Enter => self.ask = Ask::Width,
|
||||
_ => {}
|
||||
},
|
||||
Ask::Width => {
|
||||
// A point gives the width as its distance from the leader's end; a negative
|
||||
// width is none.
|
||||
let width = match i {
|
||||
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
|
||||
Input::Text(t) => crate::units::parse_distance(&t),
|
||||
Input::Enter => Some(0.0),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let finite = width.filter(|w| w.is_finite());
|
||||
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
|
||||
self.ask = Ask::FirstLine;
|
||||
}
|
||||
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
|
||||
Ask::FirstLine | Ask::NextLine => match i {
|
||||
Input::Text(t) if !t.is_empty() => {
|
||||
self.lines.push(t);
|
||||
self.ask = Ask::NextLine;
|
||||
}
|
||||
Input::Text(_) | Input::Enter => {
|
||||
let lines = std::mem::take(&mut self.lines);
|
||||
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
|
||||
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
}
|
||||
|
||||
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
|
||||
/// as `width`, placed as the command line places them. The handles of the leader and its text.
|
||||
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("points").is_none_or(Value::is_null) {
|
||||
return Err(bad("qleader", "`points` is required"));
|
||||
}
|
||||
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
|
||||
if !(2..=MAX_POINTS).contains(&pts.len()) {
|
||||
return Err(bad("qleader", "`points` takes 2 or 3 points"));
|
||||
}
|
||||
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
|
||||
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
|
||||
return Err(bad("qleader", "`text` must be a string"));
|
||||
}
|
||||
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
|
||||
// would otherwise sit level with a blank last line. Text with nothing left is no text.
|
||||
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
|
||||
while lines.last().is_some_and(String::is_empty) {
|
||||
lines.pop();
|
||||
}
|
||||
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
|
||||
let hs = add_leader(s, &pts, false, true, ann)?;
|
||||
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -386,16 +386,18 @@ fn fmt(v: f64) -> String {
|
||||
format!("{v:.4}")
|
||||
}
|
||||
|
||||
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
|
||||
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores. A whole
|
||||
/// number as typed: AutoCAD 2024 takes +3 and 03 at its array counts and refuses 5.0, 1e1, 8/2
|
||||
/// and 3' (measured at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY).
|
||||
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
|
||||
match i {
|
||||
Input::Enter => Ok(Some(cur)),
|
||||
Input::Text(t) => t
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.parse::<u64>()
|
||||
.ok()
|
||||
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
|
||||
.map(|v| Some(v as u64))
|
||||
.filter(|v| (1..=max).contains(v))
|
||||
.map(Some)
|
||||
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
|
||||
_ => Ok(None),
|
||||
}
|
||||
@@ -437,7 +439,7 @@ fn run_array(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused.
|
||||
fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
|
||||
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))),
|
||||
|
||||
+183
-60
@@ -403,13 +403,14 @@ fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// MINSERT's JSON form: INSERT's parameters and the grid.
|
||||
fn run_minsert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A whole number, as the array commands' JSON counts are: 2.0 and 1e2 are refused too.
|
||||
let count = |key: &str| -> Result<u32> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(1),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
|
||||
.map(|n| n as u32)
|
||||
.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|n| (1..=Grid::MAX).contains(n))
|
||||
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
|
||||
}
|
||||
};
|
||||
@@ -833,11 +834,35 @@ enum InsStage {
|
||||
/// rows).
|
||||
Cell(Vec2),
|
||||
ColSpacing,
|
||||
/// The second of two points a preset or the column spacing takes after a point (AutoCAD 2024
|
||||
/// asks "Specify second point:"), from the first.
|
||||
Second(TwoPoints, Vec2),
|
||||
Attribs,
|
||||
/// A Verify attribute asked again.
|
||||
Verify,
|
||||
}
|
||||
|
||||
/// What two points give: a preset scale factor (all axes, or one) or the column spacing by their
|
||||
/// distance, the preset rotation by their direction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum TwoPoints {
|
||||
Scale,
|
||||
Axis(usize),
|
||||
Rotation,
|
||||
ColSpacing,
|
||||
}
|
||||
|
||||
// AutoCAD 2024's messages at INSERT's and MINSERT's scale, rotation and spacing prompts (measured):
|
||||
// a scale factor of 0; anything else that isn't a number where two points give a distance or an
|
||||
// angle, where a point gives the distance from the insertion point, and where only a number does.
|
||||
const NONZERO: &str = "Value must be nonzero.";
|
||||
/// Exploded INSERT's scale factor, which must be positive.
|
||||
const POSITIVE: &str = "Value must be positive and nonzero.";
|
||||
const TWO_POINTS: &str = "Requires numeric distance or two points.";
|
||||
const ANGLE_TWO_POINTS: &str = "Requires valid numeric angle or two points.";
|
||||
const SECOND_POINT: &str = "Requires numeric distance or second point.";
|
||||
const NUMERIC: &str = "Requires numeric value.";
|
||||
|
||||
#[derive(Default)]
|
||||
struct InsertM {
|
||||
stage: InsStage,
|
||||
@@ -1018,6 +1043,66 @@ impl InsertM {
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// The Scale preset `f` for every axis.
|
||||
fn preset_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
|
||||
self.scale = Some(Vec2::new(f, f));
|
||||
self.z_scale = Some(f.abs());
|
||||
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
|
||||
self.axes = [Some(f), Some(f), Some(f.abs())];
|
||||
// Exploded insertion asks its one scale factor after the insertion point.
|
||||
if self.at.is_some() {
|
||||
return self.advance(s);
|
||||
}
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
/// One axis preset: the others are 1, and no scale factors are asked after the point.
|
||||
fn preset_axis(&mut self, ax: usize, f: f64) -> Result<Step> {
|
||||
if let Some(a) = self.axes.get_mut(ax) {
|
||||
*a = Some(f);
|
||||
}
|
||||
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
self.z_scale = Some(z.abs());
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
fn preset_rotation(&mut self, r: f64) -> Result<Step> {
|
||||
self.rotation = Some(r);
|
||||
self.stage = InsStage::Point;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
/// The second of two points (AutoCAD 2024, measured): their distance is a preset scale factor
|
||||
/// (0 refused) or the column spacing (0 taken), their direction the preset rotation. Enter
|
||||
/// keeps a preset's default and is refused for the spacing, as anything else is; a refusal asks
|
||||
/// the first prompt again.
|
||||
fn second_point(&mut self, s: &mut Session, what: TwoPoints, a: Vec2, i: Input) -> Result<Step> {
|
||||
let (first, refused) = match what {
|
||||
TwoPoints::Scale => (InsStage::PresetScale, TWO_POINTS),
|
||||
TwoPoints::Axis(ax) => (InsStage::PresetAxis(ax), TWO_POINTS),
|
||||
TwoPoints::Rotation => (InsStage::PresetRotation, ANGLE_TWO_POINTS),
|
||||
TwoPoints::ColSpacing => (InsStage::ColSpacing, TWO_POINTS),
|
||||
};
|
||||
self.stage = first;
|
||||
match (what, i) {
|
||||
(TwoPoints::ColSpacing, Input::Point(b)) => {
|
||||
self.col_spacing = Some(a.dist(b));
|
||||
self.advance(s)
|
||||
}
|
||||
(TwoPoints::Rotation, Input::Point(b)) => self.preset_rotation(a.angle_to(b)),
|
||||
(TwoPoints::Rotation, Input::Enter) => self.preset_rotation(0.0),
|
||||
(TwoPoints::Scale | TwoPoints::Axis(_), Input::Point(b)) if a.dist(b) == 0.0 => Err(EngineError::Other(NONZERO.into())),
|
||||
(TwoPoints::Scale, Input::Point(b)) => self.preset_scale(s, a.dist(b)),
|
||||
(TwoPoints::Scale, Input::Enter) => self.preset_scale(s, 1.0),
|
||||
(TwoPoints::Axis(ax), Input::Point(b)) => self.preset_axis(ax, a.dist(b)),
|
||||
(TwoPoints::Axis(ax), Input::Enter) => self.preset_axis(ax, 1.0),
|
||||
_ => Err(EngineError::Other(refused.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too.
|
||||
@@ -1025,8 +1110,14 @@ fn distance(t: &str) -> Result<f64> {
|
||||
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into()))
|
||||
}
|
||||
|
||||
fn nonzero(t: &str) -> Result<f64> {
|
||||
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
|
||||
/// A scale factor typed at `t`: 0 gets AutoCAD 2024's "Value must be nonzero.", anything that
|
||||
/// isn't a number the prompt's own message.
|
||||
fn nonzero(t: &str, not_a_number: &str) -> Result<f64> {
|
||||
let v = number(t).ok_or_else(|| EngineError::Other(not_a_number.into()))?;
|
||||
if v == 0.0 {
|
||||
return Err(EngineError::Other(NONZERO.into()));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
impl Interactive for InsertM {
|
||||
@@ -1047,22 +1138,31 @@ impl Interactive for InsertM {
|
||||
}
|
||||
InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]),
|
||||
InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT),
|
||||
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
|
||||
InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"),
|
||||
// Exploded, after the insertion point, it takes a number only.
|
||||
InsStage::PresetScale if self.at.is_some() => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
|
||||
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::POINT_OR_NUMBER).default("1"),
|
||||
InsStage::PresetAxis(i) => {
|
||||
Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::POINT_OR_NUMBER).default("1")
|
||||
}
|
||||
// Typed text is read as before (`<<45` the angle, not an override for a point); a point
|
||||
// still comes from a click or LISP.
|
||||
InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"),
|
||||
// Text is read here, not taken as a distance along the rubber band: the core console
|
||||
// refuses 5 at this prompt (measured).
|
||||
InsStage::Second(_, a) => Prompt::new("Specify second point", Accept::POINT_OR_NUMBER).base(a),
|
||||
InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at),
|
||||
InsStage::XScale => {
|
||||
Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at)
|
||||
}
|
||||
InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at),
|
||||
InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"),
|
||||
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
|
||||
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::POINT_OR_NUMBER).default("use X scale factor").base(at),
|
||||
InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at),
|
||||
InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"),
|
||||
InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"),
|
||||
InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER),
|
||||
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
|
||||
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
|
||||
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::POINT_OR_NUMBER),
|
||||
InsStage::Attribs => {
|
||||
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
|
||||
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
|
||||
@@ -1138,45 +1238,58 @@ impl Interactive for InsertM {
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
}
|
||||
InsStage::PresetScale => {
|
||||
let f = match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => 1.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
// Exploded, after the insertion point: a positive number only (AutoCAD 2024 refuses a
|
||||
// point and x with "Requires numeric value.", 0 and -2 with "Value must be positive and
|
||||
// nonzero.", measured).
|
||||
InsStage::PresetScale if self.at.is_some() => {
|
||||
return match i {
|
||||
Input::Text(t) => {
|
||||
let f = number(&t).ok_or_else(|| EngineError::Other(NUMERIC.into()))?;
|
||||
let f = Some(f).filter(|f| *f > 0.0).ok_or_else(|| EngineError::Other(POSITIVE.into()))?;
|
||||
self.preset_scale(s, f)
|
||||
}
|
||||
Input::Enter => self.preset_scale(s, 1.0),
|
||||
_ => Err(EngineError::Other(NUMERIC.into())),
|
||||
};
|
||||
self.scale = Some(Vec2::new(f, f));
|
||||
self.z_scale = Some(f.abs());
|
||||
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
|
||||
self.axes = [Some(f), Some(f), Some(f.abs())];
|
||||
// Exploded insertion asks its one scale factor after the insertion point.
|
||||
if self.at.is_some() {
|
||||
return self.advance(s);
|
||||
}
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
// One axis preset: the others are 1, and no scale factors are asked after the point.
|
||||
// A point at a preset is the first of two (AutoCAD 2024, measured).
|
||||
InsStage::PresetScale => {
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Scale, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => self.preset_scale(s, nonzero(&t, TWO_POINTS)?),
|
||||
Input::Enter => self.preset_scale(s, 1.0),
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
};
|
||||
}
|
||||
InsStage::PresetAxis(ax) => {
|
||||
let f = match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Enter => 1.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Axis(ax), p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => self.preset_axis(ax, nonzero(&t, TWO_POINTS)?),
|
||||
Input::Enter => self.preset_axis(ax, 1.0),
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
};
|
||||
if let Some(a) = self.axes.get_mut(ax) {
|
||||
*a = Some(f);
|
||||
}
|
||||
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
self.z_scale = Some(z.abs());
|
||||
self.stage = InsStage::Point;
|
||||
}
|
||||
InsStage::PresetRotation => {
|
||||
self.rotation = Some(match i {
|
||||
Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?,
|
||||
Input::Enter => 0.0,
|
||||
_ => return Ok(Step::Continue),
|
||||
});
|
||||
self.stage = InsStage::Point;
|
||||
return match i {
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::Rotation, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Text(t) => {
|
||||
let r = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other(ANGLE_TWO_POINTS.into()))?;
|
||||
self.preset_rotation(r)
|
||||
}
|
||||
Input::Enter => self.preset_rotation(0.0),
|
||||
_ => Err(EngineError::Other(ANGLE_TWO_POINTS.into())),
|
||||
};
|
||||
}
|
||||
InsStage::Second(what, a) => return self.second_point(s, what, a, i),
|
||||
InsStage::XScale => match i {
|
||||
Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner,
|
||||
Input::Keyword(k) if k == "XYZ" => self.xyz = true,
|
||||
@@ -1185,7 +1298,7 @@ impl Interactive for InsertM {
|
||||
return self.corner_scale(s, sc);
|
||||
}
|
||||
Input::Text(t) => {
|
||||
self.x_scale = Some(nonzero(&t)?);
|
||||
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
|
||||
self.stage = InsStage::YScale;
|
||||
}
|
||||
Input::Enter => {
|
||||
@@ -1202,10 +1315,11 @@ impl Interactive for InsertM {
|
||||
}
|
||||
InsStage::YScale => {
|
||||
let x = self.x_scale.unwrap_or(1.0);
|
||||
// A number only: AutoCAD 2024 refuses a point here (measured).
|
||||
let y = match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Text(t) => nonzero(&t, NUMERIC)?,
|
||||
Input::Enter => x,
|
||||
_ => return Ok(Step::Continue),
|
||||
_ => return Err(EngineError::Other(NUMERIC.into())),
|
||||
};
|
||||
self.scale = Some(Vec2::new(x, y));
|
||||
if self.xyz {
|
||||
@@ -1214,11 +1328,15 @@ impl Interactive for InsertM {
|
||||
}
|
||||
return self.advance(s);
|
||||
}
|
||||
// A point gives its distance from the insertion point (AutoCAD 2024, measured).
|
||||
InsStage::ZScale => {
|
||||
self.z_scale = Some(match i {
|
||||
Input::Text(t) => nonzero(&t)?,
|
||||
Input::Text(t) => nonzero(&t, SECOND_POINT)?,
|
||||
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
|
||||
_ => return Ok(Step::Continue),
|
||||
Input::Point(p) => {
|
||||
Some(self.at.unwrap_or_default().dist(p)).filter(|d| *d != 0.0).ok_or_else(|| EngineError::Other(NONZERO.into()))?
|
||||
}
|
||||
_ => return Err(EngineError::Other(SECOND_POINT.into())),
|
||||
});
|
||||
return self.advance(s);
|
||||
}
|
||||
@@ -1232,17 +1350,14 @@ impl Interactive for InsertM {
|
||||
return self.advance(s);
|
||||
}
|
||||
InsStage::Rows | InsStage::Cols => {
|
||||
// A whole number as typed: AutoCAD 2024 takes +3 and 03 here and refuses 5.0, 5.,
|
||||
// 1e1, 8/2, 3', 4.5 and a point (measured at the rows, and 5.0 and +3 at the columns).
|
||||
let n = match i {
|
||||
Input::Text(t) => t
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX))
|
||||
.map(|v| v as u32)
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?,
|
||||
Input::Enter => 1,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
Input::Text(t) => t.trim().parse::<u32>().ok().filter(|v| (1..=Grid::MAX).contains(v)),
|
||||
Input::Enter => Some(1),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?;
|
||||
if self.stage == InsStage::Rows {
|
||||
self.rows = Some(n);
|
||||
} else {
|
||||
@@ -1264,11 +1379,19 @@ impl Interactive for InsertM {
|
||||
return self.advance(s);
|
||||
}
|
||||
}
|
||||
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
|
||||
InsStage::ColSpacing => {
|
||||
if let Input::Text(t) = i {
|
||||
self.col_spacing = Some(distance(&t)?);
|
||||
return self.advance(s);
|
||||
}
|
||||
return match i {
|
||||
Input::Text(t) => {
|
||||
self.col_spacing = Some(number(&t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other(TWO_POINTS.into()))?);
|
||||
self.advance(s)
|
||||
}
|
||||
Input::Point(p) => {
|
||||
self.stage = InsStage::Second(TwoPoints::ColSpacing, p);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
_ => Err(EngineError::Other(TWO_POINTS.into())),
|
||||
};
|
||||
}
|
||||
InsStage::Attribs => {
|
||||
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
|
||||
|
||||
@@ -8,7 +8,9 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::KW;
|
||||
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
|
||||
use super::super::file::{
|
||||
Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, report_lost, report_new_folder,
|
||||
};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::super::modify::erase_kept;
|
||||
use super::super::{CommandSpec, bad, point_param, str_param, targets};
|
||||
@@ -46,7 +48,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
|
||||
Some("*") => write(s, "wblock", &path, Source::Whole)?,
|
||||
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
|
||||
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
|
||||
@@ -54,6 +56,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -64,7 +67,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
|
||||
None => {
|
||||
let hs = targets(s, p)?;
|
||||
@@ -80,16 +83,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
|
||||
/// the version it was written at, for the caller to report as a save does. The
|
||||
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
|
||||
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
|
||||
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the
|
||||
/// version it was written at and what a DWG keeps only in part, for the caller to report as a
|
||||
/// save does. The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK
|
||||
/// does: its units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in
|
||||
/// inches and scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version, Vec<String>)> {
|
||||
let src = s.doc()?;
|
||||
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
|
||||
// block's base point for a block.
|
||||
@@ -115,14 +119,19 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
// The written drawing's own version: the writer is given no other.
|
||||
let version = own_version(&d, path);
|
||||
let lost = lost_writing(&d, path, version);
|
||||
Ok((d.model.len(), bytes.len(), lost, version))
|
||||
let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() };
|
||||
Ok((d.model.len(), bytes.len(), lost, version, notes))
|
||||
}
|
||||
|
||||
/// Say on the command line what the file written at `path` and `version` left out.
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
|
||||
/// Say on the command line what the file written at `path` and `version` left out, and what a
|
||||
/// DWG keeps only in part (`notes`).
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>, notes: Vec<String>) {
|
||||
if let Some(msg) = lost_message(path, version, lost) {
|
||||
s.echo(msg);
|
||||
}
|
||||
for note in notes {
|
||||
s.echo(note);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks
|
||||
@@ -341,7 +350,7 @@ impl DashWblockM {
|
||||
|
||||
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
|
||||
match write(s, "-wblock", &self.path, what) {
|
||||
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
|
||||
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
}
|
||||
Ok(Step::Done)
|
||||
@@ -352,8 +361,8 @@ impl DashWblockM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
|
||||
Ok((.., lost, version)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost);
|
||||
Ok((.., lost, version, notes)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost, notes);
|
||||
erase(s, hs)?;
|
||||
}
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
|
||||
@@ -266,9 +266,9 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header = src.header.clone();
|
||||
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
|
||||
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
|
||||
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
|
||||
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
|
||||
|
||||
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
|
||||
if let Some(a) = annotative {
|
||||
st.annotative = a;
|
||||
}
|
||||
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
|
||||
let name = match d.dim_styles.by_name_mut(&name) {
|
||||
Some(existing) if replace => {
|
||||
let kept = existing.name.clone();
|
||||
*existing = DimStyle { name: kept.clone(), ..st };
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("pline", "Polyline", run_pline)
|
||||
.menu(&["Draw", "Polyline"])
|
||||
.alias(&["pl"])
|
||||
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
|
||||
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width? (default PLINEWID unless vertices give widths)}")
|
||||
.interactive(|_| Ok(Box::new(PlineM::default()))),
|
||||
CommandSpec::new("circle", "Circle", run_circle)
|
||||
.menu(&["Draw", "Circle", "Center, Radius"])
|
||||
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("rectang", "Rectangle", super::draw2::run_rectang2)
|
||||
.menu(&["Draw", "Rectangle"])
|
||||
.alias(&["rec", "rectangle"])
|
||||
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth, rotation? (deg), fillet?, chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
|
||||
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth (the outline encloses it, cut corners included), rotation? (deg), fillet? (wins over a chamfer), chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
|
||||
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
|
||||
CommandSpec::new("polygon", "Polygon", run_polygon)
|
||||
.menu(&["Draw", "Polygon"])
|
||||
|
||||
@@ -45,15 +45,21 @@ fn current_elevation(s: &Session) -> Result<f64> {
|
||||
|
||||
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
|
||||
let mut vertex_widths = false;
|
||||
for v in raw.into_iter().flatten() {
|
||||
size_param("pline", v, "startWidth", true)?;
|
||||
size_param("pline", v, "endWidth", true)?;
|
||||
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
|
||||
}
|
||||
let vs: Vec<PolyVertex> = raw.map(|a| a.iter().filter_map(vertex_value).collect()).unwrap_or_default();
|
||||
if vs.len() < 2 {
|
||||
return Err(bad("pline", "`vertices` needs at least 2 points"));
|
||||
}
|
||||
let width = size_param("pline", p, "width", true)?.unwrap_or(0.0);
|
||||
// Without a width, the polyline starts at PLINEWID as the command does (unless its vertices
|
||||
// give their own widths).
|
||||
let width = match size_param("pline", p, "width", true)? {
|
||||
Some(w) => w,
|
||||
None if vertex_widths => 0.0,
|
||||
None => Some(s.doc()?.header.f64("PLINEWID", 0.0)).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.0),
|
||||
};
|
||||
let mut k = lwpoly(vs, bool_or(p, "closed", false));
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.const_width = width;
|
||||
@@ -266,8 +272,11 @@ impl Interactive for PlineM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLINE"
|
||||
}
|
||||
/// Segments start at PLINEWID, the width the last Width or Halfwidth answer left.
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.elevation = current_elevation(s)?;
|
||||
let w = s.doc()?.header.f64("PLINEWID", 0.0);
|
||||
(self.start_w, self.end_w) = if w.is_finite() && w > 0.0 { (w, w) } else { (0.0, 0.0) };
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
@@ -316,6 +325,11 @@ impl Interactive for PlineM {
|
||||
self.end_w = self.start_w;
|
||||
}
|
||||
self.asking_width = if self.asking_width == 1 { 2 } else { 0 };
|
||||
if self.asking_width == 0 {
|
||||
// The ending width becomes PLINEWID, the next polyline's width (AutoCAD:
|
||||
// Halfwidth 0.5 0.5 leaves PLINEWID 1).
|
||||
s.doc_mut()?.header.set_f64("PLINEWID", self.end_w);
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if let (Some(a), Some(st)) = (self.ask, self.verts.last().map(|v| v.p)) {
|
||||
@@ -379,6 +393,10 @@ impl Interactive for PlineM {
|
||||
l.bulge = 0.0;
|
||||
(l.start_width, l.end_width) = (0.0, 0.0);
|
||||
}
|
||||
// Back to the mode of the segment now last (AutoCAD: `_A` point `_U` returns
|
||||
// to "Specify next point", where `_L` is Length, not arc mode's Line).
|
||||
let n = self.verts.len();
|
||||
self.arc_mode = n >= 2 && self.verts.get(n - 2).is_some_and(|v| v.bulge != 0.0);
|
||||
self.sync(s, false)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
@@ -125,7 +125,11 @@ impl Interactive for SplineM {
|
||||
}
|
||||
match i {
|
||||
Input::Point(p) => {
|
||||
self.pts.push(p);
|
||||
// The same point again is not a further fit point (AutoCAD 2024 leaves it out),
|
||||
// nor a kink.
|
||||
if self.pts.last() != Some(&p) {
|
||||
self.pts.push(p);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
@@ -175,6 +179,8 @@ impl Interactive for SplineM {
|
||||
}
|
||||
Some(crate::cmd::spline_opts::SplineAsk::EndTangent) => opts.end_tangent = self.pts.last().map(|l| c - *l).filter(|d| d.len() > 1e-12),
|
||||
Some(_) => {}
|
||||
// The cursor on the last point adds nothing, as a click there doesn't.
|
||||
None if pts.last() == Some(&c) => {}
|
||||
None => pts.push(c),
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
|
||||
@@ -7,7 +7,7 @@ use cadcraft_geom::{Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Spline, TA
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::curves::{self, Chain, MAX_GEN, TanObj};
|
||||
use super::helpers::{arc, circle, line, lwpoly, rect_vertices, rect_with_corners, v3};
|
||||
use super::helpers::{arc, circle, line, lwpoly, rect_corners_fit, rect_vertices, rect_with_corners, v3};
|
||||
|
||||
use super::machines::number;
|
||||
use super::{CommandSpec, bad, bool_or, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param, targets};
|
||||
|
||||
@@ -139,6 +139,15 @@ impl DivideM {
|
||||
pub(super) fn new(measure: bool) -> Self {
|
||||
DivideM { measure, obj: None, phase: DivPhase::Object, block: None, align: true }
|
||||
}
|
||||
|
||||
/// The JSON form's parameters for the picked object, before the count or length.
|
||||
fn params(&self, h: Handle, pick: Vec2) -> Value {
|
||||
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
|
||||
if let Some(b) = &self.block {
|
||||
params["block"] = json!(b);
|
||||
}
|
||||
params
|
||||
}
|
||||
}
|
||||
|
||||
impl Interactive for DivideM {
|
||||
@@ -187,27 +196,37 @@ impl Interactive for DivideM {
|
||||
self.phase = DivPhase::Value;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) => {
|
||||
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) if self.measure => {
|
||||
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
|
||||
let v = match inp {
|
||||
Input::Text(t) => number(&t).ok_or_else(|| other("Requires a number."))?,
|
||||
Input::Point(q) => pick.dist(q),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
|
||||
if let Some(b) = &self.block {
|
||||
params["block"] = json!(b);
|
||||
}
|
||||
if self.measure {
|
||||
params["length"] = json!(v);
|
||||
run_measure(s, ¶ms)?;
|
||||
} else {
|
||||
if !(2.0..=32767.0).contains(&v) || v.fract() != 0.0 {
|
||||
return Err(other("Requires an integer between 2 and 32767."));
|
||||
}
|
||||
params["segments"] = json!(v as u64);
|
||||
run_divide(s, ¶ms)?;
|
||||
let mut params = self.params(h, pick);
|
||||
params["length"] = json!(v);
|
||||
run_measure(s, ¶ms)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(DivPhase::Value, inp) if !self.measure => {
|
||||
// A whole number as typed: AutoCAD 2024 takes +5 and 05 here and refuses 5.0, 5.,
|
||||
// 1e1, 4.5, 1, 32768, x, Enter and a point, naming the Block keyword while the
|
||||
// prompt still offers it (measured).
|
||||
let n = match inp {
|
||||
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| (2..=32767).contains(n)),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| {
|
||||
other(if self.block.is_some() {
|
||||
"Requires an integer between 2 and 32767."
|
||||
} else {
|
||||
"Requires an integer between 2 and 32767, or option keyword."
|
||||
})
|
||||
})?;
|
||||
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
|
||||
let mut params = self.params(h, pick);
|
||||
params["segments"] = json!(n);
|
||||
run_divide(s, ¶ms)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(_, Input::Enter) => Ok(Step::Cancel),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Accept, EntityKind, Input, Interactive, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, f64_or, lwpoly,
|
||||
number, other, point_param, point_req, rect_with_corners, size_param,
|
||||
number, other, point_param, point_req, rect_corners_fit, rect_with_corners, size_param,
|
||||
};
|
||||
use crate::last_used::RectangModes;
|
||||
|
||||
@@ -19,9 +19,30 @@ fn rect_kind(first: Vec2, (w, h): (f64, f64), rot: f64, fillet: f64, chamfer: (f
|
||||
k
|
||||
}
|
||||
|
||||
/// The area a fillet's or chamfer's four corners take off the full rectangle (a fillet wins).
|
||||
fn corner_area(fillet: f64, chamfer: (f64, f64)) -> f64 {
|
||||
if fillet > 0.0 {
|
||||
(4.0 - std::f64::consts::PI) * fillet * fillet
|
||||
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
|
||||
2.0 * chamfer.0 * chamfer.1
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The sides of the rectangle of `area` with one side `side`, its length (or with `breadth`,
|
||||
/// its width). AutoCAD sizes it so that the outline, corners cut, encloses the area: the corners'
|
||||
/// area is added back. When the corners then don't fit they stay square, and the area is the full
|
||||
/// rectangle's.
|
||||
fn area_sides(area: f64, side: f64, breadth: bool, fillet: f64, chamfer: (f64, f64)) -> (f64, f64) {
|
||||
let sides = |a: f64| if breadth { (a / side, side) } else { (side, a / side) };
|
||||
let (w, h) = sides(area + corner_area(fillet, chamfer));
|
||||
if rect_corners_fit(Vec2::new(w, h), fillet, chamfer) { (w, h) } else { sides(area) }
|
||||
}
|
||||
|
||||
/// The width and height of a rectangle from its `dimensions`, its `p2` corner, its `area` with
|
||||
/// `length` or `breadth`, or its second corner `p2`, rotated by `rot` about `a`.
|
||||
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)> {
|
||||
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer: (f64, f64)) -> Result<(f64, f64)> {
|
||||
Ok(if let Some(d) = p.get("dimensions").and_then(Value::as_array) {
|
||||
let l = d.first().and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
|
||||
let wd = d.get(1).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
|
||||
@@ -38,8 +59,8 @@ fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)>
|
||||
return Err(bad("rectang", "area must be positive"));
|
||||
}
|
||||
match (p.get("length").and_then(Value::as_f64), p.get("breadth").and_then(Value::as_f64)) {
|
||||
(Some(l), _) if l.is_finite() && l > 0.0 => (l, area / l),
|
||||
(_, Some(b)) if b.is_finite() && b > 0.0 => (area / b, b),
|
||||
(Some(l), _) if l.is_finite() && l > 0.0 => area_sides(area, l, false, fillet, chamfer),
|
||||
(_, Some(b)) if b.is_finite() && b > 0.0 => area_sides(area, b, true, fillet, chamfer),
|
||||
_ => return Err(bad("rectang", "area needs `length` or `breadth`")),
|
||||
}
|
||||
} else {
|
||||
@@ -68,7 +89,7 @@ pub(crate) fn run_rectang2(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let fillet = size_param("rectang", p, "fillet", true)?.unwrap_or(0.0);
|
||||
let width = size_param("rectang", p, "width", true)?.unwrap_or(0.0);
|
||||
let (w, h) = rect_size(p, a, rot, centered)?;
|
||||
let (w, h) = rect_size(p, a, rot, centered, fillet, ch)?;
|
||||
if w.abs() < 1e-12 || h.abs() < 1e-12 || !w.is_finite() || !h.is_finite() {
|
||||
return Err(bad("rectang", "rectangle has no area"));
|
||||
}
|
||||
@@ -116,10 +137,13 @@ pub(crate) struct RectM2 {
|
||||
asking: Option<RAsk>,
|
||||
}
|
||||
|
||||
/// A rectangle's rotation as AutoCAD 2024 shows it: degrees from 0 to 360, two decimals.
|
||||
fn rotation_text(rotation: f64) -> String {
|
||||
let t = format!("{:.2}", rotation.to_degrees().rem_euclid(360.0));
|
||||
if t == "360.00" { "0.00".into() } else { t }
|
||||
/// A rectangle's rotation (radians counterclockwise from +X) as AutoCAD 2024 shows it: from
|
||||
/// ANGBASE in the ANGDIR sense, in the drawing's angle units, to two places. Rotation 30 typed
|
||||
/// with ANGBASE 90 and ANGDIR 1 shows as "120.00", and 30.5 in degrees/minutes/seconds as
|
||||
/// "30d30'".
|
||||
fn rotation_text(s: &Session, rotation: f64) -> String {
|
||||
let au = s.angle_settings();
|
||||
crate::units::format_angle(au.shown(rotation), au.aunits, 2)
|
||||
}
|
||||
|
||||
/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current
|
||||
@@ -144,9 +168,10 @@ fn modes_line(s: &Session, m: &RectangModes) -> Option<String> {
|
||||
if m.width > 0.0 {
|
||||
parts.push(format!("Width={}", d(m.width)));
|
||||
}
|
||||
let rot = rotation_text(m.rotation);
|
||||
if rot != "0.00" {
|
||||
parts.push(format!("Rotation={rot}"));
|
||||
// Listed when the rectangle is turned from +X at all, to two places, whatever ANGBASE says.
|
||||
let turned = format!("{:.2}", m.rotation.to_degrees().rem_euclid(360.0));
|
||||
if turned != "0.00" && turned != "360.00" {
|
||||
parts.push(format!("Rotation={}", rotation_text(s, m.rotation)));
|
||||
}
|
||||
(!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" ")))
|
||||
}
|
||||
@@ -219,7 +244,7 @@ impl Interactive for RectM2 {
|
||||
}
|
||||
/// Asks for the pending option's value, or for the first and second points; in centre mode
|
||||
/// the first prompt asks for the centre instead of a corner.
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
let num = |m: &str, d: f64| Prompt::new(m, Accept::NUMBER).default(format!("{d:.4}"));
|
||||
if let Some(a) = self.asking {
|
||||
return match a {
|
||||
@@ -237,7 +262,7 @@ impl Interactive for RectM2 {
|
||||
RAsk::DimW => num("Specify width for rectangles", self.dims.map(|d| d.1).unwrap_or(10.0)),
|
||||
RAsk::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER)
|
||||
.kw(&["Pick points"])
|
||||
.default(rotation_text(self.rotation))
|
||||
.default(rotation_text(s, self.rotation))
|
||||
.base_opt(self.first),
|
||||
RAsk::RotPick1 => Prompt::new("Specify first point", Accept::POINT),
|
||||
RAsk::RotPick2(b) => Prompt::new("Specify second point", Accept::POINT).base(b),
|
||||
@@ -299,7 +324,7 @@ impl Interactive for RectM2 {
|
||||
self.asking = Some(a);
|
||||
return Err(other("Value must be positive."));
|
||||
}
|
||||
let (w, h) = if a == RAsk::AreaLength { (v, self.area / v) } else { (self.area / v, v) };
|
||||
let (w, h) = area_sides(self.area, v, a == RAsk::AreaWidth, self.fillet, self.chamfer);
|
||||
return self.make(s, w, h);
|
||||
}
|
||||
RAsk::DimL => {
|
||||
@@ -314,7 +339,8 @@ impl Interactive for RectM2 {
|
||||
RAsk::Rotation => match i {
|
||||
Input::Keyword(_) => self.asking = Some(RAsk::RotPick1),
|
||||
Input::Point(p) => self.rotation = self.first.map(|f| f.angle_to(p)).unwrap_or(0.0),
|
||||
Input::Text(t) => self.rotation = s.angle_settings().direction(&t).ok_or_else(|| other("Requires a valid angle."))?,
|
||||
// An amount turned in the ANGDIR sense from +X, ANGBASE aside, as AutoCAD takes it.
|
||||
Input::Text(t) => self.rotation = s.angle_settings().rotation(&t).ok_or_else(|| other("Requires a valid angle."))?,
|
||||
_ => {}
|
||||
},
|
||||
RAsk::RotPick1 => {
|
||||
|
||||
@@ -729,6 +729,57 @@ fn divide_and_measure_command_line() {
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_takes_a_whole_number_as_typed() {
|
||||
// AutoCAD 2024 at "Enter the number of segments or [Block]:": +5, 05, the LISP real 5.0 and
|
||||
// 32767 are taken; 5.0, 5., 1e1, 4.5, 1, 0, -3, 32768, x, Enter and a point from LISP are
|
||||
// refused and asked again (measured).
|
||||
let points = |s: &Session| kinds(s).iter().filter(|k| **k == "Point").count();
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("divide 5,0").unwrap();
|
||||
let asked = s.prompt_text();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments or [Block]:"));
|
||||
for bad in ["5.0", "5.", "1e1", "4.5", "1", "0", "-3", "32768", "x", "", "(list 1 2)"] {
|
||||
let logged = s.log.len();
|
||||
s.cmdline(bad).unwrap();
|
||||
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
|
||||
assert_eq!(said, ["Requires an integer between 2 and 32767, or option keyword."], "{bad:?}");
|
||||
assert_eq!(s.prompt_text(), asked, "{bad:?}");
|
||||
}
|
||||
assert_eq!(points(&s), 0);
|
||||
s.cmdline("+5").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(points(&s), 4);
|
||||
for (typed, n) in [("05", 4), ("(+ 2.5 2.5)", 4), ("2", 1), ("32767", 32766)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("divide 5,0").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
|
||||
assert_eq!(points(&s), n, "{typed}");
|
||||
}
|
||||
// MEASURE shares the prompt machine and is unchanged: Enter at its length still ends it.
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("measure 5,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(points(&s), 0);
|
||||
// After Block the prompt offers no keyword, and the message names none (AutoCAD 2024, measured).
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let tick = s.execute("circle", &json!({"center": [50, 50], "radius": 0.1})).unwrap();
|
||||
s.execute("block", &json!({"name": "DOT", "base": [50, 50], "handles": [h(&tick)], "keep": "delete"})).unwrap();
|
||||
s.cmdline("divide 5,0 b DOT y").unwrap();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments:"));
|
||||
s.cmdline("5.0").unwrap();
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 2 and 32767."));
|
||||
s.cmdline("5").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(kinds(&s).iter().filter(|k| **k == "Block Reference").count(), 4);
|
||||
}
|
||||
|
||||
// ---------------- REVCLOUD ----------------
|
||||
|
||||
#[test]
|
||||
@@ -1101,6 +1152,198 @@ fn rectang_options_command_line() {
|
||||
}
|
||||
}
|
||||
|
||||
/// RECTANG against what AutoCAD 2024 stores for the same typed input (black-box: synthetic
|
||||
/// input in accoreconsole, read back with `entget`): Area with the corners taken off, and
|
||||
/// corners too large for the sides.
|
||||
#[test]
|
||||
fn rectang_area_and_oversized_corners_match_autocad() {
|
||||
type Case = (&'static [&'static str], &'static [[f64; 3]], [f64; 3]);
|
||||
// (typed input, vertices [x, y, bulge], [width, elevation, thickness])
|
||||
let cases: [Case; 4] = [
|
||||
// RECTANG-028: Area counts the chamfered corners off.
|
||||
(
|
||||
&["rectang _C 1.5 2.5 26.36462345136234,-19.7291241693893 _R 0 _A 1442.9297064464572 _W 35.53488991311575"],
|
||||
&[
|
||||
[26.36462345136234, -18.2291241693893, 0.0],
|
||||
[28.86462345136234, -19.7291241693893, 0.0],
|
||||
[65.68168268505678, -19.7291241693893, 0.0],
|
||||
[67.18168268505678, -17.2291241693893, 0.0],
|
||||
[67.18168268505678, 14.30576574372644, 0.0],
|
||||
[64.68168268505678, 15.80576574372644, 0.0],
|
||||
[27.86462345136234, 15.80576574372644, 0.0],
|
||||
[26.36462345136234, 13.30576574372644, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
// RECTANG-035-VN: Area counts the fillets off, at survey coordinates.
|
||||
(
|
||||
&["rectang _F 2.0 612322.0691653182,2398792.948957577 _R 0 _A 592.8936847254046 _L 19.287858563349488"],
|
||||
&[
|
||||
[612322.0691653182, 2398794.948957577, 0.414213562373095],
|
||||
[612324.0691653182, 2398792.948957577, 0.0],
|
||||
[612339.3570238815, 2398792.948957577, 0.414213562373095],
|
||||
[612341.3570238815, 2398794.948957577, 0.0],
|
||||
[612341.3570238815, 2398821.866195597, 0.414213562373095],
|
||||
[612339.3570238815, 2398823.866195598, 0.0],
|
||||
[612324.0691653182, 2398823.866195598, 0.414213562373095],
|
||||
[612322.0691653182, 2398821.866195597, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
// RECTANG-029: a fillet too large: each corner two coincident vertices.
|
||||
(
|
||||
&["rectang _F 11.37084114989061 -21.46774953784037,-0.023473793210982308 _R 0 -2.5163476213560187,49.88119923361903"],
|
||||
&[
|
||||
[-21.46774953784036, -0.0234737932109823, 0.0],
|
||||
[-21.46774953784036, -0.0234737932109823, 0.0],
|
||||
[-2.516347621356018, -0.0234737932109823, 0.0],
|
||||
[-2.516347621356018, -0.0234737932109823, 0.0],
|
||||
[-2.516347621356018, 49.88119923361903, 0.0],
|
||||
[-2.516347621356018, 49.88119923361903, 0.0],
|
||||
[-21.46774953784036, 49.88119923361903, 0.0],
|
||||
[-21.46774953784036, 49.88119923361903, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
// RECTANG-039-VN: a chamfer too large, rotated, with Dimensions.
|
||||
(
|
||||
&[
|
||||
"rectang _C 18.656567079201356 18.656567079201356 612317.9599920243,2398739.0200147885 _R 30 _D 26.652238684573366 32.64533161964191 612344.6122307089,2398771.6653464083",
|
||||
],
|
||||
&[
|
||||
[612317.9599920243, 2398739.020014788, 0.0],
|
||||
[612317.9599920243, 2398739.020014788, 0.0],
|
||||
[612341.041507793, 2398752.34613413, 0.0],
|
||||
[612341.041507793, 2398752.34613413, 0.0],
|
||||
[612324.7188419831, 2398780.617820628, 0.0],
|
||||
[612324.7188419831, 2398780.617820628, 0.0],
|
||||
[612301.6373262145, 2398767.291701286, 0.0],
|
||||
[612301.6373262145, 2398767.291701286, 0.0],
|
||||
],
|
||||
[0.0, 0.0, 0.0],
|
||||
),
|
||||
];
|
||||
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
|
||||
for (input, want, [width, elevation, thickness]) in cases {
|
||||
let mut s = Session::new();
|
||||
for line in input {
|
||||
s.cmdline(line).unwrap();
|
||||
assert!(s.running.is_none(), "{line}: {}", s.prompt_text());
|
||||
}
|
||||
let e = s.doc().unwrap().model.last().unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{input:?}: {:?}", e.kind) };
|
||||
let got: Vec<[f64; 3]> = p.vertices.iter().map(|v| [v.p.x, v.p.y, v.bulge]).collect();
|
||||
let ok = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.iter().zip(w).all(|(a, b)| same(*a, *b)));
|
||||
assert!(
|
||||
ok,
|
||||
"{input:?}
|
||||
got {got:?}
|
||||
want {want:?}"
|
||||
);
|
||||
assert!(p.closed && same(p.const_width, width) && same(p.elevation, elevation) && same(e.common.thickness, thickness), "{input:?}");
|
||||
}
|
||||
// Rotation, elevation and thickness are remembered too: AutoCAD opens the next RECTANG with
|
||||
// "Current rectangle modes: Elevation=7.5000 Thickness=2.2500 Rotation=30.96".
|
||||
let mut s = Session::new();
|
||||
s.cmdline("rectang _E 7.5 _T 2.25 0,0 _R _P 0,0 10,6 10,20").unwrap();
|
||||
s.cmdline("rectang 100,100 110,105").unwrap();
|
||||
let e = s.doc().unwrap().model.last().unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
|
||||
let edge = p.vertices[1].p - p.vertices[0].p;
|
||||
assert!(p.vertices[0].p == Vec2::new(100.0, 100.0) && same(edge.angle(), 6f64.atan2(10.0)), "{p:?}");
|
||||
assert!(p.elevation == 7.5 && e.common.thickness == 2.25);
|
||||
}
|
||||
|
||||
/// RECTANG's Rotation follows the drawing's angle settings as AutoCAD 2024's does.
|
||||
#[test]
|
||||
fn rectang_rotation_follows_the_angle_settings() {
|
||||
let modes = |s: &Session| s.log.iter().filter(|l| l.starts_with("Current rectangle modes:")).cloned().collect::<Vec<_>>();
|
||||
// With ANGBASE 90 and ANGDIR 1, AutoCAD 2024 turns a rectangle given Rotation 30 clockwise
|
||||
// by 30° from +X (ANGBASE aside), and shows that rotation from ANGBASE: "Rotation=120.00",
|
||||
// and <120.00> as the next rotation default.
|
||||
let mut s = Session::new();
|
||||
s.cmdline("setvar angbase 90").unwrap();
|
||||
s.cmdline("setvar angdir 1").unwrap();
|
||||
s.cmdline("rectang 50,0 _R 30 60,5").unwrap();
|
||||
let e = s.doc().unwrap().model.last().unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
|
||||
let edge = p.vertices[1].p - p.vertices[0].p;
|
||||
assert!((edge.y.atan2(edge.x) + 30f64.to_radians()).abs() < 1e-9, "{p:?}");
|
||||
s.start("rectang").unwrap();
|
||||
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=120.00"]);
|
||||
s.cmdline("50,0").unwrap();
|
||||
s.cmdline("_R").unwrap();
|
||||
assert!(s.prompt_text().contains("<120.00>"), "{}", s.prompt_text());
|
||||
s.cancel();
|
||||
// In degrees/minutes/seconds: "Rotation=30d30'".
|
||||
let mut s = Session::new();
|
||||
s.cmdline("setvar aunits 1").unwrap();
|
||||
s.cmdline("rectang 50,0 _R 30.5 60,5").unwrap();
|
||||
s.start("rectang").unwrap();
|
||||
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=30d30'"]);
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
/// Area allows for cut corners only while they fit: a fillet too large for the resulting sides
|
||||
/// leaves square corners, so the rectangle is the full area asked for (4 × 1, not 4 × 1.858).
|
||||
/// Corners exactly as long as the shorter side allows still fit; a hair longer and the corners
|
||||
/// stay square, each still written twice (AutoCAD 2024, `entget` of a 4 x 2 rectangle).
|
||||
#[test]
|
||||
fn rectang_corners_at_the_limit_fit_and_just_over_stay_square() {
|
||||
let b = (std::f64::consts::PI / 8.0).tan();
|
||||
let fit: [(&str, &[(f64, f64, f64)]); 4] = [
|
||||
(
|
||||
"_F 0.9999",
|
||||
&[
|
||||
(0.0, 0.9999, b),
|
||||
(0.9999, 0.0, 0.0),
|
||||
(3.0001, 0.0, b),
|
||||
(4.0, 0.9999, 0.0),
|
||||
(4.0, 1.0001, b),
|
||||
(3.0001, 2.0, 0.0),
|
||||
(0.9999, 2.0, b),
|
||||
(0.0, 1.0001, 0.0),
|
||||
],
|
||||
),
|
||||
("_F 1", &[(0.0, 1.0, b), (1.0, 0.0, 0.0), (3.0, 0.0, b), (4.0, 1.0, 0.0), (4.0, 1.0, b), (3.0, 2.0, 0.0), (1.0, 2.0, b), (0.0, 1.0, 0.0)]),
|
||||
(
|
||||
"_C 1 1",
|
||||
&[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (3.0, 0.0, 0.0), (4.0, 1.0, 0.0), (4.0, 1.0, 0.0), (3.0, 2.0, 0.0), (1.0, 2.0, 0.0), (0.0, 1.0, 0.0)],
|
||||
),
|
||||
(
|
||||
"_C 1.2 0.8",
|
||||
&[(0.0, 1.2, 0.0), (0.8, 0.0, 0.0), (2.8, 0.0, 0.0), (4.0, 0.8, 0.0), (4.0, 0.8, 0.0), (3.2, 2.0, 0.0), (1.2, 2.0, 0.0), (0.0, 1.2, 0.0)],
|
||||
),
|
||||
];
|
||||
let square =
|
||||
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 2.0, 0.0), (4.0, 2.0, 0.0), (0.0, 2.0, 0.0), (0.0, 2.0, 0.0)];
|
||||
let over: [(&str, &[(f64, f64, f64)]); 2] = [("_F 1.0001", &square), ("_C 1.2 0.81", &square)];
|
||||
for (corners, want) in fit.into_iter().chain(over) {
|
||||
let mut s = Session::new();
|
||||
s.cmdline(&format!("rectang {corners} 0,0 4,2")).unwrap();
|
||||
let EntityKind::LwPolyline(p) = last(&s) else { panic!("no polyline") };
|
||||
let got: Vec<(f64, f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect();
|
||||
let ok = got.len() == want.len()
|
||||
&& got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-6);
|
||||
assert!(ok, "{corners}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectang_area_with_corners_too_large_stays_exact() {
|
||||
let check = |s: &Session| {
|
||||
let pts = rect_pts(s);
|
||||
let b = cadcraft_geom::Bounds2::from_points(pts.clone());
|
||||
assert!(near(b.min, 0.0, 0.0) && near(b.max, 4.0, 1.0), "{pts:?}");
|
||||
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
|
||||
};
|
||||
let mut s = Session::new();
|
||||
s.cmdline("rectang _F 2 0,0 _A 4 _L 4").unwrap();
|
||||
check(&s);
|
||||
s.execute("rectang", &json!({"p1": [0, 0], "area": 4, "length": 4, "fillet": 2})).unwrap();
|
||||
check(&s);
|
||||
}
|
||||
|
||||
/// Guards the JSON `center: true` form for every sizing route: a picked corner mirrored about
|
||||
/// the centre, full-size `dimensions`, full `area`, rotation about the centre, that the default
|
||||
/// corner mode is untouched, and that centre mode without a size is rejected.
|
||||
@@ -1136,7 +1379,7 @@ fn rectang_center_mode_json() {
|
||||
}
|
||||
|
||||
/// Guards that fillet, chamfer, width and thickness still apply in centre mode, and that an
|
||||
/// oversized fillet falls back to sharp corners without moving the rectangle off centre.
|
||||
/// oversized fillet leaves sharp corners without moving the rectangle off centre.
|
||||
#[test]
|
||||
fn rectang_center_mode_honours_options() {
|
||||
let mut s = Session::new();
|
||||
@@ -1153,9 +1396,11 @@ fn rectang_center_mode_honours_options() {
|
||||
assert_eq!(rect_pts(&s).len(), 8);
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
// A fillet too large for the rectangle falls back to sharp corners, still centred.
|
||||
// A fillet too large for the rectangle leaves sharp corners, each one two coincident vertices
|
||||
// as in AutoCAD, still centred.
|
||||
s.execute("rectang", &json!({"center": true, "p1": [10, 10], "p2": [14, 16], "fillet": 5})).unwrap();
|
||||
assert_eq!(rect_pts(&s).len(), 4);
|
||||
let pts = rect_pts(&s);
|
||||
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
}
|
||||
@@ -1183,8 +1428,9 @@ fn rectang_center_mode_command_line() {
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
// Area too: the rectangle of that area is centred on the first point.
|
||||
s.cmdline("rectang ce 10,10 a 96 l 8").unwrap();
|
||||
// Area too: the rectangle of that area is centred on the first point (without the fillet
|
||||
// remembered from above, which would take its corners off the area).
|
||||
s.cmdline("rectang f 0 ce 10,10 a 96 l 8").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
|
||||
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
|
||||
|
||||
@@ -104,6 +104,36 @@ pub fn set_dwg_compat_lost(f: DwgCompatLost) {
|
||||
let _ = DWG_COMPAT_LOST.set(f);
|
||||
}
|
||||
|
||||
/// Notes on what a DWG keeps of a drawing only in part, such as a linetype with more dash
|
||||
/// elements than a DWG can count (installed by the app with the DWG writer, a lower layer; see
|
||||
/// `cadcraft_io::dwg_notes`).
|
||||
pub type DwgNotes = fn(&Drawing) -> Vec<String>;
|
||||
|
||||
static DWG_NOTES: OnceLock<DwgNotes> = OnceLock::new();
|
||||
|
||||
pub fn set_dwg_notes(f: DwgNotes) {
|
||||
let _ = DWG_NOTES.set(f);
|
||||
}
|
||||
|
||||
/// The [`DwgNotes`] of `d`, the drawing a DWG save writes: none without the hook.
|
||||
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
|
||||
DWG_NOTES.get().map(|f| f(d)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
|
||||
/// [`dwg_notes`]), and list it in the result's `warnings`.
|
||||
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
|
||||
if notes.is_empty() {
|
||||
return;
|
||||
}
|
||||
for note in ¬es {
|
||||
s.echo(note.clone());
|
||||
}
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("warnings".into(), json!(notes));
|
||||
}
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
|
||||
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
|
||||
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
@@ -873,6 +903,8 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
|
||||
if drops_unknown(format!("drawing.{fmt}")) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
} else if is_dxf_file(format!("drawing.{fmt}")) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
@@ -1005,7 +1037,9 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let version = own_version(d, path);
|
||||
let lost = lost_writing(d, path, version);
|
||||
let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() };
|
||||
report_lost(s, r, path, version, &lost);
|
||||
report_dwg_notes(s, r, notes);
|
||||
}
|
||||
|
||||
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
|
||||
@@ -1112,6 +1146,8 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
|
||||
report_new_folder(s, &mut r, folder);
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
|
||||
report_dwg_notes(s, &mut r, notes);
|
||||
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
|
||||
@@ -455,15 +455,9 @@ fn tinted_dim_style(d: &mut Drawing, name: &str, color: Color, tinted: &mut Tint
|
||||
if let Some(n) = tinted.names.get(&key) {
|
||||
return Some(n.clone());
|
||||
}
|
||||
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))?.clone();
|
||||
let st = d.dim_style(name)?.clone();
|
||||
let base = format!("COMPARE_{}_{}", tag(color), st.name);
|
||||
let new = tinted.next.find(
|
||||
"dimension style",
|
||||
&base,
|
||||
d.dim_styles.len(),
|
||||
|i| suffixed(&base, i),
|
||||
|n| d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n)),
|
||||
);
|
||||
let new = tinted.next.find("dimension style", &base, d.dim_styles.len(), |i| suffixed(&base, i), |n| d.dim_style(n).is_some());
|
||||
d.dim_styles.push(DimStyle {
|
||||
name: new.clone(),
|
||||
dim_line_color: Color::ByBlock,
|
||||
|
||||
@@ -68,29 +68,48 @@ pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec<PolyVertex> {
|
||||
/// chamfer distances at every corner, in AutoCAD 2024's order: from `a` along X to `b`'s X, then
|
||||
/// `b`, then back along Y. A chamfer cuts the edge into each corner by its first distance and the
|
||||
/// edge out of it by its second; each fillet arc starts on the edge into its corner. A fillet or
|
||||
/// chamfer that doesn't fit leaves the corners square.
|
||||
/// chamfer too large for the shorter side leaves the corners square, each as two coincident
|
||||
/// vertices, as AutoCAD stores them.
|
||||
pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec<PolyVertex> {
|
||||
let corners = [a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)];
|
||||
let short = (b.x - a.x).abs().min((b.y - a.y).abs());
|
||||
let (d_in, d_out, bulge) = if fillet > 0.0 && fillet * 2.0 <= short + 1e-12 {
|
||||
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
|
||||
// down and left.
|
||||
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
|
||||
(fillet, fillet, sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2))
|
||||
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 && chamfer.0 + chamfer.1 <= short + 1e-12 {
|
||||
(chamfer.0, chamfer.1, 0.0)
|
||||
} else {
|
||||
return corners.into_iter().map(PolyVertex::new).collect();
|
||||
};
|
||||
let Some((d_in, d_out)) = rect_corner_cuts(fillet, chamfer) else { return corners.into_iter().map(PolyVertex::new).collect() };
|
||||
let fits = rect_corners_fit(b - a, fillet, chamfer);
|
||||
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
|
||||
// down and left.
|
||||
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
|
||||
let bulge = if fillet > 0.0 { sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2) } else { 0.0 };
|
||||
let mut out = Vec::with_capacity(8);
|
||||
for (i, cur) in corners.iter().enumerate() {
|
||||
let (Some(prev), Some(next)) = (corners.get((i + 3) % 4), corners.get((i + 1) % 4)) else { continue };
|
||||
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
|
||||
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
|
||||
if fits {
|
||||
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
|
||||
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
|
||||
} else {
|
||||
out.extend([PolyVertex::new(*cur), PolyVertex::new(*cur)]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How far a rectangle's fillet or chamfer cuts into the edges into and out of each corner, if
|
||||
/// one is set: the fillet radius on both, or the two chamfer distances. A fillet wins over a
|
||||
/// chamfer.
|
||||
fn rect_corner_cuts(fillet: f64, chamfer: (f64, f64)) -> Option<(f64, f64)> {
|
||||
if fillet > 0.0 {
|
||||
Some((fillet, fillet))
|
||||
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
|
||||
Some(chamfer)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fillet or chamfer fits a rectangle of `size` (signed sides): its two cuts together
|
||||
/// no longer than the shorter side. True when neither is set.
|
||||
pub fn rect_corners_fit(size: Vec2, fillet: f64, chamfer: (f64, f64)) -> bool {
|
||||
rect_corner_cuts(fillet, chamfer).is_none_or(|(d_in, d_out)| d_in + d_out <= size.x.abs().min(size.y.abs()) + 1e-12)
|
||||
}
|
||||
|
||||
// ---------- the user's support files ----------
|
||||
|
||||
/// Largest support file (linetype, hatch pattern or alias file) read.
|
||||
|
||||
@@ -62,8 +62,7 @@ impl Scope {
|
||||
Some(_) => {
|
||||
let name = given.unwrap_or_default();
|
||||
let d = s.doc()?;
|
||||
let l =
|
||||
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
|
||||
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
|
||||
Ok(Scope::Space(Space::Paper(l.name.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"),
|
||||
CommandSpec::new("layout.list", "List Layouts", run_list).params("→ [{name, tabOrder, page, viewports}]").noundo(),
|
||||
CommandSpec::new("layout.saveas", "Save Layout as Template", saveas::run_saveas)
|
||||
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}")
|
||||
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?, warnings?}")
|
||||
.noundo(),
|
||||
CommandSpec::new("mview", "Viewports", run_mview)
|
||||
.alias(&["mv"])
|
||||
|
||||
@@ -12,7 +12,7 @@ use cadcraft_doc::{Common, Drawing, Entity, EntityKind, EntityStore, Point};
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::file::{drops_unknown, io, not_saved, not_saved_message};
|
||||
use super::super::file::{drops_unknown, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes};
|
||||
use super::super::{bad, str_param};
|
||||
use super::layout_name;
|
||||
use super::prompts::current_layout;
|
||||
@@ -136,6 +136,9 @@ pub(super) fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
if drops_unknown(&path) {
|
||||
report_dwg_notes(s, &mut r, dwg_notes(&t));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -129,80 +129,406 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
|
||||
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
|
||||
return Err(EngineError::Other("An object is on a locked layer.".into()));
|
||||
}
|
||||
let hs = joinable_picks(s.doc()?, hs);
|
||||
let hs = &hs[..];
|
||||
if let Some(h) = join_on_source(s, hs)? {
|
||||
return Ok(Some(h));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
let mut segs: Vec<Segment> = Vec::new();
|
||||
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
|
||||
let mut owners: Vec<Handle> = Vec::new();
|
||||
let mut common = None;
|
||||
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
|
||||
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
|
||||
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
|
||||
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
|
||||
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
|
||||
// polyline facing down; measured).
|
||||
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
|
||||
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
|
||||
for h in hs {
|
||||
let Some(e) = d.entity(*h) else { continue };
|
||||
common.get_or_insert_with(|| e.common.clone());
|
||||
match &e.kind {
|
||||
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
|
||||
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
|
||||
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
|
||||
_ => {}
|
||||
let piece =
|
||||
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
|
||||
let unit: Vec<Piece> = match &e.kind {
|
||||
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
|
||||
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
|
||||
EntityKind::Arc(a) => {
|
||||
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
|
||||
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
|
||||
}
|
||||
// Repeated vertices included: AutoCAD 2024 keeps them.
|
||||
EntityKind::LwPolyline(p) if !p.closed => {
|
||||
// The elevation is along the polyline's normal: down Z for a mirrored one.
|
||||
let z = if down(e) { -p.elevation } else { p.elevation };
|
||||
p.vertices
|
||||
.windows(2)
|
||||
.map(|w| {
|
||||
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
|
||||
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if !unit.is_empty() {
|
||||
units.push((down(e), unit));
|
||||
}
|
||||
owners.resize(segs.len(), *h);
|
||||
}
|
||||
if segs.len() < 2 {
|
||||
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
|
||||
return Err(EngineError::Other("Select at least two objects to join.".into()));
|
||||
}
|
||||
// Chain greedily from the first segment.
|
||||
let mut chain = vec![segs.remove(0)];
|
||||
let mut used = vec![owners.remove(0)];
|
||||
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
|
||||
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
|
||||
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
|
||||
// on one circle onto those), so objects facing either way still join there.
|
||||
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
|
||||
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
|
||||
// A new polyline takes the source's properties.
|
||||
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
|
||||
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
|
||||
let tol = 1e-6;
|
||||
loop {
|
||||
let start = chain.first().map(Segment::start).unwrap_or_default();
|
||||
let end = chain.last().map(Segment::end).unwrap_or_default();
|
||||
let Some(i) =
|
||||
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let s0 = segs.remove(i);
|
||||
used.push(owners.remove(i));
|
||||
if s0.start().near(end, tol) {
|
||||
chain.push(s0);
|
||||
} else if s0.end().near(end, tol) {
|
||||
chain.push(s0.reversed());
|
||||
} else if s0.end().near(start, tol) {
|
||||
chain.insert(0, s0);
|
||||
} else {
|
||||
chain.insert(0, s0.reversed());
|
||||
}
|
||||
}
|
||||
if chain.len() < 2 {
|
||||
let links = chain_units(units, tol);
|
||||
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
|
||||
// ("0 segments added to polyline").
|
||||
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
|
||||
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
|
||||
if links.len() < 2 || one_object {
|
||||
return Err(EngineError::Other("Objects are not connected.".into()));
|
||||
}
|
||||
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
|
||||
let mut vs: Vec<PolyVertex> = chain
|
||||
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
|
||||
// A polyline's own segments keep their widths.
|
||||
let mut vs: Vec<PolyVertex> = links
|
||||
.iter()
|
||||
.map(|s| PolyVertex {
|
||||
p: s.start(),
|
||||
bulge: match s {
|
||||
Segment::Line(_) => 0.0,
|
||||
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
|
||||
},
|
||||
..Default::default()
|
||||
.map(|l| {
|
||||
let (start_width, end_width) = l.widths.unwrap_or_default();
|
||||
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
|
||||
})
|
||||
.collect();
|
||||
if !closed && let Some(l) = chain.last() {
|
||||
vs.push(PolyVertex::new(l.end()));
|
||||
if !closed && let Some(l) = links.last() {
|
||||
vs.push(PolyVertex::new(l.ends.1));
|
||||
}
|
||||
let space = s.space();
|
||||
// A new polyline goes in the source's space, whichever space is current.
|
||||
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
|
||||
let doc = s.doc_mut()?;
|
||||
for h in hs.iter().filter(|h| used.contains(*h)) {
|
||||
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
|
||||
// added to polyline").
|
||||
if let Some(src) = first
|
||||
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
|
||||
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
|
||||
{
|
||||
for h in hs.iter().filter(|h| **h != src && used(h)) {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Some(src));
|
||||
}
|
||||
for h in hs.iter().filter(|h| used(h)) {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
|
||||
// elevation runs along its normal: negated for one facing down. Not measured: the core
|
||||
// console's JOIN makes no new polyline.
|
||||
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
|
||||
let common = common.unwrap_or_default();
|
||||
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
|
||||
let mut kind = lwpoly(vs, closed);
|
||||
if let EntityKind::LwPolyline(p) = &mut kind {
|
||||
p.elevation = elevation;
|
||||
}
|
||||
let nh = doc.new_handle();
|
||||
if let Some(st) = doc.space_mut(&space) {
|
||||
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
|
||||
st.push(Entity { handle: nh, common, kind });
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Some(nh))
|
||||
}
|
||||
|
||||
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
|
||||
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
|
||||
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let joinable = |h: &Handle| {
|
||||
d.entity(*h).is_some_and(|e| match &e.kind {
|
||||
EntityKind::Line(_) => true,
|
||||
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
|
||||
EntityKind::LwPolyline(p) => !p.closed,
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
|
||||
}
|
||||
|
||||
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
|
||||
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
|
||||
/// is (measured).
|
||||
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
|
||||
let Ok(d) = s.doc() else { return false };
|
||||
// Elliptical arcs and splines join another way, and a locked object stops the join.
|
||||
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
|
||||
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
|
||||
return false;
|
||||
}
|
||||
let picks = joinable_picks(d, hs);
|
||||
let arcs: Vec<&cadcraft_doc::Arc> = picks
|
||||
.iter()
|
||||
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
|
||||
Some(EntityKind::Arc(a)) => Some(a),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let tol = 1e-6;
|
||||
match &arcs[..] {
|
||||
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
|
||||
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
|
||||
/// and radius). An arc that starts even a hair before the source's start reaches on round past
|
||||
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
|
||||
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
|
||||
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
|
||||
let same_circle =
|
||||
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
|
||||
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
|
||||
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
|
||||
}
|
||||
|
||||
/// The chain JOIN builds from the first object: each next object with an end on one of the
|
||||
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
|
||||
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
|
||||
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
|
||||
/// their heights.
|
||||
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
|
||||
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
|
||||
let near = |p, q| meet(p, q, tol);
|
||||
if units.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
// A source that already ends where it starts still takes more, unless it has no length at all
|
||||
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
|
||||
// length).
|
||||
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
|
||||
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
|
||||
return chain.into();
|
||||
}
|
||||
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
|
||||
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
|
||||
let Some(i) = units.iter().position(meets) else { break };
|
||||
let unit = units.remove(i);
|
||||
let Some((a, b)) = ends(&unit) else { break };
|
||||
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
|
||||
// it (measured): a polyline by its first vertex if it can, and before the chain rather
|
||||
// than after it; a line or an arc turned round if it can, its end on the chain's end
|
||||
// before its start on the chain's start.
|
||||
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
|
||||
let (before, turned) = if polyline {
|
||||
if near(a, start) {
|
||||
(true, true)
|
||||
} else if near(a, end) {
|
||||
(false, false)
|
||||
} else {
|
||||
(near(b, start), !near(b, start))
|
||||
}
|
||||
} else if near(b, end) {
|
||||
(false, true)
|
||||
} else if near(a, start) {
|
||||
(true, true)
|
||||
} else {
|
||||
(!near(a, end), false)
|
||||
};
|
||||
match (before, turned) {
|
||||
(false, false) => chain.extend(unit),
|
||||
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
|
||||
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
|
||||
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
|
||||
}
|
||||
// A chain that a join closes takes nothing more.
|
||||
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
chain.into()
|
||||
}
|
||||
|
||||
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
|
||||
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
|
||||
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
|
||||
/// polyline's own segment, its widths.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Piece {
|
||||
owner: Handle,
|
||||
ends: (Vec2, Vec2),
|
||||
heights: (f64, f64),
|
||||
bulge: f64,
|
||||
widths: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
fn flipped(self) -> Self {
|
||||
Piece {
|
||||
ends: (self.ends.1, self.ends.0),
|
||||
heights: (self.heights.1, self.heights.0),
|
||||
bulge: -self.bulge,
|
||||
widths: self.widths.map(|(a, b)| (b, a)),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&self) -> (Vec2, f64) {
|
||||
(self.ends.0, self.heights.0)
|
||||
}
|
||||
|
||||
fn end(&self) -> (Vec2, f64) {
|
||||
(self.ends.1, self.heights.1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
|
||||
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
|
||||
/// at 5 and a line at 0, end to end in plan, stay as they are).
|
||||
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
|
||||
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
|
||||
}
|
||||
|
||||
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
|
||||
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
|
||||
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
|
||||
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
|
||||
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
|
||||
/// polyline joins, the end vertex's widths are cleared.
|
||||
///
|
||||
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
|
||||
/// starts from the source and takes its segments in order).
|
||||
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
|
||||
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
|
||||
let (&first, &last) = (run.first()?, run.last()?);
|
||||
if sp.closed || run.len() != last - first + 1 {
|
||||
return None;
|
||||
}
|
||||
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
|
||||
let mut own = sp.vertices.clone();
|
||||
if other_polyline && sp.const_width > 0.0 {
|
||||
// The constant width goes, so spell it out on the source's own segments.
|
||||
for v in &mut own {
|
||||
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
|
||||
}
|
||||
}
|
||||
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
|
||||
let (head, tail) = (widths(own.first()?), widths(own.last()?));
|
||||
let vertex = |i: usize, fill: (f64, f64)| {
|
||||
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
|
||||
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
|
||||
};
|
||||
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
|
||||
vs.extend(own);
|
||||
if last + 1 < links.len() {
|
||||
// The source's end vertex starts the first piece after it.
|
||||
let v = vertex(last + 1, tail);
|
||||
if let Some(end) = vs.last_mut() {
|
||||
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
|
||||
}
|
||||
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
|
||||
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
|
||||
}
|
||||
if other_polyline && let Some(end) = vs.last_mut() {
|
||||
(end.start_width, end.end_width) = (0.0, 0.0);
|
||||
}
|
||||
if closed {
|
||||
// The last vertex is the first one again.
|
||||
vs.pop();
|
||||
}
|
||||
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
|
||||
}
|
||||
|
||||
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
|
||||
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
|
||||
///
|
||||
/// - Lines on the source's line make one line, from the source's start end to the farthest
|
||||
/// point the way it runs (and back past its start if one reaches behind it).
|
||||
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
|
||||
/// end; arcs that reach all the way round make a circle, a new object in their place.
|
||||
///
|
||||
/// `None` when the objects aren't all of one of those kinds.
|
||||
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
|
||||
let d = s.doc()?;
|
||||
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
|
||||
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
|
||||
if rest.is_empty() || ents.len() != hs.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
|
||||
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
|
||||
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
|
||||
let tol = 1e-6;
|
||||
let kind = match &src.kind {
|
||||
EntityKind::Line(l) => {
|
||||
let (a, b) = (l.a.xy(), l.b.xy());
|
||||
let len = a.dist(b);
|
||||
let lines: Vec<&cadcraft_doc::Line> = rest
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Line(o) => Some(o),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let level = |z: f64| (z - l.a.z).abs() < tol;
|
||||
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let u = (b - a) * (1.0 / len);
|
||||
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
|
||||
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
|
||||
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
|
||||
let at = |t: f64| (a + u * t).to3(l.a.z);
|
||||
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
|
||||
}
|
||||
EntityKind::Arc(g) => {
|
||||
let arcs: Vec<&cadcraft_doc::Arc> = rest
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Arc(o) => Some(o),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
|
||||
if far > cadcraft_geom::TAU - tol {
|
||||
let circle = Entity {
|
||||
handle: Handle(0),
|
||||
common: src.common.clone(),
|
||||
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
|
||||
};
|
||||
// In the source's space, whichever space is current.
|
||||
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
|
||||
let doc = s.doc_mut()?;
|
||||
for h in hs {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
let nh = doc.new_handle();
|
||||
if let Some(st) = doc.space_mut(&space) {
|
||||
st.push(Entity { handle: nh, ..circle });
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Some(nh));
|
||||
}
|
||||
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
|
||||
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let src_h = src.handle;
|
||||
let doc = s.doc_mut()?;
|
||||
for h in hs.iter().filter(|h| **h != src_h) {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
doc.modify_entity(src_h, |e| e.kind = kind)?;
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Some(src_h))
|
||||
}
|
||||
|
||||
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
if p.get("close").and_then(Value::as_bool) == Some(true) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::break_join::join;
|
||||
use super::break_join::{join, join_makes_circle};
|
||||
use super::explode::explode;
|
||||
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
|
||||
use super::{
|
||||
@@ -20,6 +20,18 @@ pub(super) enum Op {
|
||||
Join,
|
||||
}
|
||||
|
||||
/// COPY's Array option: asking how many items, then where the second one goes (or, with Fit, the
|
||||
/// last one).
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum CopyArray {
|
||||
Off,
|
||||
Count,
|
||||
Items { n: u16, fit: bool },
|
||||
}
|
||||
|
||||
/// The most items COPY's Array option makes, the original included, as in AutoCAD.
|
||||
const MAX_COPY_ITEMS: u16 = 32767;
|
||||
|
||||
/// Select objects, then collect the points/values the operation needs.
|
||||
pub(super) struct SelectThen {
|
||||
op: Op,
|
||||
@@ -37,9 +49,16 @@ pub(super) struct SelectThen {
|
||||
/// SCALE Reference: the reference length, once known.
|
||||
ref_len: Option<f64>,
|
||||
copy_mode: bool,
|
||||
/// COPY: one copy and done (COPYMODE 1, until the Multiple option), else copies until Exit.
|
||||
copy_single: bool,
|
||||
/// COPY: the objects each placement made, so Undo takes back the last one.
|
||||
copies: Vec<Vec<Handle>>,
|
||||
copy_array: CopyArray,
|
||||
ask_erase: bool,
|
||||
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
|
||||
join_source: Option<Handle>,
|
||||
/// JOIN of arcs that make a circle: asking whether to.
|
||||
ask_circle: bool,
|
||||
}
|
||||
|
||||
impl SelectThen {
|
||||
@@ -55,8 +74,12 @@ impl SelectThen {
|
||||
ref_from: None,
|
||||
ref_len: None,
|
||||
copy_mode: false,
|
||||
copy_single: false,
|
||||
copies: Vec::new(),
|
||||
copy_array: CopyArray::Off,
|
||||
ask_erase: false,
|
||||
join_source: None,
|
||||
ask_circle: false,
|
||||
}
|
||||
}
|
||||
fn apply(&mut self, s: &mut Session) -> Result<Step> {
|
||||
@@ -84,8 +107,120 @@ impl SelectThen {
|
||||
}
|
||||
}
|
||||
|
||||
/// JOIN the selected objects and report what they became.
|
||||
/// COPY's prompt once the base point is known, as AutoCAD 2024 asks it.
|
||||
fn copy_prompt(&self, base: Option<Vec2>) -> Prompt {
|
||||
match self.copy_array {
|
||||
CopyArray::Count => Prompt::new("Enter number of items to array", Accept::NUMBER),
|
||||
CopyArray::Items { fit: false, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Fit"]).base_opt(base),
|
||||
CopyArray::Items { fit: true, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).base_opt(base),
|
||||
CopyArray::Off if self.copies.is_empty() => {
|
||||
Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).default("use first point as displacement").base_opt(base)
|
||||
}
|
||||
CopyArray::Off => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).default("Exit").base_opt(base),
|
||||
}
|
||||
}
|
||||
|
||||
/// COPY once the base point is known (AutoCAD 2024, measured): a point places a copy; Enter
|
||||
/// at the first prompt copies by the base point taken as a displacement, and after a copy
|
||||
/// ends the command; Array asks for a number of items, the original included, then puts
|
||||
/// them a second point apart (or, with Fit, spread up to it, Enter keeping them at the
|
||||
/// base); Undo takes back the last placement. One placement ends a single-copy COPY.
|
||||
fn copy_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
let Some(base) = self.pts.first().copied() else { return Ok(Step::Continue) };
|
||||
let placed = match (self.copy_array, i) {
|
||||
(CopyArray::Count, Input::Enter) => return self.copy_done(s),
|
||||
(CopyArray::Count, i) => {
|
||||
// A whole number as typed, from 2 to 32767 whatever the selection: AutoCAD 2024 takes
|
||||
// +3 and 03 here, refuses 4.0, 1e1, 8/2, 1', 3", 50002 and a point, and doesn't
|
||||
// apply MAXARRAY (with MAXARRAY 100000, four lines and 26000 items made 104000
|
||||
// lines; measured).
|
||||
let n = match i {
|
||||
Input::Text(t) => t.trim().parse::<u16>().ok().filter(|v| (2..=MAX_COPY_ITEMS).contains(v)),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 2 and {MAX_COPY_ITEMS}.")))?;
|
||||
// Not AutoCAD's: the copies (items after the first, times the objects) stay within
|
||||
// ARRAY's own limit, whatever MAXARRAY says, so a large selection can't run out of
|
||||
// memory.
|
||||
let copies = u64::from(n - 1).saturating_mul(u64::try_from(self.objs.len()).unwrap_or(u64::MAX));
|
||||
if copies > cadcraft_doc::MAX_ARRAY_ITEMS {
|
||||
return Err(EngineError::Other(format!(
|
||||
"The array would create {copies} objects; the limit is {}. Use fewer items or select fewer objects.",
|
||||
cadcraft_doc::MAX_ARRAY_ITEMS
|
||||
)));
|
||||
}
|
||||
self.copy_array = CopyArray::Items { n, fit: false };
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Items { n, fit }, Input::Keyword(kw)) if kw == if fit { "Array" } else { "Fit" } => {
|
||||
self.copy_array = CopyArray::Items { n, fit: !fit };
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Items { n, fit }, i @ (Input::Point(_) | Input::Enter)) => {
|
||||
let p = if let Input::Point(p) = i { p } else { base };
|
||||
let step = if fit { (p - base) * (1.0 / f64::from(n - 1)) } else { p - base };
|
||||
self.copy_array = CopyArray::Off;
|
||||
let mut made = Vec::new();
|
||||
for k in 1..n {
|
||||
match transform_entities(s, &self.objs, &Mat3::translate(step * f64::from(k)), true) {
|
||||
Ok(hs) => made.extend(hs),
|
||||
Err(e) => {
|
||||
// The items made so far are a placement Undo takes back.
|
||||
self.copies.push(made);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
made
|
||||
}
|
||||
(CopyArray::Off, Input::Keyword(kw)) if kw == "Array" => {
|
||||
self.copy_array = CopyArray::Count;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Off, Input::Keyword(kw)) if kw == "Undo" => {
|
||||
if let Some(last) = self.copies.pop() {
|
||||
let d = s.doc_mut()?;
|
||||
for h in last {
|
||||
d.remove_entity(h);
|
||||
}
|
||||
if self.copies.is_empty() {
|
||||
s.echo("Command has been completely undone.");
|
||||
}
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
(CopyArray::Off, Input::Keyword(kw)) if kw == "Exit" => return self.copy_done(s),
|
||||
(CopyArray::Off, Input::Enter) if !self.copies.is_empty() => return self.copy_done(s),
|
||||
(CopyArray::Off, Input::Enter) => {
|
||||
transform_entities(s, &self.objs, &Mat3::translate(base), true)?;
|
||||
return self.copy_done(s);
|
||||
}
|
||||
(CopyArray::Off, Input::Point(p)) => transform_entities(s, &self.objs, &Mat3::translate(p - base), true)?,
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
self.copies.push(placed);
|
||||
if self.copy_single {
|
||||
return self.copy_done(s);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
fn copy_done(&mut self, s: &mut Session) -> Result<Step> {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
|
||||
/// as AutoCAD 2024 does.
|
||||
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
|
||||
if join_makes_circle(s, &self.objs) {
|
||||
self.ask_circle = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
self.join_apply(s)
|
||||
}
|
||||
|
||||
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
|
||||
match join(s, &self.objs) {
|
||||
Ok(h) => {
|
||||
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
|
||||
@@ -95,6 +230,9 @@ impl SelectThen {
|
||||
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
|
||||
Some(EntityKind::Spline(_)) => "spline",
|
||||
Some(EntityKind::Ellipse(_)) => "ellipse",
|
||||
Some(EntityKind::Line(_)) => "line",
|
||||
Some(EntityKind::Arc(_)) => "arc",
|
||||
Some(EntityKind::Circle(_)) => "circle",
|
||||
_ => "polyline",
|
||||
};
|
||||
s.echo(format!("{n} objects joined into 1 {what}"))
|
||||
@@ -308,6 +446,9 @@ impl Interactive for SelectThen {
|
||||
if self.ask_erase {
|
||||
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
|
||||
}
|
||||
if self.ask_circle {
|
||||
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
|
||||
}
|
||||
if let Some(src) = self.join_source {
|
||||
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
|
||||
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
|
||||
@@ -328,7 +469,7 @@ impl Interactive for SelectThen {
|
||||
match (self.op, k) {
|
||||
(Op::Move | Op::Copy, 0) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]),
|
||||
(Op::Move, _) => Prompt::new("Specify second point or <use first point as displacement>", Accept::POINT).base_opt(base),
|
||||
(Op::Copy, _) => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).base_opt(base),
|
||||
(Op::Copy, _) => self.copy_prompt(base),
|
||||
(Op::Rotate | Op::Scale, 0) => Prompt::new("Specify base point", Accept::POINT),
|
||||
// ROTATE and SCALE offer the angle/factor used last time.
|
||||
(Op::Rotate, _) => {
|
||||
@@ -361,6 +502,14 @@ impl Interactive for SelectThen {
|
||||
}
|
||||
}
|
||||
}
|
||||
// No leaves every arc as it is (AutoCAD 2024, measured).
|
||||
if self.ask_circle {
|
||||
return match &i {
|
||||
Input::Keyword(k) if k == "No" => Ok(Step::Done),
|
||||
Input::Keyword(_) | Input::Enter => self.join_apply(s),
|
||||
_ => Err(EngineError::Other("Invalid option keyword.".into())),
|
||||
};
|
||||
}
|
||||
if let Some(src) = self.join_source {
|
||||
return self.join_source_input(s, src, i);
|
||||
}
|
||||
@@ -388,10 +537,6 @@ impl Interactive for SelectThen {
|
||||
self.reference = true;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Op::Copy, _, Input::Keyword(kw)) if kw == "Exit" => {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(_, 0, Input::Point(p)) => {
|
||||
self.pts.push(p);
|
||||
Ok(Step::Continue)
|
||||
@@ -408,15 +553,7 @@ impl Interactive for SelectThen {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Op::Copy, _, Input::Point(p)) => {
|
||||
let d = p - self.pts[0];
|
||||
transform_entities(s, &self.objs, &Mat3::translate(d), true)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Op::Copy, _, Input::Enter) => {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Op::Copy, _, i) => self.copy_input(s, i),
|
||||
(Op::Rotate, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
|
||||
let a = match inp {
|
||||
Input::Point(p) => self.pts[0].angle_to(p),
|
||||
@@ -542,11 +679,13 @@ impl Interactive for SelectThen {
|
||||
pub(super) struct DisplaceM {
|
||||
inner: SelectThen,
|
||||
displacement: bool,
|
||||
/// COPY's mOde option: asking Single or Multiple.
|
||||
ask_mode: bool,
|
||||
}
|
||||
|
||||
impl DisplaceM {
|
||||
pub(super) fn new(op: Op) -> Self {
|
||||
DisplaceM { inner: SelectThen::new(op), displacement: false }
|
||||
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false }
|
||||
}
|
||||
/// At "Specify base point": objects selected, no point yet.
|
||||
fn at_base(&self) -> bool {
|
||||
@@ -559,14 +698,26 @@ impl Interactive for DisplaceM {
|
||||
self.inner.name()
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.inner.copy_single = self.inner.op == Op::Copy && s.settings.copymode;
|
||||
self.inner.begin(s)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
if self.displacement {
|
||||
return Prompt::new("Specify displacement", Accept::POINT).default("0,0");
|
||||
}
|
||||
if self.ask_mode {
|
||||
let current = if s.settings.copymode { "Single" } else { "Multiple" };
|
||||
return Prompt::new("Enter a copy mode option", crate::cmd::curves::KW).kw(&["Single", "Multiple"]).default(current);
|
||||
}
|
||||
if self.at_base() {
|
||||
return Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement");
|
||||
// COPY: mOde sets COPYMODE; Multiple, offered while it is single, copies until Exit
|
||||
// this once.
|
||||
let kw: &[&str] = match self.inner.op {
|
||||
Op::Copy if self.inner.copy_single => &["Displacement", "mOde", "Multiple"],
|
||||
Op::Copy => &["Displacement", "mOde"],
|
||||
_ => &["Displacement"],
|
||||
};
|
||||
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement");
|
||||
}
|
||||
self.inner.prompt(s)
|
||||
}
|
||||
@@ -583,10 +734,34 @@ impl Interactive for DisplaceM {
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
if self.ask_mode {
|
||||
match &i {
|
||||
Input::Keyword(k) if k == "Single" || k == "Multiple" => s.settings.copymode = k == "Single",
|
||||
Input::Enter => {}
|
||||
_ => return Ok(Step::Continue),
|
||||
}
|
||||
// The mode shown is the mode this COPY runs in, Enter keeping it.
|
||||
self.inner.copy_single = s.settings.copymode;
|
||||
self.ask_mode = false;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.at_base() && (matches!(&i, Input::Enter) || matches!(&i, Input::Keyword(k) if k == "Displacement")) {
|
||||
self.displacement = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.at_base() && self.inner.op == Op::Copy {
|
||||
match &i {
|
||||
Input::Keyword(k) if k == "mOde" => {
|
||||
self.ask_mode = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
Input::Keyword(k) if k == "Multiple" => {
|
||||
self.inner.copy_single = false;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.inner.input(s, i)
|
||||
}
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
Accept, Entity, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelectKind, SelectMode, Session, Step, Value, Vec2, bad, json,
|
||||
line, points_param,
|
||||
};
|
||||
use cadcraft_geom::Arc;
|
||||
|
||||
/// An area whose vertices STRETCH moves: a window's box, or a polygon closed back to its first
|
||||
/// point.
|
||||
@@ -40,6 +41,18 @@ fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>)
|
||||
}
|
||||
}
|
||||
|
||||
/// The bulge that keeps an arc's height (bulge × chord / 2) when its chord changes length; none
|
||||
/// once the chord collapses to a point, which has no arc left to keep.
|
||||
fn keep_height(bulge: f64, old_chord: f64, new_chord: f64) -> f64 {
|
||||
if new_chord.is_nan() || new_chord <= 1e-12 {
|
||||
0.0
|
||||
} else if old_chord.is_finite() {
|
||||
bulge * old_chord / new_chord
|
||||
} else {
|
||||
bulge
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the vertices of `e` that lie inside any of the areas `wins` by `d` (STRETCH).
|
||||
fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
|
||||
let inside = |p: Vec2| wins.iter().any(|a| a.contains(p));
|
||||
@@ -55,18 +68,56 @@ fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
|
||||
mv(&mut l.b);
|
||||
}
|
||||
EntityKind::LwPolyline(pl) => {
|
||||
let old: Vec<Vec2> = pl.vertices.iter().map(|v| v.p).collect();
|
||||
for v in &mut pl.vertices {
|
||||
if inside(v.p) {
|
||||
v.p += d;
|
||||
}
|
||||
}
|
||||
// An arc segment keeps its height (bulge × chord / 2) as its ends move, as in AutoCAD.
|
||||
let n = pl.vertices.len();
|
||||
let segs = if pl.closed { n } else { n.saturating_sub(1) };
|
||||
for i in 0..segs {
|
||||
let j = (i + 1) % n;
|
||||
let (Some(a0), Some(b0), Some(b1)) = (old.get(i), old.get(j), pl.vertices.get(j).map(|v| v.p)) else { continue };
|
||||
if let Some(v) = pl.vertices.get_mut(i)
|
||||
&& v.bulge != 0.0
|
||||
{
|
||||
v.bulge = keep_height(v.bulge, a0.dist(*b0), v.p.dist(b1));
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::MLine(m) => m.vertices.iter_mut().for_each(|v| mv(&mut v.p)),
|
||||
EntityKind::Arc(a) => {
|
||||
// Arcs keep their shape: move when the centre is inside.
|
||||
if inside(a.center.xy()) {
|
||||
a.center.x += d.x;
|
||||
a.center.y += d.y;
|
||||
// AutoCAD moves the ends inside the area and keeps the arc's height (bulge × chord / 2);
|
||||
// the centre alone moves nothing. An end stretched onto the other leaves the arc as it
|
||||
// was: AutoCAD collapses it into a zero-radius arc at that point (radius 6e-16, start
|
||||
// 180°, end 0°), an object nothing can draw or pick, which CADCraft does not make.
|
||||
let g = Arc::new(a.center.xy(), a.radius, a.start, a.end);
|
||||
let (s0, e0) = (g.start_point(), g.end_point());
|
||||
let (s_in, e_in) = (inside(s0), inside(e0));
|
||||
let (s1, e1) = (if s_in { s0 + d } else { s0 }, if e_in { e0 + d } else { e0 });
|
||||
if s_in && e_in {
|
||||
// Both ends move: the arc moves whole (a full sweep has no chord to rebuild from).
|
||||
(a.center.x, a.center.y) = (a.center.x + d.x, a.center.y + d.y);
|
||||
} else if (s_in || e_in)
|
||||
&& let Some((r, _)) =
|
||||
cadcraft_geom::bulge_to_arc(s1, e1, keep_height(cadcraft_geom::arc_to_bulge(g.sweep()), s0.dist(e0), s1.dist(e1)))
|
||||
{
|
||||
(a.center.x, a.center.y) = (r.center.x, r.center.y);
|
||||
(a.radius, a.start, a.end) = (r.radius, r.start, r.end);
|
||||
}
|
||||
}
|
||||
// Control points inside the area move (AutoCAD).
|
||||
EntityKind::Spline(sp) if sp.fit.is_empty() => sp.control.iter_mut().filter(|p| inside(**p)).for_each(|p| *p += d),
|
||||
// A spline built from fit points: the fit points inside the area move and it is fitted
|
||||
// through them again, its fit data kept (AutoCAD 2024). All of them inside, it moves.
|
||||
EntityKind::Spline(sp) => {
|
||||
if sp.fit.iter().all(|p| inside(*p)) {
|
||||
sp.transform(&Mat3::translate(d));
|
||||
} else if sp.fit.iter().any(|p| inside(*p)) {
|
||||
let fit: Vec<Vec2> = sp.fit.iter().map(|p| if inside(*p) { *p + d } else { *p }).collect();
|
||||
*sp = sp.refit(&fit, sp.closed);
|
||||
}
|
||||
}
|
||||
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(mv),
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
use cadcraft_doc::{Common, Entity, EntityKind, Handle, LwPolyline, MAX_BLOCK_DEPTH, Space};
|
||||
use cadcraft_geom::{
|
||||
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, ccw_sweep, intersect_ext, line_circle, line_line_infinite, norm_angle,
|
||||
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, Vec3, ccw_sweep, intersect_ext, line_circle, line_line_infinite,
|
||||
norm_angle,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(
|
||||
"{handle, option: close|open|join|reverse|refit|purge|polyline|move|fitmove|fitadd|fitdelete|kink|tangents|tolerance|vertexadd|vertexmove|vertexdelete|weight|elevate, \
|
||||
handles2? (join), fit?, index?, to?, before?: bool (fitadd), at? (kink, vertexadd), start?, end? (tangent directions; null = default), tolerance?, weight?, \
|
||||
order? (elevate), precision?}",
|
||||
order? (elevate), precision?: 0..99 (polyline, default 10)}",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(SplineditM::default()))),
|
||||
CommandSpec::new("lengthen", "Lengthen", run_lengthen)
|
||||
@@ -122,6 +123,47 @@ pub(crate) fn as_lwpoly(k: &EntityKind) -> Option<LwPolyline> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The polyline PEDIT turns a line or an arc into, and the normal it faces, as AutoCAD 2024 makes
|
||||
/// them (measured): facing the way the arc faces, and up for a line whatever its normal; at the
|
||||
/// line's height, or at the arc's centre height measured along its normal (a mirrored arc whose
|
||||
/// centre is at world Z -5 gives elevation 5, one at Z 5 elevation -5); the thickness stays the
|
||||
/// object's. A sloped line still comes out at elevation 0: AutoCAD makes a polyline in the line's
|
||||
/// vertical plane, which a CADCraft polyline can't be. An arc in a tilted plane (normal neither up
|
||||
/// nor down Z), which CADCraft keeps only approximately, keeps its normal and goes by the sign of
|
||||
/// its Z as above; AutoCAD's result for one isn't measured. A polyline is returned as it is.
|
||||
pub(crate) fn polyline_of(e: &Entity) -> Option<(LwPolyline, Vec3)> {
|
||||
let mut pl = as_lwpoly(&e.kind)?;
|
||||
let normal = e.common.extrusion;
|
||||
match &e.kind {
|
||||
EntityKind::Line(l) => {
|
||||
if (l.a.z - l.b.z).abs() < 1e-9 {
|
||||
pl.elevation = l.a.z;
|
||||
}
|
||||
Some((pl, Vec3::Z))
|
||||
}
|
||||
// The arc's centre is in world coordinates; a polyline's elevation runs along its normal.
|
||||
// A mirrored arc runs clockwise in plan, and so does its polyline (AutoCAD 2024 starts it
|
||||
// at the arc's start in the arc's own coordinates).
|
||||
EntityKind::Arc(a) => {
|
||||
pl.elevation = if normal.z < 0.0 { -a.center.z } else { a.center.z };
|
||||
if normal.z < 0.0 {
|
||||
pl.vertices = curves::reverse_vertices(&pl.vertices, false);
|
||||
}
|
||||
Some((pl, normal))
|
||||
}
|
||||
_ => Some((pl, normal)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the polyline `pl`, facing `normal`, in place of the object `h`.
|
||||
fn set_polyline(s: &mut Session, h: Handle, pl: LwPolyline, normal: Vec3) -> Result<()> {
|
||||
s.doc_mut()?.modify_entity(h, |e| {
|
||||
e.kind = EntityKind::LwPolyline(pl);
|
||||
e.common.extrusion = normal;
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
mod pedit_multi;
|
||||
mod pedit_vertex;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Accept, Chain, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Value, bad, bool_or, curves, json,
|
||||
number, other, targets,
|
||||
other, targets,
|
||||
};
|
||||
|
||||
// =====================================================================================
|
||||
@@ -26,7 +26,13 @@ pub(crate) fn arraypath(
|
||||
return Err(other("Select objects to array."));
|
||||
}
|
||||
let (n, step) = match (count, spacing) {
|
||||
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => (((l / sp).floor() as usize).saturating_add(1), sp),
|
||||
// As AutoCAD 2024 fills a path by distance: floor(length / spacing) items on a closed path,
|
||||
// so none lands on or near the first where the path closes, and one more, at the end, on
|
||||
// an open one (measured). The 1e-9 lets a length that comes out a hair short still fit.
|
||||
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => {
|
||||
let fit = (l / sp + 1e-9).floor() as usize;
|
||||
(if c.closed { fit.max(1) } else { fit.saturating_add(1) }, sp)
|
||||
}
|
||||
(Some(n), _) => {
|
||||
let n = n.max(1);
|
||||
(n, if c.closed { l / n as f64 } else { l / (n.max(2) - 1) as f64 })
|
||||
@@ -61,12 +67,25 @@ pub(crate) fn arraypath(
|
||||
pub(super) fn run_arraypath(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
let path = curves::handle_param(p, "path").ok_or_else(|| bad("arraypath", "`path` (handle) is required"))?;
|
||||
let count = p.get("count").and_then(Value::as_u64).map(|n| usize::try_from(n).unwrap_or(usize::MAX));
|
||||
let spacing = p.get("spacing").and_then(Value::as_f64);
|
||||
let r = arraypath(s, &hs, path, count, spacing, bool_or(p, "align", true))?;
|
||||
// As in the other arrays' JSON forms, a value that isn't a whole number of at least 1 (or a
|
||||
// positive spacing) is refused, not ignored; missing or null is the default.
|
||||
let count = crate::cmd::array::count_or("arraypath", p, "count", 6)?;
|
||||
let spacing = crate::cmd::size_param("arraypath", p, "spacing", false)?;
|
||||
let r = arraypath(s, &hs, path, Some(usize::try_from(count).unwrap_or(usize::MAX)), spacing, bool_or(p, "align", true))?;
|
||||
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The number of items typed at ARRAYPATH's prompt: a whole number from 1 to 32767, written in
|
||||
/// plain decimals. AutoCAD 2024 takes 5, +5, 05, 5., 5.0, 5.00 and +5.0 there, and refuses 4.5,
|
||||
/// 1e1, 8/2, 3', 0 and 32768 (measured).
|
||||
pub(super) fn item_count(t: &str) -> Option<usize> {
|
||||
let t = t.trim();
|
||||
let digits = t.strip_prefix('+').unwrap_or(t);
|
||||
let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
|
||||
let plain = !whole.is_empty() && whole.bytes().all(|b| b.is_ascii_digit()) && fraction.bytes().all(|b| b == b'0');
|
||||
whole.parse::<usize>().ok().filter(|n| plain && (1..=32_767).contains(n))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::cmd) struct PathArrayM {
|
||||
sel: SelectPhase,
|
||||
@@ -121,7 +140,7 @@ impl Interactive for PathArrayM {
|
||||
}
|
||||
(Some(path), inp @ (Input::Text(_) | Input::Enter)) => {
|
||||
let n = match &inp {
|
||||
Input::Text(t) => number(t).filter(|n| *n >= 1.0).ok_or_else(|| other("Requires a count of 1 or more."))? as usize,
|
||||
Input::Text(t) => item_count(t).ok_or_else(|| other("Requires an integer between 1 and 32767."))?,
|
||||
_ => 6,
|
||||
};
|
||||
arraypath(s, &self.objs, path, Some(n), None, true)?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Accept, Chain, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session, Spline,
|
||||
Step, Value, Vec2, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req, set_kind, str_param,
|
||||
targets,
|
||||
Accept, Chain, Entity, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session,
|
||||
Spline, Step, Value, Vec2, Vec3, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req,
|
||||
polyline_of, set_kind, set_polyline, str_param, targets,
|
||||
};
|
||||
|
||||
/// Fit curve: a tangent-continuous pair of arcs (biarc) per segment through every vertex,
|
||||
@@ -106,7 +106,21 @@ pub(crate) fn spline_vertices(vs: &[PolyVertex], closed: bool, segs: usize) -> V
|
||||
}
|
||||
|
||||
/// Join connected lines/arcs/open polylines onto the ends of polyline `h` (kept in place).
|
||||
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64) -> Result<usize> {
|
||||
///
|
||||
/// As AutoCAD 2024 joins (measured), none facing the other way: an arc or a polyline whose normal
|
||||
/// points down Z where the polyline's points up, or the other way round; a line counts as facing
|
||||
/// up. Multiple's Join (`same_height` false) takes them at any height (lines at Z 5 and Z 0 join).
|
||||
///
|
||||
/// PEDIT's own Join takes only objects in one plane with the polyline: the plane the polyline and
|
||||
/// every line picked share, when they share one, else the polyline's own. So a sloped line joins
|
||||
/// only when the polyline and all the lines picked lie in one plane (a vertical one for a sloped
|
||||
/// line continuing a straight polyline in plan), and then no arc or polyline joins, as those lie
|
||||
/// flat; otherwise only objects at the polyline's height join (a line, arc or polyline at Z 0
|
||||
/// stays off one at Z 5). Ends meet within `fuzz` in plan and within 1e-6 in height, which `fuzz`
|
||||
/// doesn't widen. After a sloped line the chain's end is at the line's far end, so the next object
|
||||
/// meets it there; AutoCAD's polyline then lies in the lines' plane, CADCraft's keeps the source's
|
||||
/// elevation and runs through the objects' points seen from above.
|
||||
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64, same_height: bool) -> Result<usize> {
|
||||
let e = curves::entity(s, h)?;
|
||||
let mut base = as_lwpoly(&e.kind).ok_or_else(|| other("Select a polyline."))?;
|
||||
if base.closed {
|
||||
@@ -114,46 +128,88 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
|
||||
}
|
||||
let mut chain = Chain::of(&EntityKind::LwPolyline(base.clone())).unwrap_or_default();
|
||||
let tol = fuzz.max(1e-6);
|
||||
let mut pool: Vec<(Handle, Chain)> = Vec::new();
|
||||
for o in others {
|
||||
if *o == h {
|
||||
// Which way an object faces, and its two ends' world heights.
|
||||
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
|
||||
let heights = |e: &Entity| match &e.kind {
|
||||
EntityKind::Line(l) => (l.a.z, l.b.z),
|
||||
// An arc's centre is in world coordinates.
|
||||
EntityKind::Arc(a) => (a.center.z, a.center.z),
|
||||
// A polyline's elevation runs along its normal.
|
||||
EntityKind::LwPolyline(p) => {
|
||||
let z = if down(e) { -p.elevation } else { p.elevation };
|
||||
(z, z)
|
||||
}
|
||||
_ => (0.0, 0.0),
|
||||
};
|
||||
// Two ends meet: in plan within the fuzz distance, and for PEDIT's own Join at the same height.
|
||||
let at = |p: Vec2, ph: f64, q: Vec2, qh: f64| p.near(q, tol) && (!same_height || (ph - qh).abs() < 1e-6);
|
||||
let picked: Vec<(Handle, Entity)> = others.iter().filter(|o| **o != h).filter_map(|o| Some((*o, curves::entity(s, *o).ok()?))).collect();
|
||||
// The plane PEDIT's own Join works in (AutoCAD 2024, measured): the polyline's points, with a
|
||||
// point off the chord of an arc segment, which lies flat, and the ends of every line picked.
|
||||
let z0 = heights(&e).0;
|
||||
let mut pts: Vec<Vec3> = base.vertices.iter().map(|v| Vec3::new(v.p.x, v.p.y, z0)).collect();
|
||||
if let Some(w) = base.vertices.windows(2).find(|w| w[0].bulge.abs() > 1e-12) {
|
||||
let (a, b) = (w[0].p, w[1].p);
|
||||
let off = (a + b) * 0.5 + Vec2::new(a.y - b.y, b.x - a.x);
|
||||
pts.push(Vec3::new(off.x, off.y, z0));
|
||||
}
|
||||
let lines: Vec<(Vec3, Vec3)> =
|
||||
picked.iter().filter_map(|(_, oe)| if let EntityKind::Line(l) = &oe.kind { Some((l.a, l.b)) } else { None }).collect();
|
||||
pts.extend(lines.iter().flat_map(|(a, b)| [*a, *b]));
|
||||
let shared = coplanar(&pts);
|
||||
// That plane is the polyline's own, flat, when every line is at its height.
|
||||
let level = lines.iter().all(|(a, b)| (a.z - z0).abs() < 1e-6 && (b.z - z0).abs() < 1e-6);
|
||||
let mut pool: Vec<(Handle, Chain, (f64, f64))> = Vec::new();
|
||||
for (o, oe) in &picked {
|
||||
if down(oe) != down(&e) {
|
||||
continue;
|
||||
}
|
||||
let Ok(oe) = curves::entity(s, *o) else { continue };
|
||||
let ok = matches!(&oe.kind, EntityKind::Line(_) | EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
|
||||
let line = matches!(oe.kind, EntityKind::Line(_));
|
||||
let (ah, bh) = heights(oe);
|
||||
// A sloped line lies in no flat plane, and an arc or a polyline in no other.
|
||||
let off_plane = if shared && !level { !line } else { (ah - bh).abs() >= 1e-6 };
|
||||
if same_height && off_plane {
|
||||
continue;
|
||||
}
|
||||
let ok = line || matches!(&oe.kind, EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
|
||||
if ok && let Some(c) = Chain::of(&oe.kind) {
|
||||
pool.push((*o, c));
|
||||
pool.push((*o, c, (ah, bh)));
|
||||
}
|
||||
}
|
||||
let (mut st_h, mut en_h) = heights(&e);
|
||||
let mut joined = Vec::new();
|
||||
while let (Some(st), Some(en)) = (chain.start(), chain.end()) {
|
||||
let Some(i) = pool
|
||||
.iter()
|
||||
.position(|(_, c)| c.start().zip(c.end()).is_some_and(|(a, b)| a.near(en, tol) || b.near(en, tol) || a.near(st, tol) || b.near(st, tol)))
|
||||
else {
|
||||
let meets = |c: &Chain, (ah, bh): (f64, f64)| {
|
||||
c.start().zip(c.end()).is_some_and(|(a, b)| at(a, ah, en, en_h) || at(b, bh, en, en_h) || at(a, ah, st, st_h) || at(b, bh, st, st_h))
|
||||
};
|
||||
let Some(i) = pool.iter().position(|(_, c, z)| meets(c, *z)) else {
|
||||
break;
|
||||
};
|
||||
let (oh, c) = pool.remove(i);
|
||||
let (oh, c, (ah, bh)) = pool.remove(i);
|
||||
let (Some(a), Some(b)) = (c.start(), c.end()) else { continue };
|
||||
if a.near(en, tol) {
|
||||
if at(a, ah, en, en_h) {
|
||||
chain.segs.extend(c.segs);
|
||||
} else if b.near(en, tol) {
|
||||
en_h = bh;
|
||||
} else if at(b, bh, en, en_h) {
|
||||
chain.segs.extend(c.reversed().segs);
|
||||
} else if b.near(st, tol) {
|
||||
en_h = ah;
|
||||
} else if at(b, bh, st, st_h) {
|
||||
let mut v = c.segs;
|
||||
v.extend(chain.segs);
|
||||
chain.segs = v;
|
||||
st_h = ah;
|
||||
} else {
|
||||
let mut v = c.reversed().segs;
|
||||
v.extend(chain.segs);
|
||||
chain.segs = v;
|
||||
st_h = bh;
|
||||
}
|
||||
joined.push(oh);
|
||||
}
|
||||
if joined.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| a.near(b, tol)) && chain.segs.len() > 1;
|
||||
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| at(a, st_h, b, en_h)) && chain.segs.len() > 1;
|
||||
base.vertices = chain.vertices();
|
||||
base.closed = chain.closed;
|
||||
let d = s.doc_mut()?;
|
||||
@@ -164,14 +220,29 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
|
||||
Ok(joined.len())
|
||||
}
|
||||
|
||||
/// Whether the points `pts` lie in one plane, to within 1e-6 (points in a line always do).
|
||||
fn coplanar(pts: &[Vec3]) -> bool {
|
||||
let Some(&p0) = pts.first() else { return true };
|
||||
let far = |a: &&Vec3, b: &&Vec3| (**a - p0).len().total_cmp(&(**b - p0).len());
|
||||
let Some(&p1) = pts.iter().max_by(far) else { return true };
|
||||
let d = p1 - p0;
|
||||
// The normal from the point farthest off the line p0 p1, for the least rounding.
|
||||
let Some(n) = pts.iter().map(|p| d.cross(*p - p0)).max_by(|a, b| a.len().total_cmp(&b.len())) else { return true };
|
||||
if n.len() <= 1e-6 * d.len() {
|
||||
return true;
|
||||
}
|
||||
let n = n.normalized();
|
||||
pts.iter().all(|p| n.dot(*p - p0).abs() < 1e-6)
|
||||
}
|
||||
|
||||
pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result<Value> {
|
||||
let e = curves::entity(s, h)?;
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
}
|
||||
let mut pl = match &e.kind {
|
||||
EntityKind::LwPolyline(pl) => pl.clone(),
|
||||
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => as_lwpoly(&e.kind).ok_or_else(|| other("Cannot convert."))?,
|
||||
let (mut pl, normal) = match &e.kind {
|
||||
EntityKind::LwPolyline(pl) => (pl.clone(), e.common.extrusion),
|
||||
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => polyline_of(&e).ok_or_else(|| other("Cannot convert."))?,
|
||||
_ => return Err(other("Object selected is not a polyline.")),
|
||||
};
|
||||
match opt {
|
||||
@@ -197,14 +268,14 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
|
||||
"reverse" | "r" => pl.vertices = curves::reverse_vertices(&pl.vertices, pl.closed),
|
||||
"ltypegen" | "l" => pl.plinegen = bool_or(p, "on", !pl.plinegen),
|
||||
"join" | "j" => {
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
let others: Vec<Handle> = p
|
||||
.get("handles2")
|
||||
.or_else(|| p.get("join"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(curves::handle_value).collect())
|
||||
.unwrap_or_default();
|
||||
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0))?;
|
||||
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0), true)?;
|
||||
return Ok(json!({ "handle": h.hex(), "joined": n }));
|
||||
}
|
||||
"vertex" | "e" => {
|
||||
@@ -254,7 +325,7 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
|
||||
}
|
||||
_ => return Err(bad("pedit", "unknown option")),
|
||||
}
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
Ok(json!({ "handle": h.hex() }))
|
||||
}
|
||||
|
||||
@@ -468,10 +539,9 @@ impl Interactive for PeditM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
let h = self.h.ok_or_else(|| other("No object."))?;
|
||||
let k = curves::entity(s, h)?.kind;
|
||||
let pl = as_lwpoly(&k).ok_or_else(|| other("Cannot convert."))?;
|
||||
let (pl, normal) = polyline_of(&curves::entity(s, h)?).ok_or_else(|| other("Cannot convert."))?;
|
||||
self.original = Some(pl.vertices.clone());
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
self.phase = PPhase::Main;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
@@ -544,7 +614,7 @@ impl Interactive for PeditM {
|
||||
SelOutcome::Done(hs) => {
|
||||
let h = self.h.ok_or_else(|| other("No polyline."))?;
|
||||
self.snapshot(s);
|
||||
let n = pedit_join(s, h, &hs, 0.0)?;
|
||||
let n = pedit_join(s, h, &hs, 0.0, true)?;
|
||||
s.echo(format!("{n} segments added to polyline"));
|
||||
s.set_selection(vec![h]);
|
||||
self.phase = PPhase::Main;
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde_json::json;
|
||||
use super::super::curves;
|
||||
use super::super::machines::{SelOutcome, SelectPhase, number};
|
||||
use super::pedit::{PPhase, PeditM, clear_widths, pedit_apply, pedit_join, yes_no};
|
||||
use super::{as_lwpoly, other, set_kind};
|
||||
use super::{other, polyline_of, set_kind, set_polyline};
|
||||
use crate::{Accept, Input, Prompt, Result, Session, Step};
|
||||
|
||||
/// Most option steps Undo can take back.
|
||||
@@ -78,13 +78,13 @@ impl PeditM {
|
||||
let no = !yes_no(&i)?;
|
||||
let mut kept = Vec::new();
|
||||
for h in std::mem::take(&mut self.multi) {
|
||||
let kind = curves::entity(s, h)?.kind;
|
||||
match kind {
|
||||
let e = curves::entity(s, h)?;
|
||||
match e.kind {
|
||||
EntityKind::LwPolyline(_) => kept.push(h),
|
||||
_ if no => {}
|
||||
k => {
|
||||
if let Some(pl) = as_lwpoly(&k) {
|
||||
set_kind(s, h, EntityKind::LwPolyline(pl))?;
|
||||
_ => {
|
||||
if let Some((pl, normal)) = polyline_of(&e) {
|
||||
set_polyline(s, h, pl, normal)?;
|
||||
kept.push(h);
|
||||
}
|
||||
}
|
||||
@@ -219,7 +219,7 @@ impl PeditM {
|
||||
let open = matches!(curves::entity(s, h)?.kind, EntityKind::LwPolyline(p) if !p.closed);
|
||||
if open {
|
||||
// A polyline that took on segments no longer goes back past the Join on Decurve.
|
||||
if pedit_join(s, h, &rest, fuzz)? > 0 {
|
||||
if pedit_join(s, h, &rest, fuzz, false)? > 0 {
|
||||
self.morig.remove(&h);
|
||||
}
|
||||
rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some()));
|
||||
|
||||
@@ -61,8 +61,11 @@ fn edit(sp: &Spline, opt: &str, p: &Value) -> Result<EntityKind> {
|
||||
spline(sp.refit(&fit, sp.closed))
|
||||
}
|
||||
"polyline" => {
|
||||
let precision = p.get("precision").and_then(Value::as_u64).unwrap_or(10).min(99) as usize;
|
||||
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision)))
|
||||
let precision = match p.get("precision") {
|
||||
None | Some(Value::Null) => 10,
|
||||
Some(v) => v.as_u64().filter(|n| *n <= 99).ok_or_else(|| bad("splinedit", "`precision` must be a whole number from 0 to 99"))?,
|
||||
};
|
||||
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision as usize)))
|
||||
}
|
||||
"move" => {
|
||||
let (i, to) = (index(p)?, point_req("splinedit", p, "to")?);
|
||||
@@ -96,7 +99,9 @@ fn spline_close(sp: &Spline) -> Spline {
|
||||
return sp.clone();
|
||||
}
|
||||
let mut out = if sp.fit.len() >= 2 {
|
||||
sp.refit(&sp.fit, true)
|
||||
// The open ends' tangents don't carry over: the closed curve takes its own where it closes.
|
||||
let opts = cadcraft_geom::FitOptions { start_tangent: None, end_tangent: None, ..sp.fit_opts };
|
||||
Spline::fit_with_end_derivatives(&sp.fit, true, opts)
|
||||
} else {
|
||||
let mut c = sp.control.clone();
|
||||
c.extend(sp.control.first().copied());
|
||||
@@ -235,11 +240,11 @@ fn tolerance(sp: &Spline, tol: f64) -> Result<Spline> {
|
||||
|
||||
// ---------------- control points ----------------
|
||||
|
||||
/// The number of distinct control points: a periodic spline repeats its first `degree` at the
|
||||
/// end, and a clamped closed one repeats its first at the end.
|
||||
/// The number of distinct control points: control points that wrap round repeat their first
|
||||
/// `degree` at the end, and a clamped closed spline repeats its first at the end.
|
||||
fn distinct(sp: &Spline) -> usize {
|
||||
let n = sp.control.len();
|
||||
if sp.is_periodic() {
|
||||
if sp.wraps() {
|
||||
n.saturating_sub(sp.degree)
|
||||
} else if sp.closed && n > 2 && sp.control.first().zip(sp.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
|
||||
n - 1
|
||||
@@ -311,7 +316,7 @@ fn delete_control(sp: &Spline, j: usize) -> Result<Spline> {
|
||||
}
|
||||
let mut s = without_fit(sp.clone());
|
||||
let w = |s: &Spline, i: usize| s.weights.get(i).copied().unwrap_or(1.0);
|
||||
if sp.is_periodic() {
|
||||
if sp.wraps() {
|
||||
if u <= p + 1 {
|
||||
return Err(other(format!("A closed spline of degree {p} needs more than {} control points.", p + 1)));
|
||||
}
|
||||
@@ -379,22 +384,30 @@ fn join(s: &mut Session, h: Handle, sp: &Spline, others: &[Handle]) -> Result<Ve
|
||||
}
|
||||
|
||||
/// A control point added by inserting a knot where the curve passes nearest `at`; the curve
|
||||
/// keeps its shape. A periodic spline is clamped at its seam first.
|
||||
/// keeps its shape. Control points that wrap round are clamped at the seam first.
|
||||
fn add_control(sp: &Spline, at: Vec2) -> Result<Spline> {
|
||||
let base = if sp.is_periodic() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
|
||||
let base = if sp.wraps() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
|
||||
let t = curves::spline_param_of(&base, at);
|
||||
let mut out = base.insert_knot(t).ok_or_else(|| other("Cannot add a control point to this spline."))?;
|
||||
out.closed = sp.closed;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The highest order Elevate order takes: degree 25 is the most `Spline::elevated` builds, and
|
||||
/// AutoCAD 2024's limit too.
|
||||
const MAX_ORDER: u64 = 26;
|
||||
|
||||
/// AutoCAD 2024's message for an order it refuses: from the spline's own order to 26 (measured at
|
||||
/// orders 4 and 5).
|
||||
fn order_range(sp: &Spline) -> crate::EngineError {
|
||||
other(format!("Requires an integer between {} and {MAX_ORDER}.", sp.degree as u64 + 1))
|
||||
}
|
||||
|
||||
/// The same curve at a higher order (degree + 1), with more control points.
|
||||
fn elevate(sp: &Spline, order: u64) -> Result<Spline> {
|
||||
// Degree 25 is the most `Spline::elevated` builds.
|
||||
let max = 26;
|
||||
let current = sp.degree as u64 + 1;
|
||||
if order < current || order > max {
|
||||
return Err(other(format!("Requires an order between {current} and {max}.")));
|
||||
if order < current || order > MAX_ORDER {
|
||||
return Err(order_range(sp));
|
||||
}
|
||||
if order == current {
|
||||
return Ok(sp.clone());
|
||||
@@ -585,6 +598,22 @@ impl SplineditM {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Elevate order's "Enter new order": a whole number as typed. AutoCAD 2024 takes +5 and 05
|
||||
/// and refuses 5.0, 5., 1e1, 4.5, 3, 27 and a point, all with the order range; Enter keeps
|
||||
/// the order (measured).
|
||||
fn input_order(&mut self, s: &mut Session, sp: &Spline, input: &Input) -> Result<()> {
|
||||
if *input != Input::Enter {
|
||||
let order = match input {
|
||||
Input::Text(t) => t.trim().parse::<u64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| order_range(sp))?;
|
||||
self.apply(s, json!({ "option": "elevate", "order": order }))?;
|
||||
}
|
||||
self.sub = Sub::Vertex;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Interactive for SplineditM {
|
||||
@@ -673,11 +702,15 @@ impl Interactive for SplineditM {
|
||||
}
|
||||
Sub::Join => self.input_join(s, h, &sp, &i)?,
|
||||
Sub::Precision => {
|
||||
// A whole number as typed: AutoCAD 2024 takes +5 and 05 and refuses 5.0, 5., 4.5,
|
||||
// 1e1, 8/2, 100, -1 and a point (measured).
|
||||
let precision = match &i {
|
||||
Input::Text(t) => number(t).filter(|n| (0.0..=99.0).contains(n)).ok_or_else(|| other("Requires an integer between 0 and 99."))?,
|
||||
_ => 10.0,
|
||||
};
|
||||
self.apply(s, json!({ "option": "polyline", "precision": precision.round() as u64 }))?;
|
||||
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| *n <= 99),
|
||||
Input::Enter => Some(10),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or_else(|| other("Requires an integer between 0 and 99."))?;
|
||||
self.apply(s, json!({ "option": "polyline", "precision": precision }))?;
|
||||
s.set_selection(Vec::new());
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
@@ -784,14 +817,7 @@ impl Interactive for SplineditM {
|
||||
None if enter => self.sub = Sub::Vertex,
|
||||
None => {}
|
||||
},
|
||||
Sub::VertexOrder => {
|
||||
if let Input::Text(t) = &i {
|
||||
let order =
|
||||
number(t).filter(|o| o.fract() == 0.0 && *o >= 1.0 && *o <= 1000.0).ok_or_else(|| other("Requires a whole number."))?;
|
||||
self.apply(s, json!({ "option": "elevate", "order": order as u64 }))?;
|
||||
}
|
||||
self.sub = Sub::Vertex;
|
||||
}
|
||||
Sub::VertexOrder => self.input_order(s, &sp, &i)?,
|
||||
Sub::VertexDelete => match point {
|
||||
Some(p) => {
|
||||
let u = distinct(&sp);
|
||||
|
||||
@@ -639,6 +639,32 @@ fn arraypath_json_and_command_line() {
|
||||
assert!(matches!(last(&s), EntityKind::Line(l) if near(l.a.xy(), -5.0, 20.0) && near(l.b.xy(), -6.0, 20.0)));
|
||||
assert!(s.execute("arraypath", &json!({"handles": [dot], "path": dot})).is_err());
|
||||
|
||||
// By spacing, AutoCAD 2024 fills a closed path with floor(length / spacing) items and an open
|
||||
// one with one more, at the end (measured on a 100 square and on the same square open).
|
||||
let square = [[0, 0], [100, 0], [100, 100], [0, 100]];
|
||||
let r400 = 400.0 / std::f64::consts::TAU;
|
||||
for (closed, spacing, items) in
|
||||
[(true, 100, 4), (true, 30, 13), (true, 200, 2), (true, 400, 1), (true, 399, 1), (false, 100, 4), (false, 30, 11), (false, 300, 2)]
|
||||
{
|
||||
let mut s = Session::new();
|
||||
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
|
||||
let path = h(&s.execute("pline", &json!({"points": square, "closed": closed})).unwrap());
|
||||
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": spacing})).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(items - 1), "closed {closed}, spacing {spacing}");
|
||||
}
|
||||
// A circle 400 round: 4 items at 100, none on the first (AutoCAD 2024, measured).
|
||||
let mut s = Session::new();
|
||||
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
|
||||
let path = h(&s.execute("circle", &json!({"center": [0, r400], "radius": r400})).unwrap());
|
||||
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 100})).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
|
||||
// Three sides of 0.35 add up to a hair under 3 × 0.35; the item at the end still fits.
|
||||
let mut s = Session::new();
|
||||
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 0.01})).unwrap());
|
||||
let path = h(&s.execute("pline", &json!({"points": [[0, 0], [0.35, 0], [0.35, 0.35], [0, 0.35]]})).unwrap());
|
||||
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 0.35})).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
@@ -649,6 +675,40 @@ fn arraypath_json_and_command_line() {
|
||||
assert_eq!(s.doc().unwrap().model.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arraypath_item_count_as_autocad_takes_it() {
|
||||
// AutoCAD 2024 at "Enter number of items along path": a whole number from 1 to 32767 in plain
|
||||
// decimals, 5. and 5.0 included; 4.5, 1e1, 8/2, 3', 0 and 32768 are refused.
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
s.cmdline("arraypath 0.25,1").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("5,0").unwrap();
|
||||
let asked = s.prompt_text();
|
||||
// Measured, then texts that aren't plain whole numbers (not measured).
|
||||
for t in ["4.5", "1e1", "8/2", "3'", "0", "32768", "+", ".5", "5.0.0", "5.1"] {
|
||||
s.cmdline(t).unwrap();
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 1 and 32767."), "{t}");
|
||||
assert_eq!(s.prompt_text(), asked, "{t}");
|
||||
}
|
||||
s.cmdline("3").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
// The ends of the range, without drawing 32,767 copies.
|
||||
assert_eq!((super::patharray::item_count("1"), super::patharray::item_count("32767")), (Some(1), Some(32_767)));
|
||||
for (typed, items) in [("5", 5), ("5.", 5), ("5.0", 5), ("5.00", 5), ("05.0", 5), ("+5.0", 5), ("05", 5), ("+4", 4), ("1", 1)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
for t in ["arraypath 0.25,1", "", "5,0", typed] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
|
||||
// The path and the items (the original is the first).
|
||||
assert_eq!(s.doc().unwrap().model.len(), 1 + items, "{typed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn textedit_json_and_command_line() {
|
||||
let mut s = Session::new();
|
||||
@@ -777,3 +837,155 @@ fn offset_elliptical_arc_follows_picked_side() {
|
||||
let outer = max_x(json!([20, 20]));
|
||||
assert!((outer - 11.0).abs() < 0.05, "outer side went inward: max x = {outer}");
|
||||
}
|
||||
|
||||
/// STRETCH against what AutoCAD 2024 stores for the same crossing window and displacement (5, 3)
|
||||
/// (black-box: synthetic objects in accoreconsole, read back with `entget`): the ends of an arc
|
||||
/// that are inside move and the arc keeps its height (bulge × chord / 2), as does a polyline arc
|
||||
/// segment; the centre alone moves nothing; a spline's control points inside move.
|
||||
#[test]
|
||||
fn stretch_arcs_bulges_and_splines_match_autocad() {
|
||||
enum Want {
|
||||
Arc([f64; 2], f64, f64, f64),
|
||||
Bulges(&'static [f64]),
|
||||
Control(&'static [[f64; 2]]),
|
||||
}
|
||||
// ((seed command, params), crossing window, what AutoCAD stores)
|
||||
let cases: Vec<((&str, Value), [[f64; 2]; 2], Want)> = vec![
|
||||
// SX-ARC-1END: one end of the arc inside.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[15.0, -5.0], [30.0, 5.0]],
|
||||
Want::Arc([3.17984478246544, -2.20611061402141], 22.43262716319083, 0.2342130724507349, 1.713026264953702),
|
||||
),
|
||||
// SX2-ARC-ENDPT: the other end inside.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[-5.0, 15.0], [5.0, 25.0]],
|
||||
Want::Arc([1.476584509301813, 4.310815984327269], 19.01841360081773, 6.054532724492258, 1.384456456611818),
|
||||
),
|
||||
// SX2-ARC-BIG-END: an arc over 180 degrees, its end inside.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 30.0, "end": 300.0})),
|
||||
[[5.0, -25.0], [15.0, -12.0]],
|
||||
Want::Arc([1.341732093243006, -0.7463649967436295], 19.25631435504786, 0.5920576993601167, 5.500876277544912),
|
||||
),
|
||||
// SX2-ARC-CEN: only the centre inside: unchanged.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[-3.0, -3.0], [16.0, 16.0]],
|
||||
Want::Arc([0.0, 0.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
|
||||
),
|
||||
// SX-ARC-ALL: the whole arc inside: moved.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
|
||||
[[-5.0, -5.0], [30.0, 30.0]],
|
||||
Want::Arc([5.0, 3.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
|
||||
),
|
||||
// A full-sweep arc (start = end) inside the window: moved whole, though its chord is zero.
|
||||
(
|
||||
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 45.0, "end": 45.0})),
|
||||
[[-25.0, -25.0], [25.0, 25.0]],
|
||||
Want::Arc([5.0, 3.0], 20.0, std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_4),
|
||||
),
|
||||
// SX-PLA-V1: the vertex starting an arc segment.
|
||||
(
|
||||
(
|
||||
"pline",
|
||||
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
|
||||
),
|
||||
[[25.0, -5.0], [35.0, 5.0]],
|
||||
Want::Bulges(&[0.0, 0.6337751582042422, 0.0, 0.0]),
|
||||
),
|
||||
// SX-PLA-V2: the vertex ending an arc segment.
|
||||
(
|
||||
(
|
||||
"pline",
|
||||
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
|
||||
),
|
||||
[[40.0, 15.0], [50.0, 25.0]],
|
||||
Want::Bulges(&[0.0, 0.4101116968279916, 0.0, 0.0]),
|
||||
),
|
||||
// SX2-PLA-NEG: a negative bulge over 180 degrees.
|
||||
(
|
||||
(
|
||||
"pline",
|
||||
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": -1.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
|
||||
),
|
||||
[[40.0, 15.0], [50.0, 25.0]],
|
||||
Want::Bulges(&[0.0, -1.230335090483974, 0.0, 0.0]),
|
||||
),
|
||||
// SX3-SPL-CV-ONLY: a window holding a control point but missing the drawn curve selects
|
||||
// nothing in AutoCAD ("0 found"), so the spline stays as it was.
|
||||
(
|
||||
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
|
||||
[[5.0, 95.0], [15.0, 105.0]],
|
||||
Want::Control(&[[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]]),
|
||||
),
|
||||
// SX3-SPL-CV-CROSS: the same control point in a window that also crosses the curve moves.
|
||||
(
|
||||
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
|
||||
[[5.0, 40.0], [15.0, 105.0]],
|
||||
Want::Control(&[[0.0, 0.0], [15.0, 103.0], [20.0, 100.0], [30.0, 0.0]]),
|
||||
),
|
||||
// SX-SPL: two control points inside.
|
||||
(
|
||||
("spline", json!({"control": [[0.0, 0.0], [10.0, 10.0], [20.0, 0.0], [30.0, 10.0]], "degree": 3})),
|
||||
[[15.0, -5.0], [35.0, 15.0]],
|
||||
Want::Control(&[[0.0, 0.0], [10.0, 10.0], [25.0, 3.0], [35.0, 13.0]]),
|
||||
),
|
||||
];
|
||||
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
|
||||
let same_angle = |a: f64, b: f64| {
|
||||
let d = (a - b).rem_euclid(std::f64::consts::TAU);
|
||||
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
|
||||
};
|
||||
for ((seed, params), window, want) in cases {
|
||||
let mut s = Session::new();
|
||||
let hd = h(&s.execute(seed, ¶ms).unwrap());
|
||||
s.execute("stretch", &json!({"window": window, "delta": [5.0, 3.0]})).unwrap();
|
||||
match (kind(&s, &hd), want) {
|
||||
(EntityKind::Arc(a), Want::Arc(c, r, start, end)) => assert!(
|
||||
same(a.center.x, c[0]) && same(a.center.y, c[1]) && same(a.radius, r) && same_angle(a.start, start) && same_angle(a.end, end),
|
||||
"{window:?}: {a:?}"
|
||||
),
|
||||
(EntityKind::LwPolyline(p), Want::Bulges(want)) => {
|
||||
let got: Vec<f64> = p.vertices.iter().map(|v| v.bulge).collect();
|
||||
assert!(got.len() == want.len() && got.iter().zip(want).all(|(a, b)| same(*a, *b)), "{window:?}: {got:?} / {want:?}");
|
||||
}
|
||||
(EntityKind::Spline(sp), Want::Control(want)) => {
|
||||
let ok = sp.control.len() == want.len() && sp.control.iter().zip(want).all(|(p, w)| same(p.x, w[0]) && same(p.y, w[1]));
|
||||
assert!(ok, "{window:?}: {:?} / {want:?}", sp.control);
|
||||
}
|
||||
(k, _) => panic!("{window:?}: {k:?}"),
|
||||
}
|
||||
}
|
||||
// A spline built from fit points: the fit points inside move and it is fitted through them
|
||||
// again, keeping its fit data; all of them inside, it moves whole (AutoCAD 2024, `entget`
|
||||
// after STRETCH of a spline stored with these fit points only).
|
||||
let fit = [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [230.0, 10.0]];
|
||||
let fit_cases: [([[f64; 2]; 2], [f64; 2], [[f64; 2]; 4]); 3] = [
|
||||
([[225.0, 5.0], [235.0, 15.0]], [5.0, 0.0], [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [235.0, 10.0]]),
|
||||
([[205.0, 5.0], [215.0, 15.0]], [0.0, 5.0], [[200.0, 0.0], [210.0, 15.0], [220.0, 0.0], [230.0, 10.0]]),
|
||||
([[195.0, -5.0], [235.0, 15.0]], [5.0, 5.0], [[205.0, 5.0], [215.0, 15.0], [225.0, 5.0], [235.0, 15.0]]),
|
||||
];
|
||||
for (window, delta, want) in fit_cases {
|
||||
let mut s = Session::new();
|
||||
let hd = h(&s.execute("spline", &json!({ "fit": fit })).unwrap());
|
||||
s.execute("stretch", &json!({ "window": window, "delta": delta })).unwrap();
|
||||
let EntityKind::Spline(sp) = kind(&s, &hd) else { panic!("not a spline") };
|
||||
let got: Vec<[f64; 2]> = sp.fit.iter().map(|p| [p.x, p.y]).collect();
|
||||
assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| same(g[0], w[0]) && same(g[1], w[1])), "{window:?}: {got:?}");
|
||||
// The curve still runs through them.
|
||||
let (lo, hi) = sp.domain();
|
||||
for w in want {
|
||||
let q = cadcraft_geom::Vec2::new(w[0], w[1]);
|
||||
let near = (0..=4000).map(|i| sp.eval(lo + (hi - lo) * f64::from(i) / 4000.0).dist(q)).fold(f64::INFINITY, f64::min);
|
||||
assert!(near < 1e-2, "{window:?}: {w:?} is {near} off the curve");
|
||||
}
|
||||
}
|
||||
// A stretch that brings an arc segment's ends together leaves no arc to keep: the bulge goes.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([{"p": [0, 0], "bulge": 0.5}, [10, 0], [20, 0]]), false);
|
||||
s.execute("stretch", &json!({"window": [[9, -1], [11, 1]], "delta": [-10, 0]})).unwrap();
|
||||
assert_eq!(poly(&kind(&s, &p)).vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), [0.0, 0.0, 0.0]);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ pub const PROFILE_VARS: &[&str] = &[
|
||||
"CURSORSIZE",
|
||||
"PICKFIRST",
|
||||
"PICKADD",
|
||||
"COPYMODE",
|
||||
"PICKDRAG",
|
||||
"MAXARRAY",
|
||||
"MEASUREINIT",
|
||||
@@ -157,6 +158,7 @@ pub fn reset(s: &mut Session) {
|
||||
st.cursorsize = d.cursorsize;
|
||||
st.pickfirst = d.pickfirst;
|
||||
st.pickadd = d.pickadd;
|
||||
st.copymode = d.copymode;
|
||||
st.pickdrag = d.pickdrag;
|
||||
st.maxarray = d.maxarray;
|
||||
st.dynprompt = d.dynprompt;
|
||||
|
||||
@@ -449,7 +449,7 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc_mut()?;
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.text_style(&name).cloned();
|
||||
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
let idx = match d.text_styles.position_by_name(&name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
d.text_styles.push(cadcraft_doc::TextStyle { name: name.clone(), ..Default::default() });
|
||||
@@ -554,7 +554,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.text_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("style.rename", format!("a text style `{to}` already exists")));
|
||||
}
|
||||
let st = d.text_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("style.rename", "no such style"))?;
|
||||
let st = d.text_styles.by_name_mut(&from).ok_or_else(|| bad("style.rename", "no such style"))?;
|
||||
st.name = to.clone();
|
||||
// References follow the new name.
|
||||
let fix = |n: &mut String| {
|
||||
@@ -642,7 +642,7 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.dim_style(&name).cloned();
|
||||
let base = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default();
|
||||
let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
let idx = match d.dim_styles.position_by_name(&name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
d.dim_styles.push(cadcraft_doc::DimStyle { name: name.clone(), ..base });
|
||||
@@ -792,7 +792,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.dim_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("dimstyle.rename", format!("a dimension style `{to}` already exists")));
|
||||
}
|
||||
let st = d.dim_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
|
||||
let st = d.dim_styles.by_name_mut(&from).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
|
||||
st.name = to.clone();
|
||||
if d.header.str("DIMSTYLE", "Standard").eq_ignore_ascii_case(&from) {
|
||||
d.header.set_str("DIMSTYLE", &to);
|
||||
@@ -1015,7 +1015,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.linetype(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("rename", format!("a linetype `{to}` already exists")));
|
||||
}
|
||||
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
|
||||
let st = d.linetypes.by_name_mut(&from).ok_or_else(|| bad("rename", "no such linetype"))?;
|
||||
st.name = to.clone();
|
||||
// References follow the new name.
|
||||
let fix = |n: &mut String| {
|
||||
|
||||
@@ -59,7 +59,7 @@ fn put(d: &mut Drawing, lt: Linetype, reload: bool, out: &mut Loaded) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match d.linetypes.iter_mut().find(|l| l.name.eq_ignore_ascii_case(<.name)) {
|
||||
match d.linetypes.by_name_mut(<.name) {
|
||||
Some(old) if reload => {
|
||||
out.reloaded.push(old.name.clone());
|
||||
// The drawing keeps the name as it had it (objects refer to it).
|
||||
|
||||
@@ -202,6 +202,7 @@ pub const NO_FILES: &[&str] = &[
|
||||
"dim",
|
||||
"mleader",
|
||||
"leader",
|
||||
"qleader",
|
||||
"dimstyle.update",
|
||||
"dimoverride",
|
||||
"dimreassociate",
|
||||
|
||||
@@ -37,6 +37,7 @@ const NO_OR: &[&str] = &[
|
||||
"Choose mode for selected object conversion",
|
||||
"Create annotative block",
|
||||
"Enter a configuration option",
|
||||
"Enter a copy mode option",
|
||||
"Enter a plotting preference",
|
||||
"Enter an annotation option",
|
||||
"Enter an option",
|
||||
|
||||
@@ -75,6 +75,8 @@ pub struct Settings {
|
||||
/// FILEDIA: kept for routines that switch file dialogs off around a script; no command reads it yet.
|
||||
pub filedia: bool,
|
||||
pub pickadd: bool,
|
||||
/// COPYMODE: COPY makes one copy and ends (true, 1), or copies until Enter (false, 0).
|
||||
pub copymode: bool,
|
||||
/// PICKDRAG: false = two-click windows (0), true = clicks or dragging (2).
|
||||
/// Drag-only mode (1) is not supported yet.
|
||||
pub pickdrag: bool,
|
||||
@@ -180,6 +182,7 @@ impl Default for Settings {
|
||||
cmdecho: true,
|
||||
filedia: true,
|
||||
pickadd: true,
|
||||
copymode: false,
|
||||
pickdrag: true,
|
||||
pickstyle: 1,
|
||||
gripsize: 5.0,
|
||||
|
||||
@@ -162,7 +162,7 @@ impl SpatialIndex {
|
||||
SpatialIndex {
|
||||
store: store.clone(),
|
||||
blocks: (*d.blocks).clone(),
|
||||
dim_styles: d.dim_styles.clone(),
|
||||
dim_styles: d.dim_styles.to_vec(),
|
||||
dimscale: d.header.f64("DIMSCALE", 1.0),
|
||||
anno: anno_key(d),
|
||||
hidden_layers: hidden_layers(d).map(str::to_owned).collect(),
|
||||
@@ -178,7 +178,7 @@ impl SpatialIndex {
|
||||
self.blocks.len() == d.blocks.len()
|
||||
&& self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b))
|
||||
&& self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits()
|
||||
&& self.dim_styles == d.dim_styles
|
||||
&& self.dim_styles == *d.dim_styles
|
||||
&& self.anno == anno_key(d)
|
||||
&& self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d))
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ const SESSION_VARS: &[&str] = &[
|
||||
"CMDECHO",
|
||||
"FILEDIA",
|
||||
"PICKADD",
|
||||
"COPYMODE",
|
||||
"PICKDRAG",
|
||||
"PICKSTYLE",
|
||||
"GRIPSIZE",
|
||||
@@ -140,6 +141,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"CMDECHO" => json!(i32::from(st.cmdecho)),
|
||||
"FILEDIA" => json!(i32::from(st.filedia)),
|
||||
"PICKADD" => json!(i32::from(st.pickadd)),
|
||||
"COPYMODE" => json!(i32::from(st.copymode)),
|
||||
"PICKDRAG" => json!(i32::from(st.pickdrag) * 2),
|
||||
"PICKSTYLE" => json!(st.pickstyle),
|
||||
"GRIPSIZE" => json!(st.gripsize),
|
||||
@@ -394,6 +396,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
"CMDECHO" => st.cmdecho = small(v, 1).ok_or_else(bad)? == 1,
|
||||
"FILEDIA" => st.filedia = small(v, 1).ok_or_else(bad)? == 1,
|
||||
"PICKADD" => st.pickadd = as_bool(v).ok_or_else(bad)?,
|
||||
"COPYMODE" => st.copymode = small(v, 1).ok_or_else(bad)? == 1,
|
||||
"PICKDRAG" => st.pickdrag = as_i(v).filter(|b| matches!(b, 0 | 2)).map(|b| b == 2).ok_or_else(bad)?,
|
||||
"PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?,
|
||||
"GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0),
|
||||
|
||||
@@ -67,6 +67,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)),
|
||||
("OFFSETERASE", Kind::Choice(&[0, 1]), Def::Int(0)),
|
||||
("OFFSETLAYER", Kind::Choice(&[0, 1]), Def::Int(0)),
|
||||
// The width a new polyline starts at; PLINE's Width and Halfwidth answers set it.
|
||||
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
|
||||
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
|
||||
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
|
||||
|
||||
@@ -1309,6 +1309,62 @@ fn pline_width_answers_taper_the_next_segment() {
|
||||
assert_eq!(widths(&p), (0.0, vec![(0.0, 0.0), (0.0, 0.0)]));
|
||||
}
|
||||
|
||||
/// PLINE against what AutoCAD 2024 stores for the same typed input (black-box: synthetic input
|
||||
/// in accoreconsole, read back with `entget` and GETVAR).
|
||||
#[test]
|
||||
fn pline_undo_mode_and_plinewid_match_autocad() {
|
||||
// Undo after an arc segment returns to line mode, where `_L` is Length (a point gives the
|
||||
// length, along the last segment).
|
||||
let p = typed_pline(
|
||||
"pline -0.702422643378533,-28.46727901968281 -27.912058384977463,-34.74188138168937 -22.546524604415925,32.44142803067136 _U \
|
||||
25.831317263304115,13.510616645626207 _A -33.2372517304228,12.083585785350365 _U _L -22.546524604415925,32.44142803067136",
|
||||
);
|
||||
let want = [
|
||||
(-0.7024226433785329, -28.4672790196828),
|
||||
(-27.91205838497746, -34.74188138168937),
|
||||
(25.83131726330411, 13.5106166456262),
|
||||
(64.48701958199356, 48.21692560701169),
|
||||
];
|
||||
assert_eq!(p.vertices.len(), want.len(), "{p:?}");
|
||||
for (v, (x, y)) in p.vertices.iter().zip(want) {
|
||||
assert!(v.p.near(Vec2::new(x, y), 1e-9 * x.abs().max(y.abs())) && v.bulge == 0.0, "{p:?}");
|
||||
}
|
||||
// PLINEWID is the width a new polyline starts with…
|
||||
let mut s = Session::new();
|
||||
s.cmdline("(setvar \"PLINEWID\" 0.75)").unwrap();
|
||||
s.cmdline("pline -21.06802233135781,9.943678105070298 -29.261665218975015,-28.460093326613574 7.898763272534772,6.73634194079888").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(matches!(&s.doc().unwrap().model.last().unwrap().kind, EntityKind::LwPolyline(p) if p.const_width == 0.75));
|
||||
// …and the ending width of the last Width or Halfwidth answer (half-width 0.5: PLINEWID 1).
|
||||
let mut s = Session::new();
|
||||
s.cmdline("pline -9.151085154682761,12.9438035725412 _W 0.0934460985004879 1.547654372298795").unwrap();
|
||||
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 1.547654372298795);
|
||||
s.cmdline("19.161590651864245,38.23079339857958 26.720225103092986,-9.028145532375504 _H 0.5 0.5 -24.7035288980598,-14.309723714209586").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 1.0);
|
||||
// PLINEWID is an ordinary system variable: 0 until set, typed at the command line or set
|
||||
// with SETVAR, and that width is where the next polyline starts.
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("getvar", &json!({"name": "PLINEWID"})).unwrap();
|
||||
assert_eq!(r["value"].as_f64(), Some(0.0), "{r}");
|
||||
s.cmdline("plinewid 0.5").unwrap();
|
||||
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 0.5);
|
||||
s.cmdline("pline 0,0 10,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(matches!(&s.doc().unwrap().model.last().unwrap().kind, EntityKind::LwPolyline(p) if p.const_width == 0.5));
|
||||
// The JSON form starts there too, unless it gives a width or its vertices give theirs.
|
||||
let width = |s: &mut Session, p: serde_json::Value| {
|
||||
s.execute("pline", &p).unwrap();
|
||||
match &s.doc().unwrap().model.last().unwrap().kind {
|
||||
EntityKind::LwPolyline(p) => p.const_width,
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
};
|
||||
assert_eq!(width(&mut s, json!({"vertices": [[0, 0], [10, 0]]})), 0.5);
|
||||
assert_eq!(width(&mut s, json!({"vertices": [[0, 0], [10, 0]], "width": 0})), 0.0);
|
||||
assert_eq!(width(&mut s, json!({"vertices": [{"p": [0, 0], "startWidth": 1, "endWidth": 2}, [10, 0]]})), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn press_and_drag_selection_window() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -198,7 +198,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
|
||||
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)) {
|
||||
if let Some(l) = d.layouts.by_name_mut(layout) {
|
||||
l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name));
|
||||
}
|
||||
}
|
||||
@@ -210,7 +210,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
|
||||
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),
|
||||
Space::Paper(layout) => d.layouts.by_name_mut(layout).map(|l| &mut l.ucs_previous),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -229,3 +229,34 @@ fn json_arraypolar_rejects_bad_fill_angles() {
|
||||
s.execute("arraypolar", &p).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_arraypath_rejects_a_bad_count_or_spacing() {
|
||||
// As arrayrect's and arraypolar's counts: not a whole number of at least 1 is refused, as is a
|
||||
// spacing that isn't a positive number. Before, these fell back to the default 6 items.
|
||||
let mut s = Session::new();
|
||||
let h = s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap()["handle"].clone();
|
||||
let path = s.execute("line", &json!({"points": [[0, 0], [100, 0]]})).unwrap()["handles"][0].clone();
|
||||
let before = s.doc().unwrap().model.iter().count();
|
||||
for (key, bad) in [
|
||||
("count", json!(0)),
|
||||
("count", json!(-3)),
|
||||
("count", json!(4.5)),
|
||||
("count", json!("8")),
|
||||
("spacing", json!(0)),
|
||||
("spacing", json!(-5)),
|
||||
("spacing", json!("10")),
|
||||
] {
|
||||
let p = json!({"handles": [h], "path": path, key: bad});
|
||||
let e = s.execute("arraypath", &p).unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("`{key}`")), "{key} {bad}: {e}");
|
||||
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{key} {bad}");
|
||||
}
|
||||
// Missing or null is the default, 6 items: the original and 5 copies.
|
||||
for p in [json!({"handles": [h], "path": path}), json!({"handles": [h], "path": path, "count": null, "spacing": null})] {
|
||||
assert_eq!(s.execute("arraypath", &p).unwrap()["handles"].as_array().map(Vec::len), Some(5), "{p}");
|
||||
}
|
||||
// One item is the original alone; a spacing of 25 along 100 is 5 items.
|
||||
assert_eq!(s.execute("arraypath", &json!({"handles": [h], "path": path, "count": 1})).unwrap()["handles"], json!([]));
|
||||
assert_eq!(s.execute("arraypath", &json!({"handles": [h], "path": path, "spacing": 25})).unwrap()["handles"].as_array().map(Vec::len), Some(4));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! The counts the ARRAY commands ask for take a whole number as typed, as AutoCAD 2024's do
|
||||
//! (measured in its core console at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows,
|
||||
//! and -ARRAY's rows and items): +3 and 03 are three, and 5.0, 1e1, 8/2 and 3' are refused and
|
||||
//! asked for again.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{ArrayKind, EntityKind, Handle};
|
||||
use serde_json::json;
|
||||
|
||||
/// Texts AutoCAD 2024 refuses at an array count.
|
||||
const REFUSED: [&str; 6] = ["5.0", "4.", "1e1", "8/2", "3'", "4.5"];
|
||||
|
||||
fn typed(s: &mut Session, inputs: &[&str]) {
|
||||
for t in inputs {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Each refused text gets the count message, and the same prompt again.
|
||||
fn refuses_and_asks_again(s: &mut Session) {
|
||||
let asked = s.prompt_text();
|
||||
for t in REFUSED {
|
||||
s.cmdline(t).unwrap();
|
||||
assert!(s.log.last().is_some_and(|l| l.starts_with("Requires an integer between 1 and")), "{t}: {:?}", s.log.last());
|
||||
assert_eq!(s.prompt_text(), asked, "{t}");
|
||||
}
|
||||
}
|
||||
|
||||
fn lines(s: &Session) -> usize {
|
||||
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
|
||||
}
|
||||
|
||||
fn with_line() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[10, 0], [12, 0]] })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrayrect_columns_and_rows() {
|
||||
let mut s = with_line();
|
||||
typed(&mut s, &["arrayrect", "l", "", "cou"]);
|
||||
assert!(s.prompt_text().contains("Enter the number of columns"), "{}", s.prompt_text());
|
||||
refuses_and_asks_again(&mut s);
|
||||
s.cmdline("+3").unwrap();
|
||||
assert!(s.prompt_text().contains("Enter the number of rows"), "{}", s.prompt_text());
|
||||
refuses_and_asks_again(&mut s);
|
||||
typed(&mut s, &["03", "as", "n", "x"]);
|
||||
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), 9);
|
||||
}
|
||||
|
||||
/// The bounds are CADCraft's, which this rule leaves as they were: a count runs from 1 to what
|
||||
/// MAXARRAY allows for the array's other counts. With MAXARRAY 100 and three rows, 0 and 34 columns
|
||||
/// are refused and 33 taken; then 4 rows are refused and 3 taken.
|
||||
#[test]
|
||||
fn a_count_runs_from_one_to_the_maxarray_limit() {
|
||||
let mut s = with_line();
|
||||
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
|
||||
typed(&mut s, &["arrayrect", "l", "", "cou"]);
|
||||
let refused = |s: &mut Session, texts: &[&str], max: u64| {
|
||||
let asked = s.prompt_text();
|
||||
for t in texts {
|
||||
s.cmdline(t).unwrap();
|
||||
let msg = format!("Requires an integer between 1 and {max} ");
|
||||
assert!(s.log.last().is_some_and(|l| l.starts_with(&msg)), "{t}: {:?}", s.log.last());
|
||||
assert_eq!(s.prompt_text(), asked, "{t}");
|
||||
}
|
||||
};
|
||||
assert!(s.prompt_text().contains("Enter the number of columns"), "{}", s.prompt_text());
|
||||
refused(&mut s, &["0", "34"], 33);
|
||||
s.cmdline("33").unwrap();
|
||||
assert!(s.prompt_text().contains("Enter the number of rows"), "{}", s.prompt_text());
|
||||
refused(&mut s, &["0", "4"], 3);
|
||||
typed(&mut s, &["3", "as", "n", "x"]);
|
||||
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), 99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arraypolar_items() {
|
||||
let mut s = with_line();
|
||||
typed(&mut s, &["arraypolar", "l", "", "0,0", "i"]);
|
||||
assert!(s.prompt_text().contains("Enter number of items in array"), "{}", s.prompt_text());
|
||||
refuses_and_asks_again(&mut s);
|
||||
typed(&mut s, &["+5", "as", "n", "x"]);
|
||||
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), 5);
|
||||
}
|
||||
|
||||
/// ARRAYEDIT's counts go through the same count parser as ARRAYRECT's, ARRAYPOLAR's and -ARRAY's
|
||||
/// (`count()` in `crates/engine/src/cmd/array.rs`), so they refuse and take the same texts: here 5.0,
|
||||
/// 5., 4.5, 1e1 and 8/2 are refused at a rectangular array's columns and rows and a polar array's
|
||||
/// items, and +5, 05 and 5 are taken. No AutoCAD measurement of ARRAYEDIT is claimed.
|
||||
#[test]
|
||||
fn arrayedit_counts() {
|
||||
let refused = ["5.0", "5.", "4.5", "1e1", "8/2"];
|
||||
let edit = |s: &mut Session, h: Handle, option: &str, asked: &str, count: &str, after: &[&str]| {
|
||||
s.set_selection(vec![h]);
|
||||
typed(s, &["arrayedit", option]);
|
||||
assert!(s.prompt_text().contains(asked), "{}", s.prompt_text());
|
||||
let prompt = s.prompt_text();
|
||||
for t in refused {
|
||||
s.cmdline(t).unwrap();
|
||||
assert!(s.log.last().is_some_and(|l| l.starts_with("Requires an integer between 1 and")), "{t}: {:?}", s.log.last());
|
||||
assert_eq!(s.prompt_text(), prompt, "{t}");
|
||||
}
|
||||
s.cmdline(count).unwrap();
|
||||
typed(s, after);
|
||||
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
|
||||
let d = s.doc().unwrap();
|
||||
d.array_params(d.entity(h).unwrap()).unwrap().kind
|
||||
};
|
||||
let mut s = with_line();
|
||||
let l = s.doc().unwrap().model.iter().next().unwrap().handle.hex();
|
||||
let r = s.execute("arrayrect", &json!({ "handles": [l], "cols": 4, "rows": 3, "colSpacing": 5, "rowSpacing": 5 })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let ArrayKind::Rect(a) = edit(&mut s, h, "col", "Enter the number of columns", "+5", &["", "x"]) else { panic!("not rectangular") };
|
||||
assert_eq!((a.cols, a.rows), (5, 3));
|
||||
let ArrayKind::Rect(a) = edit(&mut s, h, "r", "Enter the number of rows", "05", &["", "", "x"]) else { panic!("not rectangular") };
|
||||
assert_eq!((a.cols, a.rows), (5, 5));
|
||||
|
||||
let mut s = with_line();
|
||||
let l = s.doc().unwrap().model.iter().next().unwrap().handle.hex();
|
||||
let r = s.execute("arraypolar", &json!({ "handles": [l], "center": [0, -50], "count": 6 })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let ArrayKind::Polar(a) = edit(&mut s, h, "i", "Enter number of items in array", "5", &["x"]) else { panic!("not polar") };
|
||||
assert_eq!(a.items, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_array_rows_columns_and_items() {
|
||||
let mut s = with_line();
|
||||
typed(&mut s, &["-array", "l", "", "r"]);
|
||||
assert!(s.prompt_text().contains("Enter the number of rows (---)"), "{}", s.prompt_text());
|
||||
refuses_and_asks_again(&mut s);
|
||||
s.cmdline("03").unwrap();
|
||||
assert!(s.prompt_text().contains("Enter the number of columns (|||)"), "{}", s.prompt_text());
|
||||
refuses_and_asks_again(&mut s);
|
||||
typed(&mut s, &["+2", "5", "5"]);
|
||||
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), 6);
|
||||
|
||||
let mut s = with_line();
|
||||
typed(&mut s, &["-array", "l", "", "p", "0,0"]);
|
||||
assert!(s.prompt_text().contains("Enter the number of items in the array"), "{}", s.prompt_text());
|
||||
refuses_and_asks_again(&mut s);
|
||||
typed(&mut s, &["+3", "360", "y"]);
|
||||
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), 3);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! COPY at the command line as AutoCAD 2024 runs it (accoreconsole, a line from (0, 0) to (1, 0)
|
||||
//! copied with `(command "_.COPY" line "" ...)`, then the start point of every line):
|
||||
//!
|
||||
//! - COPYMODE 1 makes one copy and ends; Multiple copies until Exit or Enter, and Undo takes back
|
||||
//! the last placement, a whole array at once;
|
||||
//! - Enter at the first second point copies by the base point taken as a displacement;
|
||||
//! - Array asks for a number of items, the original included (2 to 32767), and puts them the
|
||||
//! second point apart, or spread up to it with Fit; Enter there leaves them at the base.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::json;
|
||||
|
||||
/// A session with one line from (0, 0) to (1, 0) and COPYMODE set to `mode`.
|
||||
fn with_line(mode: i64) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap();
|
||||
s.execute("setvar", &json!({ "name": "COPYMODE", "value": mode })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The start point of every line, sorted.
|
||||
fn starts(s: &Session) -> Vec<(f64, f64)> {
|
||||
let mut v: Vec<(f64, f64)> =
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.x, l.a.y)) } else { None }).collect();
|
||||
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
v
|
||||
}
|
||||
|
||||
fn copymode(s: &mut Session) -> serde_json::Value {
|
||||
s.execute("getvar", &json!({ "name": "COPYMODE" })).unwrap()["value"].clone()
|
||||
}
|
||||
|
||||
/// Types COPY, selects everything, then each of `inputs`.
|
||||
fn copy(s: &mut Session, inputs: &[&str]) {
|
||||
for t in ["COPY", "all", ""].iter().chain(inputs) {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copymode_1_makes_one_copy_and_ends() {
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["0,0"]);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array] <use first point as displacement>:");
|
||||
s.cmdline("10,0").unwrap();
|
||||
assert!(s.current_prompt().is_none(), "COPY ended");
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0)]);
|
||||
assert_eq!(copymode(&mut s), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_base_point_prompt_offers_mode_and_multiple() {
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &[]);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify base point or [Displacement/mOde/Multiple] <Displacement>:");
|
||||
// Multiple, this once: the option goes and COPYMODE stays 1.
|
||||
s.cmdline("M").unwrap();
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify base point or [Displacement/mOde] <Displacement>:");
|
||||
for t in ["0,0", "10,0", "20,0"] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array/Exit/Undo] <Exit>:");
|
||||
s.cmdline("E").unwrap();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)]);
|
||||
assert_eq!(copymode(&mut s), json!(1));
|
||||
// Multiple, then mOde with Enter: the mode shown (Single, COPYMODE 1) is the mode COPY runs in.
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["M", "O"]);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Enter a copy mode option [Single/Multiple] <Single>:");
|
||||
for t in ["", "0,0", "5,0"] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.current_prompt().is_none(), "one copy");
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0)]);
|
||||
// mOde sets COPYMODE.
|
||||
let mut s = with_line(0);
|
||||
copy(&mut s, &["O"]);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Enter a copy mode option [Single/Multiple] <Multiple>:");
|
||||
s.cmdline("S").unwrap();
|
||||
assert_eq!(copymode(&mut s), json!(1));
|
||||
for t in ["0,0", "5,0"] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.current_prompt().is_none(), "one copy, now single");
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copymode_0_copies_until_enter_and_undo_takes_back_the_last() {
|
||||
let mut s = with_line(0);
|
||||
copy(&mut s, &["0,0", "10,0", "20,0", "U", "30,0", ""]);
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (30.0, 0.0)]);
|
||||
// Undoing the only copy goes back to the first prompt.
|
||||
let mut s = with_line(0);
|
||||
copy(&mut s, &["0,0", "10,0", "U"]);
|
||||
assert!(s.log.iter().any(|l| l == "Command has been completely undone."), "{:?}", s.log);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array] <use first point as displacement>:");
|
||||
s.cmdline("30,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (30.0, 0.0)]);
|
||||
// An array is one placement: Undo takes all its items back.
|
||||
let mut s = with_line(0);
|
||||
copy(&mut s, &["0,0", "10,0", "A", "3", "0,5", "U", "40,0", ""]);
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (40.0, 0.0)]);
|
||||
// An array after a copy, and more after it.
|
||||
let mut s = with_line(0);
|
||||
copy(&mut s, &["3,4", "10,4", "A", "2", "20,4", ""]);
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (7.0, 0.0), (17.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_at_the_first_second_point_copies_by_the_base_point() {
|
||||
for mode in [0, 1] {
|
||||
let mut s = with_line(mode);
|
||||
copy(&mut s, &["3,4", ""]);
|
||||
assert!(s.current_prompt().is_none(), "COPYMODE {mode}");
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (3.0, 4.0)], "COPYMODE {mode}");
|
||||
}
|
||||
// Displacement, and Enter at the base point (its default), make one copy too.
|
||||
for inputs in [["D", "5,6"], ["", "7,8"]] {
|
||||
let mut s = with_line(0);
|
||||
copy(&mut s, &inputs);
|
||||
assert!(s.current_prompt().is_none(), "{inputs:?}");
|
||||
assert_eq!(starts(&s).len(), 2, "{inputs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_puts_the_items_a_second_point_apart_or_fits_them() {
|
||||
// (inputs after the base point (0, 0), AutoCAD's lines)
|
||||
let cases: [(&[&str], &[(f64, f64)]); 5] = [
|
||||
(&["A", "4", "10,5"], &[(0.0, 0.0), (10.0, 5.0), (20.0, 10.0), (30.0, 15.0)]),
|
||||
(&["A", "4", "F", "30,0"], &[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (30.0, 0.0)]),
|
||||
// Fit, then Array again: back to the spacing.
|
||||
(&["A", "3", "F", "A", "10,0"], &[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)]),
|
||||
// The base point again, or Enter: every item at the base.
|
||||
(&["A", "3", "0,0"], &[(0.0, 0.0); 3]),
|
||||
(&["A", "3", ""], &[(0.0, 0.0); 3]),
|
||||
];
|
||||
for (inputs, want) in cases {
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["0,0"]);
|
||||
for t in inputs {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.current_prompt().is_none(), "{inputs:?}");
|
||||
assert_eq!(starts(&s), want, "{inputs:?}");
|
||||
}
|
||||
// Enter at the array's point with the base at (3, 4): still on the original, the base
|
||||
// isn't taken as a displacement there.
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["3,4", "A", "3", ""]);
|
||||
assert_eq!(starts(&s), [(0.0, 0.0); 3]);
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["0,0", "A", "4"]);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
|
||||
s.cmdline("F").unwrap();
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array]:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_takes_2_to_32767_items() {
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["0,0", "A"]);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:");
|
||||
// A point from LISP is refused too (AutoCAD 2024 with '(1 2): the same message).
|
||||
for bad in ["1", "0", "2.5", "32768", "-3", "1'", "8/2", "x", "4.0", "1e1", "3\"", "(list 1 2)"] {
|
||||
let logged = s.log.len();
|
||||
s.cmdline(bad).unwrap();
|
||||
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
|
||||
assert_eq!(said, ["Requires an integer between 2 and 32767."], "{bad}");
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:", "{bad}");
|
||||
}
|
||||
s.cmdline("32767").unwrap();
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
|
||||
// A sign or a leading zero is still a whole number, and so is the LISP real 3.0 (AutoCAD 2024:
|
||||
// three items each).
|
||||
for three in ["+3", "03", "(+ 1.5 1.5)"] {
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["0,0", "A", three, "5,0"]);
|
||||
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)], "{three}");
|
||||
}
|
||||
// Enter at the number ends COPY with nothing copied.
|
||||
let mut s = with_line(1);
|
||||
copy(&mut s, &["0,0", "A", ""]);
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(starts(&s), [(0.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maxarray_doesnt_limit_the_items() {
|
||||
// AutoCAD 2024 with MAXARRAY 100000: four lines and 26000 items made 104000 lines (measured).
|
||||
// Here MAXARRAY is 100 (its least): two lines and 60 items, and 101 lines and 2 items, go past
|
||||
// it and are still made.
|
||||
let mut s = with_line(1);
|
||||
s.execute("line", &json!({ "points": [[0, 5], [1, 5]] })).unwrap();
|
||||
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
|
||||
copy(&mut s, &["0,0", "A", "60", "10,0"]);
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(starts(&s).len(), 120);
|
||||
let mut s = with_line(1);
|
||||
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
|
||||
for y in 1..=100 {
|
||||
s.execute("line", &json!({ "points": [[0, y], [1, y]] })).unwrap();
|
||||
}
|
||||
copy(&mut s, &["0,0", "A", "2", "10,0"]);
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(starts(&s).len(), 202);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_copies_stay_within_ten_million() {
|
||||
// Not AutoCAD's limit, ARRAY's: 400 lines times 25000 more items is exactly 10 million copies
|
||||
// and is taken; one item more is refused before anything is made.
|
||||
let mut s = with_line(1);
|
||||
for y in 1..400 {
|
||||
s.execute("line", &json!({ "points": [[0, y], [1, y]] })).unwrap();
|
||||
}
|
||||
copy(&mut s, &["0,0", "A", "25002"]);
|
||||
assert_eq!(
|
||||
s.log.last().map(String::as_str),
|
||||
Some("The array would create 10000400 objects; the limit is 10000000. Use fewer items or select fewer objects.")
|
||||
);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:");
|
||||
assert_eq!(starts(&s).len(), 400);
|
||||
s.cmdline("25001").unwrap();
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copymode_is_a_profile_variable() {
|
||||
// OPTIONS reports it, a saved profile brings it back, reset puts it back to 0, and typing its
|
||||
// name asks for it as for any variable.
|
||||
let mut s = with_line(1);
|
||||
assert_eq!(s.execute("options", &json!({})).unwrap()["COPYMODE"], json!(1));
|
||||
let saved = cadcraft_engine::cmd::options::profile(&s);
|
||||
let mut t = Session::new();
|
||||
cadcraft_engine::cmd::options::restore(&mut t, &saved);
|
||||
assert_eq!(copymode(&mut t), json!(1));
|
||||
s.execute("options", &json!({ "reset": true })).unwrap();
|
||||
assert_eq!(copymode(&mut s), json!(0));
|
||||
s.cmdline("COPYMODE").unwrap();
|
||||
s.cmdline("1").unwrap();
|
||||
assert_eq!(copymode(&mut s), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copymode_takes_0_or_1() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(copymode(&mut s), json!(0));
|
||||
for bad in [json!(2), json!(-1), json!("x")] {
|
||||
assert!(s.execute("setvar", &json!({ "name": "COPYMODE", "value": bad })).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(copymode(&mut s), json!(0));
|
||||
}
|
||||
@@ -129,3 +129,105 @@ fn insert_options_match_autocad() {
|
||||
s.cmdline("(command \"_.-INSERT\" \"B7\" \"_B\" '(612350.678 2398770.432) '(612365.678 2398775.432) 1 \"\" 0)").unwrap();
|
||||
assert_eq!(last_insert(&s), (115.0, 55.0, 1.0, 1.0, 1.0, 0.0));
|
||||
}
|
||||
|
||||
/// A session with block B1, a line from (0, 0) to (10, 0) based at the origin.
|
||||
fn with_b1() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("block", &json!({ "name": "B1", "base": [0, 0], "keep": "delete", "handles": ["100"] })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Points at the scale and rotation prompts, as AutoCAD 2024 takes them (accoreconsole, unitless;
|
||||
/// INSERT measured at Scale, Rotate and XYZ's Z, MINSERT at every one): at the Scale, X, Y, Z and
|
||||
/// Rotate presets a point is the first of two, "Specify second point:" gives their distance or
|
||||
/// direction, and Enter there keeps the default; at XYZ's Z a point gives its distance from the
|
||||
/// insertion point.
|
||||
#[test]
|
||||
fn points_at_the_scale_and_rotation_prompts() {
|
||||
let cases = [
|
||||
("\"_S\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 5.0, 5.0, 5.0, 0.0)),
|
||||
("\"_X\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 5.0, 1.0, 1.0, 0.0)),
|
||||
("\"_Z\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 5.0, 0.0)),
|
||||
("\"_R\" '(3.0 4.0) '(3.0 8.0) '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 90.0)),
|
||||
// Enter at the second point keeps the preset's default.
|
||||
("\"_S\" '(3.0 4.0) \"\" '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
|
||||
("\"_X\" '(3.0 4.0) \"\" '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
|
||||
("\"_R\" '(3.0 4.0) \"\" '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
|
||||
// <<45 typed at the Rotate preset is still the angle 45, not an override for a point.
|
||||
("\"_R\" \"<<45\" '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 45.0)),
|
||||
// The same point twice is no turn.
|
||||
("\"_R\" '(3.0 4.0) '(3.0 4.0) '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
|
||||
];
|
||||
for (args, want) in cases {
|
||||
let mut s = with_b1();
|
||||
s.cmdline(&format!("(command \"_.-INSERT\" \"B1\" {args})")).unwrap();
|
||||
assert!(s.running.is_none(), "{args}: {}", s.prompt_text());
|
||||
assert_eq!(last_insert(&s), want, "{args}");
|
||||
}
|
||||
// Typed at the command line too: the prompt asks for the second point.
|
||||
let mut s = with_b1();
|
||||
s.cmdline("-insert B1 s 3,4").unwrap();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify second point:"));
|
||||
s.cmdline("6,8 10,0 0").unwrap();
|
||||
assert_eq!(last_insert(&s), (10.0, 0.0, 5.0, 5.0, 5.0, 0.0));
|
||||
// XYZ's Z: (3, 4) is √65 from the insertion point (10, 0).
|
||||
let mut s = with_b1();
|
||||
s.cmdline("(command \"_.-INSERT\" \"B1\" '(10.0 0.0) \"_XYZ\" 2 3 '(3.0 4.0) 0)").unwrap();
|
||||
let (.., z, _) = last_insert(&s);
|
||||
assert!((z - 65f64.sqrt()).abs() < 1e-9, "{z}");
|
||||
}
|
||||
|
||||
/// What the scale and rotation prompts refuse, with AutoCAD 2024's messages (accoreconsole,
|
||||
/// measured), and the prompt asked again ("" for the same one): a refusal at "Specify second point:"
|
||||
/// asks the first one.
|
||||
#[test]
|
||||
fn what_the_scale_and_rotation_prompts_refuse() {
|
||||
const TWO: &str = "Requires numeric distance or two points.";
|
||||
const NONZERO: &str = "Value must be nonzero.";
|
||||
const NUMERIC: &str = "Requires numeric value.";
|
||||
const SCALE: &str = "Specify scale factor for XYZ axes <1>:";
|
||||
const Y: &str = "Enter Y scale factor <use X scale factor>:";
|
||||
const Z: &str = "Specify Z scale factor or <use X scale factor>:";
|
||||
let cases = [
|
||||
("-insert B1 s", "x", TWO, SCALE),
|
||||
("-insert B1 s", "0", NONZERO, SCALE),
|
||||
("-insert B1 s 3,4", "5", TWO, SCALE),
|
||||
("-insert B1 s 3,4", "3,4", NONZERO, SCALE),
|
||||
("-insert B1 x", "x", TWO, "Specify X scale factor <1>:"),
|
||||
("-insert B1 x", "0", NONZERO, "Specify X scale factor <1>:"),
|
||||
("-insert B1 x 3,4", "5", TWO, "Specify X scale factor <1>:"),
|
||||
("-insert B1 x 3,4", "3,4", NONZERO, "Specify X scale factor <1>:"),
|
||||
("-insert B1 r", "x", "Requires valid numeric angle or two points.", "Specify rotation angle <0>:"),
|
||||
// A point from LISP: typed text at this prompt is read as an angle, as before.
|
||||
("-insert B1 r|(list 3 4)", "5", "Requires valid numeric angle or two points.", "Specify rotation angle <0>:"),
|
||||
("-insert B1 10,0", "0", NONZERO, ""),
|
||||
("-insert B1 10,0 2", "(list 3 4)", NUMERIC, Y),
|
||||
("-insert B1 10,0 2", "x", NUMERIC, Y),
|
||||
("-insert B1 10,0 2", "0", NONZERO, Y),
|
||||
("-insert B1 10,0 xyz 2 3", "x", "Requires numeric distance or second point.", Z),
|
||||
("-insert B1 10,0 xyz 2 3", "0", NONZERO, Z),
|
||||
// XYZ's Z at the insertion point itself: no distance.
|
||||
("-insert B1 10,0 xyz 2 3", "10,0", NONZERO, Z),
|
||||
// Exploded, after the insertion point, the scale is a positive number only.
|
||||
("-insert *B1 10,0", "(list 3 4)", NUMERIC, ""),
|
||||
("-insert *B1 10,0", "x", NUMERIC, ""),
|
||||
("-insert *B1 10,0", "0", "Value must be positive and nonzero.", ""),
|
||||
("-insert *B1 10,0", "-2", "Value must be positive and nonzero.", ""),
|
||||
];
|
||||
for (typed, bad, message, again) in cases {
|
||||
let mut s = with_b1();
|
||||
// Separate inputs are split at `|`.
|
||||
for t in typed.split('|') {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
let before = s.current_prompt().map(|p| p.display());
|
||||
let logged = s.log.len();
|
||||
s.cmdline(bad).unwrap();
|
||||
let said: Vec<&str> =
|
||||
s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires") || l.starts_with("Value must")).collect();
|
||||
assert_eq!(said, [message], "{typed} then {bad}");
|
||||
let again = if again.is_empty() { before.clone() } else { Some(again.to_string()) };
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()), again, "{typed} then {bad}");
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ mod annotate_options;
|
||||
mod annotative;
|
||||
mod arc_ctrl_direction;
|
||||
mod array_commands;
|
||||
mod array_counts;
|
||||
mod array_key_point;
|
||||
mod array_live;
|
||||
mod assoc_array;
|
||||
@@ -34,6 +35,7 @@ mod compare_export;
|
||||
mod constraint_geometry;
|
||||
mod constraint_infer;
|
||||
mod copy_count;
|
||||
mod copy_modes;
|
||||
mod count;
|
||||
mod dash_block;
|
||||
mod dash_units;
|
||||
@@ -85,6 +87,7 @@ mod insert_enter;
|
||||
mod insert_prompts;
|
||||
mod isometric;
|
||||
mod join_close;
|
||||
mod join_on_source;
|
||||
mod json_param_validation;
|
||||
mod kept_dimension_snaps;
|
||||
mod layer_cmdline;
|
||||
@@ -123,6 +126,7 @@ mod oops_command;
|
||||
mod options_profile;
|
||||
mod overkill;
|
||||
mod parallel_display_list;
|
||||
mod pedit_heights;
|
||||
mod pedit_multiple;
|
||||
mod pedit_splinedit;
|
||||
mod pick_text;
|
||||
@@ -144,6 +148,7 @@ mod purge_mlinestyles;
|
||||
mod purge_prompts;
|
||||
mod qdim;
|
||||
mod qdim_modes;
|
||||
mod qleader;
|
||||
mod query_entities;
|
||||
mod quickcalc;
|
||||
mod recent_commands;
|
||||
|
||||
@@ -117,6 +117,73 @@ fn the_prompts_follow_autocad_2024() {
|
||||
assert_eq!(grid(&i), (3, 2, 20.0, 15.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_column_spacing_takes_two_points() {
|
||||
// AutoCAD 2024 at "Specify distance between columns (|||):": a point asks "Specify second
|
||||
// point:", and the two points' distance is the spacing, 0 included; x and Enter there, and
|
||||
// Enter or 5 at the second point, get "Requires numeric distance or two points." (measured).
|
||||
let to_spacing = |s: &mut Session| {
|
||||
let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap());
|
||||
s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap();
|
||||
for input in ["minsert", "B", "10,0", "1", "", "0", "2", "2", "10"] {
|
||||
s.cmdline(input).unwrap();
|
||||
}
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify distance between columns (|||):"));
|
||||
};
|
||||
for (second, spacing) in [("6,8", 5.0), ("3,4", 0.0)] {
|
||||
let mut s = Session::new();
|
||||
to_spacing(&mut s);
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify second point:"));
|
||||
s.cmdline(second).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let [i] = inserts(&s).try_into().unwrap();
|
||||
assert_eq!(grid(&i), (2, 2, spacing, 10.0), "{second}");
|
||||
}
|
||||
for bad in [&["x"][..], &[""], &["3,4", ""], &["3,4", "5"]] {
|
||||
let mut s = Session::new();
|
||||
to_spacing(&mut s);
|
||||
let logged = s.log.len();
|
||||
for input in bad {
|
||||
s.cmdline(input).unwrap();
|
||||
}
|
||||
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
|
||||
assert_eq!(said, ["Requires numeric distance or two points."], "{bad:?}");
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify distance between columns (|||):"), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_take_a_whole_number_as_typed() {
|
||||
// AutoCAD 2024 at "Enter number of rows (---)": +3 and 03 are three rows; 5.0, 5., 1e1, 8/2,
|
||||
// 3', 4.5, 0 and a point from LISP are refused and asked again (measured; at the columns 5.0
|
||||
// and +3 too).
|
||||
let mut s = Session::new();
|
||||
let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap());
|
||||
s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap();
|
||||
for input in ["minsert", "B", "0,0", "1", "", "0"] {
|
||||
s.cmdline(input).unwrap();
|
||||
}
|
||||
for row_or_column in ["+3", "03"] {
|
||||
let asked = s.prompt_text();
|
||||
for bad in ["5.0", "5.", "1e1", "8/2", "3'", "4.5", "0", "(list 1 2)"] {
|
||||
let logged = s.log.len();
|
||||
s.cmdline(bad).unwrap();
|
||||
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
|
||||
assert_eq!(said, ["Requires an integer between 1 and 32767."], "{bad}");
|
||||
assert_eq!(s.prompt_text(), asked, "{bad}");
|
||||
}
|
||||
s.cmdline(row_or_column).unwrap();
|
||||
}
|
||||
for input in ["10", "20"] {
|
||||
s.cmdline(input).unwrap();
|
||||
}
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let [i] = inserts(&s).try_into().unwrap();
|
||||
// (columns, rows, column spacing, row spacing)
|
||||
assert_eq!(grid(&i), (3, 3, 20.0, 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_run_from_1_to_32767() {
|
||||
// AutoCAD 2024: "Requires an integer between 1 and 32767."
|
||||
@@ -205,14 +272,31 @@ fn the_json_form_makes_the_same_grid() {
|
||||
json!({"name": "B", "at": [0, 0], "rows": 0}),
|
||||
json!({"name": "B", "at": [0, 0], "columns": 32768}),
|
||||
json!({"name": "B", "at": [0, 0], "rows": 2.5}),
|
||||
// A whole number written as a float is refused, as by the array commands' JSON forms.
|
||||
json!({"name": "B", "at": [0, 0], "rows": 2.0}),
|
||||
json!({"name": "B", "at": [0, 0], "columns": 1e2}),
|
||||
json!({"name": "B", "at": [0, 0], "rows": "2"}),
|
||||
json!({"name": "B", "at": [0, 0], "rows": -2}),
|
||||
// A distance that is not a number is refused, not taken as 0.
|
||||
json!({"name": "B", "at": [0, 0], "rows": 2, "rowSpacing": "15"}),
|
||||
json!({"name": "B", "at": [0, 0], "columns": 2, "columnSpacing": true}),
|
||||
] {
|
||||
assert!(s.execute("minsert", &bad).is_err(), "{bad}");
|
||||
}
|
||||
// A whole number written as 2.0 is a count; `explode` is INSERT's and leaves the grid made.
|
||||
let r = s.execute("minsert", &json!({"name": "B", "at": [0, 200], "rows": 2.0, "rowSpacing": 15, "explode": true})).unwrap();
|
||||
// Nothing was made by the refused calls.
|
||||
assert_eq!(inserts(&s).len(), 2);
|
||||
// `explode` is INSERT's and leaves the grid made; 32767 is the largest count.
|
||||
let r = s.execute("minsert", &json!({"name": "B", "at": [0, 200], "rows": 2, "rowSpacing": 15, "explode": true})).unwrap();
|
||||
assert!(r["handle"].is_string(), "{r}");
|
||||
assert_eq!(inserts(&s).last().map(grid), Some((1, 2, 0.0, 15.0)));
|
||||
// A null count is 1 and a null distance 0, as missing ones are: each count on its own, then
|
||||
// both distances with two rows and two columns (one row or column keeps no distance anyway).
|
||||
s.execute("minsert", &json!({"name": "B", "at": [0, 250], "rows": null, "columns": 2, "columnSpacing": 20})).unwrap();
|
||||
assert_eq!(inserts(&s).last().map(grid), Some((2, 1, 20.0, 0.0)));
|
||||
s.execute("minsert", &json!({"name": "B", "at": [0, 270], "rows": 2, "columns": null, "rowSpacing": 15})).unwrap();
|
||||
assert_eq!(inserts(&s).last().map(grid), Some((1, 2, 0.0, 15.0)));
|
||||
s.execute("minsert", &json!({"name": "B", "at": [0, 290], "rows": 2, "columns": 2, "rowSpacing": null, "columnSpacing": null})).unwrap();
|
||||
assert_eq!(inserts(&s).last().map(grid), Some((2, 2, 0.0, 0.0)));
|
||||
s.execute("minsert", &json!({"name": "B", "at": [0, 300], "columns": 32767, "columnSpacing": 1})).unwrap();
|
||||
assert_eq!(inserts(&s).last().map(grid), Some((32767, 1, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! PEDIT on lines, arcs and polylines away from Z 0, as AutoCAD 2024 runs it (accoreconsole,
|
||||
//! `entget` of the polyline made, on self-built drawings). A mirrored object here is one whose
|
||||
//! normal is 0,0,-1, kept in world coordinates as the DXF reader keeps it.
|
||||
|
||||
use cadcraft_doc::{Entity, EntityKind, Handle, LwPolyline};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn entity(s: &Session, h: Handle) -> Entity {
|
||||
(**s.doc().unwrap().entity(h).unwrap()).clone()
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, h: Handle, f: impl FnOnce(&mut Entity)) {
|
||||
s.doc_mut().unwrap().modify_entity(h, f).unwrap();
|
||||
}
|
||||
|
||||
/// A line from `a` to `b`.
|
||||
fn line(s: &mut Session, a: [f64; 3], b: [f64; 3]) -> Handle {
|
||||
let h = handle(&s.execute("line", &json!({ "points": [[a[0], a[1]], [b[0], b[1]]] })).unwrap());
|
||||
edit(s, h, |e| {
|
||||
if let EntityKind::Line(l) = &mut e.kind {
|
||||
(l.a.z, l.b.z) = (a[2], b[2]);
|
||||
}
|
||||
});
|
||||
h
|
||||
}
|
||||
|
||||
/// An arc round `c` (world) from `a1` to `a2` degrees, counterclockwise in plan.
|
||||
fn arc(s: &mut Session, c: [f64; 3], r: f64, a1: f64, a2: f64) -> Handle {
|
||||
let h = handle(&s.execute("arc", &json!({ "center": [c[0], c[1]], "radius": r, "start": a1, "end": a2 })).unwrap());
|
||||
edit(s, h, |e| {
|
||||
if let EntityKind::Arc(a) = &mut e.kind {
|
||||
a.center.z = c[2];
|
||||
}
|
||||
});
|
||||
h
|
||||
}
|
||||
|
||||
/// An open polyline through `points` at `elevation`.
|
||||
fn pline(s: &mut Session, points: Value, elevation: f64) -> Handle {
|
||||
let h = handle(&s.execute("pline", &json!({ "points": points })).unwrap());
|
||||
edit(s, h, |e| {
|
||||
if let EntityKind::LwPolyline(p) = &mut e.kind {
|
||||
p.elevation = elevation;
|
||||
}
|
||||
});
|
||||
h
|
||||
}
|
||||
|
||||
fn face_down(s: &mut Session, h: Handle) {
|
||||
edit(s, h, |e| e.common.extrusion = Vec3::new(0.0, 0.0, -1.0));
|
||||
}
|
||||
|
||||
fn polyline(e: &Entity) -> LwPolyline {
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline: {e:?}") };
|
||||
p.clone()
|
||||
}
|
||||
|
||||
/// PEDIT's JSON form with nothing to change, which only turns a line or an arc into a polyline.
|
||||
fn convert(s: &mut Session, h: Handle) -> Entity {
|
||||
s.execute("pedit", &json!({ "handle": h.hex(), "option": "ltypegen", "on": false })).unwrap();
|
||||
entity(s, h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_or_an_arc_becomes_a_polyline_at_its_height() {
|
||||
// AutoCAD 2024: a line at Z 5 and an arc whose centre is at Z 5 give elevation 5 facing up;
|
||||
// a thickness of 2 stays, a line's and an arc's; a line facing down still gives a polyline
|
||||
// facing up.
|
||||
let mut s = Session::new();
|
||||
let l = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
edit(&mut s, l, |e| e.common.thickness = 2.0);
|
||||
let e = convert(&mut s, l);
|
||||
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
|
||||
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
|
||||
edit(&mut s, a, |e| e.common.thickness = 2.0);
|
||||
let e = convert(&mut s, a);
|
||||
let p = polyline(&e);
|
||||
assert_eq!((p.elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
|
||||
assert!((p.vertices[0].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
|
||||
// Below Z 0 too (AutoCAD 2024: 38 = -5 for the arc's centre at Z -5).
|
||||
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
|
||||
let e = convert(&mut s, a);
|
||||
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::Z));
|
||||
let l = line(&mut s, [0.0, 20.0, 5.0], [10.0, 20.0, 5.0]);
|
||||
face_down(&mut s, l);
|
||||
let e = convert(&mut s, l);
|
||||
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
|
||||
// A mirrored arc keeps its normal (AutoCAD 2024: 210 0,0,-1, elevation 5 for the arc at world
|
||||
// Z -5) and runs as it does in its own coordinates: from world (15,5) to (10,0), bulge
|
||||
// -0.414214 in plan (0.414214 in its own coordinates).
|
||||
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
|
||||
face_down(&mut s, a);
|
||||
let e = convert(&mut s, a);
|
||||
let p = polyline(&e);
|
||||
assert_eq!((p.elevation, e.common.extrusion), (5.0, Vec3::new(0.0, 0.0, -1.0)));
|
||||
let v: Vec<(f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect();
|
||||
assert!((v[0].0 - 15.0).abs() < 1e-9 && (v[0].1 - 5.0).abs() < 1e-9 && (v[1].0 - 10.0).abs() < 1e-9 && v[1].1.abs() < 1e-9, "{v:?}");
|
||||
assert!((p.vertices[0].bulge + std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
|
||||
// The elevation runs along the normal the other way too: a mirrored arc at world Z 5 gives -5,
|
||||
// and one 2 thick at world Z -5 keeps the thickness (AutoCAD 2024: 38 = -5; 38 = 5, 39 = 2).
|
||||
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
|
||||
face_down(&mut s, a);
|
||||
let e = convert(&mut s, a);
|
||||
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::new(0.0, 0.0, -1.0)));
|
||||
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
|
||||
face_down(&mut s, a);
|
||||
edit(&mut s, a, |e| e.common.thickness = 2.0);
|
||||
let e = convert(&mut s, a);
|
||||
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::new(0.0, 0.0, -1.0), 2.0));
|
||||
// A sloped line still comes out at elevation 0, facing up: AutoCAD 2024 makes a polyline in the
|
||||
// line's vertical plane (normal 0,1,0), which a CADCraft polyline can't be.
|
||||
let l = line(&mut s, [0.0, 40.0, 0.0], [10.0, 40.0, 5.0]);
|
||||
let e = convert(&mut s, l);
|
||||
assert_eq!((polyline(&e).elevation, e.common.extrusion), (0.0, Vec3::Z));
|
||||
// A refused option leaves a line as it was, its normal included.
|
||||
let l = line(&mut s, [0.0, 60.0, 5.0], [10.0, 60.0, 5.0]);
|
||||
face_down(&mut s, l);
|
||||
let before = entity(&s, l);
|
||||
let r = s.execute("pedit", &json!({ "handle": l.hex(), "option": "vertex", "index": 0, "action": "break" }));
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert_eq!(entity(&s, l), before);
|
||||
}
|
||||
|
||||
/// PEDIT Join from the first object onto the second; whether the second was taken.
|
||||
fn joins(s: &mut Session, first: Handle, second: Handle) -> bool {
|
||||
let r = s.execute("pedit", &json!({ "handle": first.hex(), "option": "join", "join": [second.hex()] })).unwrap();
|
||||
let taken = r["joined"] == json!(1);
|
||||
assert_eq!(taken, s.doc().unwrap().entity(second).is_none(), "{r}");
|
||||
taken
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_takes_only_objects_at_the_polylines_height_facing_its_way() {
|
||||
// AutoCAD 2024, from a line at Z 5 ending at (10,0): "1 segments added to polyline" or "0".
|
||||
let next: [(&str, bool, fn(&mut Session) -> Handle); 6] = [
|
||||
("a line at Z 5", true, |s| line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0])),
|
||||
("a line at Z 0", false, |s| line(s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0])),
|
||||
("an arc at Z 5", true, |s| arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0)),
|
||||
("an arc at Z 0", false, |s| arc(s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0)),
|
||||
("a mirrored line at Z 5", true, |s| {
|
||||
let h = line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0]);
|
||||
face_down(s, h);
|
||||
h
|
||||
}),
|
||||
("a mirrored arc at Z 5", false, |s| {
|
||||
let h = arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
|
||||
face_down(s, h);
|
||||
h
|
||||
}),
|
||||
];
|
||||
for (what, want, make) in next {
|
||||
let mut s = Session::new();
|
||||
let base = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
let other = make(&mut s);
|
||||
assert_eq!(joins(&mut s, base, other), want, "{what}");
|
||||
let p = polyline(&entity(&s, base));
|
||||
assert_eq!((p.elevation, p.vertices.len()), (5.0, if want { 3 } else { 2 }), "{what}");
|
||||
if want && what.contains("arc") {
|
||||
// AutoCAD 2024: bulge 0.414214 on the arc's segment.
|
||||
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
|
||||
}
|
||||
}
|
||||
// From a mirrored polyline at elevation 5 (world Z -5, from (0,0) to (10,0)): no line at its
|
||||
// world height, but a mirrored arc there and another mirrored polyline at elevation 5; and a
|
||||
// polyline at elevation 5 takes no polyline at 0.
|
||||
let mirrored: [(&str, bool, fn(&mut Session) -> Handle); 3] = [
|
||||
("a line at Z -5", false, |s| line(s, [10.0, 0.0, -5.0], [10.0, 5.0, -5.0])),
|
||||
("a mirrored arc at Z -5", true, |s| {
|
||||
let h = arc(s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
|
||||
face_down(s, h);
|
||||
h
|
||||
}),
|
||||
("a mirrored polyline at elevation 5", true, |s| {
|
||||
let h = pline(s, json!([[10, 0], [10, 5]]), 5.0);
|
||||
face_down(s, h);
|
||||
h
|
||||
}),
|
||||
];
|
||||
for (what, want, make) in mirrored {
|
||||
let mut s = Session::new();
|
||||
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
|
||||
face_down(&mut s, base);
|
||||
let other = make(&mut s);
|
||||
assert_eq!(joins(&mut s, base, other), want, "{what}");
|
||||
// AutoCAD 2024: the polyline keeps elevation 5 and normal 0,0,-1; the arc's segment has
|
||||
// bulge -0.414214 in the polyline's own coordinates, 0.414214 seen from above.
|
||||
let e = entity(&s, base);
|
||||
let p = polyline(&e);
|
||||
assert_eq!((p.elevation, e.common.extrusion, p.vertices.len()), (5.0, Vec3::new(0.0, 0.0, -1.0), if want { 3 } else { 2 }), "{what}");
|
||||
if want && what.contains("arc") {
|
||||
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
|
||||
}
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
|
||||
let other = pline(&mut s, json!([[10, 0], [10, 5]]), 0.0);
|
||||
assert!(!joins(&mut s, base, other), "a polyline at elevation 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_join_takes_objects_at_any_height_but_not_facing_the_other_way() {
|
||||
// AutoCAD 2024: PEDIT Multiple, a line at Z 5 and one at Z 0 meeting it in plan, convert and
|
||||
// Join with no fuzz: "1 segments added to polyline", one polyline at elevation 5.
|
||||
let mut s = Session::new();
|
||||
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
|
||||
s.cmdline("pedit m 5,0 10,2.5").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("y j 0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
|
||||
assert_eq!(objects.len(), 1, "{objects:?}");
|
||||
let p = polyline(&objects[0]);
|
||||
assert_eq!((p.elevation, p.vertices.len()), (5.0, 3));
|
||||
// A line at Z 0 to (10,0) and a mirrored arc from there to (15,5), picked in either order:
|
||||
// both become polylines, the arc's facing down, and Join takes neither ("0 segments added").
|
||||
for arc_first in [false, true] {
|
||||
let mut s = Session::new();
|
||||
line(&mut s, [0.0, 0.0, 0.0], [10.0, 0.0, 0.0]);
|
||||
let a = arc(&mut s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0);
|
||||
face_down(&mut s, a);
|
||||
// The arc picked on it, at 315 degrees.
|
||||
s.cmdline(if arc_first { "pedit m 13.5355339,1.4644661 5,0" } else { "pedit m 5,0 13.5355339,1.4644661" }).unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("y j 0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
|
||||
assert_eq!(objects.len(), 2, "arc first {arc_first}: {objects:?}");
|
||||
assert!(objects.iter().all(|e| matches!(e.kind, EntityKind::LwPolyline(_))), "{objects:?}");
|
||||
// AutoCAD 2024: the arc's polyline at elevation 0 with normal 0,0,-1, the line's facing up.
|
||||
let (arcs, lines): (Vec<&Entity>, Vec<&Entity>) = objects.iter().partition(|e| e.common.extrusion.z < 0.0);
|
||||
assert_eq!((arcs.len(), lines.len()), (1, 1), "{objects:?}");
|
||||
let p = polyline(arcs[0]);
|
||||
assert!(p.elevation == 0.0 && p.vertices[0].bulge != 0.0 && lines[0].common.extrusion == Vec3::Z, "{objects:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_continues_from_a_sloped_lines_far_end_height() {
|
||||
// AutoCAD 2024: from a line at Z 5, a sloped line down to Z 0 and a line on at Z 0 both join
|
||||
// ("2 segments added"), at the polyline's end and at its start alike, the sloped line drawn
|
||||
// either way. AutoCAD makes that polyline in the lines' vertical plane; a CADCraft polyline
|
||||
// stays at the source's elevation.
|
||||
for (base, sloped, next) in [
|
||||
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
|
||||
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
|
||||
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[0.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
|
||||
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [0.0, 0.0, 0.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
let h = line(&mut s, base[0], base[1]);
|
||||
let a = line(&mut s, sloped[0], sloped[1]);
|
||||
let b = line(&mut s, next[0], next[1]);
|
||||
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
|
||||
assert_eq!(r["joined"], json!(2), "{base:?}: {r}");
|
||||
assert_eq!(polyline(&entity(&s, h)).vertices.len(), 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chain_closes_only_at_one_height() {
|
||||
// AutoCAD 2024: three sides of a triangle at Z 5 join into a closed polyline; with its last
|
||||
// side at Z 0, that side stays a line and the polyline stays open ("1 segments added").
|
||||
for (last_z, joined, closed) in [(5.0, 2, true), (0.0, 1, false)] {
|
||||
let mut s = Session::new();
|
||||
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
let a = line(&mut s, [10.0, 0.0, 5.0], [10.0, 10.0, 5.0]);
|
||||
let b = line(&mut s, [10.0, 10.0, last_z], [0.0, 0.0, last_z]);
|
||||
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
|
||||
assert_eq!(r["joined"], json!(joined), "last side at {last_z}: {r}");
|
||||
assert_eq!(polyline(&entity(&s, h)).closed, closed, "last side at {last_z}");
|
||||
}
|
||||
// A line at Z 5 and a sloped line back over it to Z 0: the ends meet in plan at Z 5 and at Z 0,
|
||||
// and the polyline stays open (AutoCAD 2024: "1 segments added", 70 = 0).
|
||||
let mut s = Session::new();
|
||||
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
let back = line(&mut s, [10.0, 0.0, 5.0], [0.0, 0.0, 0.0]);
|
||||
assert!(joins(&mut s, h, back));
|
||||
let p = polyline(&entity(&s, h));
|
||||
assert_eq!((p.vertices.len(), p.closed), (3, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_takes_a_sloped_line_only_in_one_plane_with_the_polyline_and_every_line_picked() {
|
||||
// AutoCAD 2024 joins only objects in one plane with the polyline: the plane the polyline and
|
||||
// every line picked share, when they share one, else the polyline's own, flat, where no sloped
|
||||
// line lies. From a line at Z 5, (0,0) to (10,0):
|
||||
let cases: [(&str, &[[[f64; 3]; 2]], usize); 4] = [
|
||||
// a sloped line at right angles in plan, a tilted plane: "1 segments added";
|
||||
("at an angle", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 0.0]]], 1),
|
||||
// a triangle at Z 5 whose last side slopes from (10,10,5) to (0,0,0): that side stays a line;
|
||||
("a triangle's sloped side", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [0.0, 0.0, 0.0]]], 1),
|
||||
// a corner at Z 5, then a sloped line on in plan: the sloped line stays a line;
|
||||
("after a corner", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [10.0, 20.0, 0.0]]], 1),
|
||||
// a sloped line on in plan, then a line at Z 0 from its foot turning off their vertical
|
||||
// plane: the three share no plane, and neither joins ("0 segments added").
|
||||
("then a turn", &[[[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [20.0, 10.0, 0.0]]], 0),
|
||||
];
|
||||
for (what, lines, joined) in cases {
|
||||
let mut s = Session::new();
|
||||
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
let picked: Vec<String> = lines.iter().map(|[a, b]| line(&mut s, *a, *b).hex()).collect();
|
||||
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": picked })).unwrap();
|
||||
assert_eq!(r["joined"], json!(joined), "{what}: {r}");
|
||||
let left = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
assert_eq!(left, lines.len() - joined, "{what}");
|
||||
}
|
||||
// A sloped line on in plan, then an arc at Z 0 from its foot: the line joins, the arc, which
|
||||
// lies flat, doesn't ("1 segments added").
|
||||
let mut s = Session::new();
|
||||
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
let l = line(&mut s, [10.0, 0.0, 5.0], [20.0, 0.0, 0.0]);
|
||||
let a = arc(&mut s, [20.0, 5.0, 0.0], 5.0, 270.0, 0.0);
|
||||
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [l.hex(), a.hex()] })).unwrap();
|
||||
assert_eq!(r["joined"], json!(1), "{r}");
|
||||
assert!(s.doc().unwrap().entity(l).is_none() && s.doc().unwrap().entity(a).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_meets_within_the_fuzz_in_plan_and_1e_6_in_height() {
|
||||
// The JSON form's fuzz bridges a gap in plan only: a line 0.3 off the end joins with fuzz 0.5
|
||||
// at the polyline's height, to within 1e-6, and not 0.001 above it.
|
||||
for (z, want) in [(5.0, true), (5.0 + 1e-9, true), (5.001, false)] {
|
||||
let mut s = Session::new();
|
||||
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
let o = line(&mut s, [10.3, 0.0, z], [10.3, 5.0, z]);
|
||||
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [o.hex()], "fuzz": 0.5 })).unwrap();
|
||||
assert_eq!(r["joined"] == json!(1), want, "Z {z}: {r}");
|
||||
}
|
||||
// Multiple's Join takes the line 0.001 above too, as it takes one at any height.
|
||||
let mut s = Session::new();
|
||||
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
line(&mut s, [10.3, 0.0, 5.001], [10.3, 5.0, 5.001]);
|
||||
s.cmdline("pedit m 5,0 10.3,2.5").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("y j 0.5").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(s.doc().unwrap().model.iter().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_line_converts_and_joins_the_same_way() {
|
||||
// PEDIT typed: a mirrored line at Z 5 becomes a polyline at elevation 5 facing up, and Join
|
||||
// leaves a line at Z 0 off it ("0 segments added to polyline").
|
||||
let mut s = Session::new();
|
||||
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
|
||||
face_down(&mut s, h);
|
||||
let other = line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
|
||||
s.cmdline("pedit 5,0 y").unwrap();
|
||||
let e = entity(&s, h);
|
||||
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
|
||||
let n = s.log.len();
|
||||
s.cmdline("j 10,2.5").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.log[n..].iter().any(|l| l.contains("0 segments added to polyline")), "{:?}", &s.log[n..]);
|
||||
assert!(s.doc().unwrap().entity(other).is_some());
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
}
|
||||
@@ -151,6 +151,19 @@ fn fit_spline(s: &mut Session) -> String {
|
||||
h(&s.execute("spline", &json!({ "fit": [[0, 0], [2, 2], [4, 0], [6, 2]] })).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_gives_a_closed_fit_its_own_tangent() {
|
||||
// SPLINEDIT Close refits the fit points closed: the open ends' tangents don't carry over, the
|
||||
// closed curve takes its own where it closes, as SPLINE ... Close builds it.
|
||||
let mut s = Session::new();
|
||||
let fit = json!([[0, 0], [4, 0], [6, 3], [1, 4]]);
|
||||
let sp = h(&s.execute("spline", &json!({ "fit": fit, "startTangent": [0, 1] })).unwrap());
|
||||
s.execute("splinedit", &json!({ "handle": sp, "option": "close" })).unwrap();
|
||||
let closed = spline(&s, &sp);
|
||||
let own = h(&s.execute("spline", &json!({ "fit": fit, "closed": true })).unwrap());
|
||||
assert_eq!(closed, spline(&s, &own));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_data_options_at_the_command_line() {
|
||||
let mut s = Session::new();
|
||||
@@ -281,9 +294,10 @@ fn control_edits_drop_fit_data_and_keep_closed_splines_closed() {
|
||||
let x = spline(&s, &sp);
|
||||
assert!(x.fit.is_empty() && x.control[1] == Vec2::new(1.0, 5.0));
|
||||
|
||||
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true })).unwrap());
|
||||
// Control points that wrap round (uniform knots): the first `degree` repeat at the end.
|
||||
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true, "knots": "uniform" })).unwrap());
|
||||
let before = spline(&s, &c);
|
||||
assert!(before.is_periodic());
|
||||
assert!(before.wraps() && before.is_periodic());
|
||||
let u = before.control.len() - before.degree;
|
||||
s.execute("splinedit", &json!({ "handle": c, "option": "vertexmove", "index": 0, "to": [-1, -1] })).unwrap();
|
||||
let x = spline(&s, &c);
|
||||
@@ -297,6 +311,23 @@ fn control_edits_drop_fit_data_and_keep_closed_splines_closed() {
|
||||
let (lo, hi) = x.domain();
|
||||
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed");
|
||||
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 99 })).is_err());
|
||||
|
||||
// Clamped (chord-length knots, as AutoCAD 2024 builds a closed fit spline): only the first
|
||||
// control point repeats, at the end. Moving it leaves a corner where the curve closes.
|
||||
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true })).unwrap());
|
||||
let before = spline(&s, &c);
|
||||
assert!(before.is_periodic() && !before.wraps());
|
||||
let last = before.control.len() - 1;
|
||||
s.execute("splinedit", &json!({ "handle": c, "option": "vertexmove", "index": 0, "to": [-1, -1] })).unwrap();
|
||||
let x = spline(&s, &c);
|
||||
assert_eq!((x.control[0], x.control[last]), (Vec2::new(-1.0, -1.0), Vec2::new(-1.0, -1.0)), "both ends move");
|
||||
assert!(x.closed && !x.is_periodic(), "a corner where it closes");
|
||||
s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 2 })).unwrap();
|
||||
let x = spline(&s, &c);
|
||||
assert!(x.is_valid() && x.closed && x.control.len() == before.control.len() - 1);
|
||||
let (lo, hi) = x.domain();
|
||||
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed");
|
||||
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 0 })).is_err(), "the start point stays");
|
||||
}
|
||||
|
||||
/// Largest distance from samples of `a` to the curve `b` (a shape comparison).
|
||||
@@ -369,3 +400,108 @@ fn edit_vertex_add_and_elevate_order_keep_the_shape() {
|
||||
}
|
||||
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexadd" })).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elevate_order_takes_a_whole_number_as_typed() {
|
||||
// AutoCAD 2024 at "Enter new order <4>:" on a cubic: +5, 05 and the LISP real 5.0 make it order
|
||||
// 5, and 4 keeps it; 5.0, 5., 1e1, 4.5, 3, 27 and a point from LISP get "Requires an integer
|
||||
// between 4 and 26." and the prompt again. At order 5 the range starts at 5 (measured).
|
||||
let control = json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] });
|
||||
let refused = |s: &mut Session, bad: &str, message: &str| {
|
||||
let asked = s.prompt_text();
|
||||
let logged = s.log.len();
|
||||
s.cmdline(bad).unwrap();
|
||||
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
|
||||
assert_eq!(said, [message], "{bad}");
|
||||
assert_eq!(s.prompt_text(), asked, "{bad}");
|
||||
};
|
||||
for typed in ["+5", "05", "(+ 2.5 2.5)"] {
|
||||
let mut s = Session::new();
|
||||
let sp = h(&s.execute("spline", &control).unwrap());
|
||||
s.cmdline("splinedit 0,0 e e").unwrap();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter new order <4>:"));
|
||||
for bad in ["5.0", "5.", "1e1", "4.5", "3", "27", "(list 1 2)"] {
|
||||
refused(&mut s, bad, "Requires an integer between 4 and 26.");
|
||||
}
|
||||
assert_eq!(spline(&s, &sp).degree, 3);
|
||||
s.cmdline(typed).unwrap();
|
||||
assert_eq!(spline(&s, &sp).degree, 4, "{typed}");
|
||||
assert!(s.prompt_text().contains("vertex editing option"), "{}", s.prompt_text());
|
||||
// Now order 5: 4 is below it, 5 keeps it.
|
||||
s.cmdline("e").unwrap();
|
||||
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter new order <5>:"));
|
||||
refused(&mut s, "4", "Requires an integer between 5 and 26.");
|
||||
s.cmdline("5").unwrap();
|
||||
assert_eq!(spline(&s, &sp).degree, 4, "{typed}");
|
||||
assert!(s.prompt_text().contains("vertex editing option"), "{typed}: {}", s.prompt_text());
|
||||
}
|
||||
// 26 is the highest order (AutoCAD 2024: taken, degree 25).
|
||||
let mut s = Session::new();
|
||||
let sp = h(&s.execute("spline", &control).unwrap());
|
||||
s.cmdline("splinedit 0,0 e e 26").unwrap();
|
||||
assert_eq!(spline(&s, &sp).degree, 25);
|
||||
// 4 keeps a cubic as it is, and so does Enter.
|
||||
for keep in ["4", ""] {
|
||||
let mut s = Session::new();
|
||||
let sp = h(&s.execute("spline", &control).unwrap());
|
||||
let before = spline(&s, &sp);
|
||||
s.cmdline("splinedit 0,0 e e").unwrap();
|
||||
s.cmdline(keep).unwrap();
|
||||
assert!(s.prompt_text().contains("vertex editing option"), "{keep:?}: {}", s.prompt_text());
|
||||
assert_eq!(spline(&s, &sp).control, before.control, "{keep:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_polyline_precision_is_a_whole_number_as_typed() {
|
||||
// AutoCAD 2024 at "Specify a precision <10>:": +5, 05, 0, 99 and the LISP real 5.0 are taken;
|
||||
// 5.0, 5., 4.5, 1e1, 8/2, 100, -1, a point and the real 4.6 from LISP are refused and asked
|
||||
// again (measured).
|
||||
let control = json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] });
|
||||
for (typed, precision) in [("+5", 5), ("05", 5), ("0", 0), ("99", 99), ("", 10), ("(+ 2.5 2.5)", 5)] {
|
||||
// The same spline converted through the JSON form, for the vertices to expect.
|
||||
let mut s = Session::new();
|
||||
let sp = h(&s.execute("spline", &control).unwrap());
|
||||
s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": precision })).unwrap();
|
||||
let EntityKind::LwPolyline(want) = kind(&s, &sp) else { panic!("converted") };
|
||||
|
||||
let mut s = Session::new();
|
||||
let sp = h(&s.execute("spline", &control).unwrap());
|
||||
s.cmdline("splinedit 0,0 p").unwrap();
|
||||
let asked = s.prompt_text();
|
||||
for bad in ["5.0", "5.", "4.5", "1e1", "8/2", "100", "-1", "(list 1 2)", "(+ 2.3 2.3)"] {
|
||||
let logged = s.log.len();
|
||||
s.cmdline(bad).unwrap();
|
||||
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
|
||||
assert_eq!(said, ["Requires an integer between 0 and 99."], "{bad}");
|
||||
assert_eq!(s.prompt_text(), asked, "{bad}");
|
||||
}
|
||||
s.cmdline(typed).unwrap();
|
||||
assert!(s.running.is_none(), "{typed:?}: {}", s.prompt_text());
|
||||
let EntityKind::LwPolyline(got) = kind(&s, &sp) else { panic!("{typed:?} converted") };
|
||||
assert_eq!(pts(&got), pts(&want), "{typed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_json_polyline_precision_is_a_whole_number_from_0_to_99() {
|
||||
let mut s = Session::new();
|
||||
let sp = h(&s.execute("spline", &json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] })).unwrap());
|
||||
for bad in [json!(100), json!(-1), json!(4.5), json!(5.0), json!("5")] {
|
||||
assert!(s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": bad })).is_err(), "{bad}");
|
||||
assert!(matches!(kind(&s, &sp), EntityKind::Spline(_)), "{bad}");
|
||||
}
|
||||
s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": 99 })).unwrap();
|
||||
assert!(matches!(kind(&s, &sp), EntityKind::LwPolyline(_)));
|
||||
// Without a precision, or with null, it is 10, the prompt's default.
|
||||
let [a, b, c] = [json!({ "precision": 10 }), json!({}), json!({ "precision": null })].map(|mut p| {
|
||||
let sp = h(&s.execute("spline", &json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] })).unwrap());
|
||||
p["handle"] = json!(sp);
|
||||
p["option"] = json!("polyline");
|
||||
s.execute("splinedit", &p).unwrap();
|
||||
let EntityKind::LwPolyline(poly) = kind(&s, &sp) else { panic!("converted") };
|
||||
pts(&poly)
|
||||
});
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a, c);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
//! QLEADER at the command line as AutoCAD 2024 runs it with its default settings (accoreconsole,
|
||||
//! `(command "_.QLEADER" ...)` on a metric drawing, then `entget` of the LEADER and the MTEXT):
|
||||
//! up to three points, a text width, lines of text; the text sits DIMGAP past the leader's end
|
||||
//! with the middle of its first line level with it on the right, of its last line on the left.
|
||||
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
/// What QLEADER drew: the leader's vertices, and the text's insertion point, height, width,
|
||||
/// attachment and contents (rounded to 1e-9).
|
||||
type Drawn = (Vec<(f64, f64)>, Option<((f64, f64), f64, f64, u8, String)>);
|
||||
|
||||
fn drawn(s: &Session) -> Drawn {
|
||||
let r = |v: f64| (v * 1e9).round() / 1e9;
|
||||
let d = s.doc().unwrap();
|
||||
let leader = d
|
||||
.model
|
||||
.iter()
|
||||
.find_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.vertices.iter().map(|p| (r(p.x), r(p.y))).collect()) } else { None });
|
||||
let text = d.model.iter().find_map(|e| match &e.kind {
|
||||
EntityKind::MText(m) => Some(((r(m.insert.x), r(m.insert.y)), r(m.height), r(m.width), m.attach, m.contents.clone())),
|
||||
_ => None,
|
||||
});
|
||||
(leader.unwrap_or_default(), text)
|
||||
}
|
||||
|
||||
/// A drawing with the measured scripts' dimension settings: DIMTAD 1, DIMGAP 0.625, DIMASZ 2.5,
|
||||
/// DIMSCALE 1 and DIMTXT 2.5.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [("DIMTAD", 1.0), ("DIMGAP", 0.625), ("DIMASZ", 2.5), ("DIMSCALE", 1.0), ("DIMTXT", 2.5)] {
|
||||
s.execute("setvar", &json!({ "name": name, "value": v })).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Types QLEADER then each of `inputs`, and checks it ended.
|
||||
fn qleader(s: &mut Session, inputs: &[&str]) {
|
||||
s.cmdline("QLEADER").unwrap();
|
||||
for t in inputs {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.running.is_none(), "{inputs:?}: {}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qleader_places_the_text_as_autocad_does() {
|
||||
// (inputs, AutoCAD's leader vertices, text insertion point, width, attachment, contents)
|
||||
type Case<'a> = (&'a [&'a str], &'a [(f64, f64)], (f64, f64), f64, u8, &'a str);
|
||||
let cases: [Case; 8] = [
|
||||
// Three points, the last segment level: no hook line.
|
||||
(&["0,0", "20,15", "40,15", "0", "ABC", ""], &[(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], (40.625, 16.25), 0.0, 1, "ABC"),
|
||||
// Two points: a hook line DIMASZ (2.5) long into the end.
|
||||
(&["0,0", "20,15", "", "0", "ABC", ""], &[(0.0, 0.0), (17.5, 15.0), (20.0, 15.0)], (20.625, 16.25), 0.0, 1, "ABC"),
|
||||
(
|
||||
&["0,0", "20,15", "35,30", "20", "AB", "CD", ""],
|
||||
&[(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)],
|
||||
(35.625, 31.25),
|
||||
20.0,
|
||||
1,
|
||||
"AB\\PCD",
|
||||
),
|
||||
// Running left: the middle of the last line level with the end.
|
||||
(&["0,0", "-20,15", "-40,15", "0", "AB", "CD", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "AB\\PCD"),
|
||||
(&["0,0", "-20,15", "-40,15", "0", "A", "B", "C", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "A\\PB\\PC"),
|
||||
// A short leader running left: the hook line comes from past the start.
|
||||
(&["0.5,0.25", "0.48,0.265", "", "0", "ABC", ""], &[(0.5, 0.25), (2.98, 0.265), (0.48, 0.265)], (-0.145, -0.985), 0.0, 9, "ABC"),
|
||||
// Straight up: it counts as running right.
|
||||
(&["0,0", "0,20", "", "0", "ABC", ""], &[(0.0, 0.0), (-2.5, 20.0), (0.0, 20.0)], (0.625, 21.25), 0.0, 1, "ABC"),
|
||||
// Survey coordinates, running left.
|
||||
(
|
||||
&["612345.678,2398765.432", "612325.678,2398780.432", "612305.678,2398780.432", "0", "ABC", ""],
|
||||
&[(612345.678, 2398765.432), (612325.678, 2398780.432), (612305.678, 2398780.432)],
|
||||
(612305.053, 2398779.182),
|
||||
0.0,
|
||||
9,
|
||||
"ABC",
|
||||
),
|
||||
];
|
||||
for (inputs, leader, at, width, attach, text) in cases {
|
||||
let mut s = session();
|
||||
qleader(&mut s, inputs);
|
||||
assert_eq!(drawn(&s), (leader.to_vec(), Some((at, 2.5, width, attach, text.to_string()))), "{inputs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qleader_scales_with_dimscale_and_ignores_dimtad() {
|
||||
// DIMGAP 2 and DIMSCALE 2: text 5 high, 4 past the end; the hook line 5 long.
|
||||
let mut s = session();
|
||||
s.execute("setvar", &json!({ "name": "DIMGAP", "value": 2.0 })).unwrap();
|
||||
s.execute("setvar", &json!({ "name": "DIMSCALE", "value": 2.0 })).unwrap();
|
||||
qleader(&mut s, &["0,0", "20,15", "35,30", "0", "ABC", ""]);
|
||||
let want = vec![(0.0, 0.0), (20.0, 15.0), (30.0, 30.0), (35.0, 30.0)];
|
||||
assert_eq!(drawn(&s), (want, Some(((39.0, 32.5), 5.0, 0.0, 1, "ABC".to_string()))));
|
||||
// DIMTAD 0 or 1, the same place.
|
||||
for tad in [0, 1] {
|
||||
let mut s = session();
|
||||
s.execute("setvar", &json!({ "name": "DIMTAD", "value": tad })).unwrap();
|
||||
qleader(&mut s, &["0,0", "20,15", "40,15", "0", "ABC", ""]);
|
||||
assert_eq!(drawn(&s).1, Some(((40.625, 16.25), 2.5, 0.0, 1, "ABC".to_string())), "DIMTAD {tad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qleader_prompts_and_its_width() {
|
||||
let mut s = session();
|
||||
let mut asked = Vec::new();
|
||||
s.cmdline("QLEADER").unwrap();
|
||||
for t in ["0,0", "20,15", "40,15", "50,15", "ABC", ""] {
|
||||
asked.push(s.current_prompt().unwrap().display());
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
asked,
|
||||
[
|
||||
"Specify first leader point, or [Settings] <Settings>:",
|
||||
"Specify next point:",
|
||||
"Specify next point:",
|
||||
"Specify text width <0>:",
|
||||
"Enter first line of annotation text <Mtext>:",
|
||||
"Enter next line of annotation text:",
|
||||
]
|
||||
);
|
||||
// A point gives the width as its distance from the end, so Dynamic Input shows a distance.
|
||||
assert_eq!(drawn(&s).1.map(|t| t.2), Some(10.0));
|
||||
let mut s = session();
|
||||
s.cmdline("QLEADER").unwrap();
|
||||
for t in ["0,0", "20,15", "40,15"] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.current_prompt().unwrap().distance);
|
||||
// Text that isn't a distance is refused and asked again; Enter is no width.
|
||||
let _ = s.cmdline("abc");
|
||||
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
|
||||
for t in ["", "ABC", ""] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(drawn(&s).1.map(|t| t.2), Some(0.0));
|
||||
// A point so far off that its distance overflows is refused like bad text.
|
||||
let mut s = session();
|
||||
s.cmdline("QLEADER").unwrap();
|
||||
for p in [Vec2::new(0.0, 0.0), Vec2::new(1e308, 0.0)] {
|
||||
s.input(Input::Point(p)).unwrap();
|
||||
}
|
||||
s.cmdline("").unwrap();
|
||||
let _ = s.input(Input::Point(Vec2::new(-1e308, 0.0)));
|
||||
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
|
||||
// A negative width is none. A width isn't remembered: AutoCAD 2024 offers 0 again after 20.
|
||||
for width in ["-5", "20"] {
|
||||
let mut s = session();
|
||||
qleader(&mut s, &["0,0", "20,15", "40,15", width, "ABC", ""]);
|
||||
assert_eq!(drawn(&s).1.map(|t| t.2), Some(width.parse::<f64>().unwrap().max(0.0)));
|
||||
s.cmdline("QLEADER").unwrap();
|
||||
for t in ["0,0", "20,15", "40,15"] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:", "{width}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_at_the_text_prompts_is_no_line_of_text() {
|
||||
let mut s = session();
|
||||
s.cmdline("QLEADER").unwrap();
|
||||
for t in ["0,0", "20,15", "40,15", "0"] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Enter first line of annotation text <Mtext>:");
|
||||
s.cmdline("AB").unwrap();
|
||||
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Enter next line of annotation text:");
|
||||
s.cmdline("CD").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(drawn(&s).1.map(|t| t.4), Some("AB\\PCD".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qleader_without_text_or_points() {
|
||||
// Enter at the first line: the leader alone.
|
||||
let mut s = session();
|
||||
qleader(&mut s, &["0,0", "20,15", "40,15", "0", ""]);
|
||||
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], None));
|
||||
// Sloped, without text: no hook line either (AutoCAD 2024: two vertices).
|
||||
let mut s = session();
|
||||
qleader(&mut s, &["0,0", "20,15", "", "0", ""]);
|
||||
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None));
|
||||
// Enter after one point: nothing.
|
||||
let mut s = session();
|
||||
qleader(&mut s, &["0,0", ""]);
|
||||
assert_eq!(s.doc().unwrap().model.iter().count(), 0);
|
||||
// Settings, typed or by Enter: no dialog yet, the first point is asked again.
|
||||
for settings in ["S", ""] {
|
||||
let mut s = session();
|
||||
s.cmdline("QLEADER").unwrap();
|
||||
s.cmdline(settings).unwrap();
|
||||
assert!(s.log.iter().any(|l| l == "The QLEADER Settings dialog is not available yet."), "{settings:?}: {:?}", s.log);
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:", "{settings:?}");
|
||||
}
|
||||
// LE starts it too.
|
||||
let mut s = session();
|
||||
s.cmdline("LE").unwrap();
|
||||
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qleader_by_json() {
|
||||
let mut s = session();
|
||||
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "width": 20, "text": "AB\r\nCD" })).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(2));
|
||||
let want = vec![(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)];
|
||||
assert_eq!(drawn(&s), (want, Some(((35.625, 31.25), 2.5, 20.0, 1, "AB\\PCD".to_string()))));
|
||||
// Text with nothing on its lines is no text: the leader alone, without a hook line.
|
||||
for text in ["", "\n", "\r\n\r\n"] {
|
||||
let mut s = session();
|
||||
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15]], "width": 0, "text": text })).unwrap();
|
||||
assert_eq!(r["handles"].as_array().map(Vec::len), Some(1), "{text:?}");
|
||||
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None), "{text:?}");
|
||||
}
|
||||
// Empty lines at the end are dropped: running left, the text sits as the command line puts it.
|
||||
let mut s = session();
|
||||
s.execute("qleader", &json!({ "points": [[0, 0], [-20, 15], [-40, 15]], "text": "AB\n\n" })).unwrap();
|
||||
assert_eq!(drawn(&s).1, Some(((-40.625, 13.75), 2.5, 0.0, 9, "AB".to_string())));
|
||||
// 2 or 3 points, a width of 0 or more, text as a string.
|
||||
for bad in [
|
||||
json!({ "points": [[0, 0]] }),
|
||||
json!({ "points": [[0, 0], [1, 1], [2, 1], [3, 1]] }),
|
||||
json!({ "points": [[0, 0], [1, 1]], "width": -1 }),
|
||||
json!({ "points": [[0, 0], [1, 1]], "width": "x" }),
|
||||
json!({ "points": [[0, 0], [1, 1]], "text": 5 }),
|
||||
json!({ "points": [[0, 0], [1, 1]], "text": ["AB", "CD"] }),
|
||||
] {
|
||||
let before = s.doc().unwrap().model.iter().count();
|
||||
assert!(s.execute("qleader", &bad).is_err(), "{bad}");
|
||||
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{bad}");
|
||||
}
|
||||
// A point that can't be read is named as such, not as missing points.
|
||||
for (bad, says) in [
|
||||
(json!({}), "`points` is required"),
|
||||
(json!({ "points": null }), "`points` is required"),
|
||||
(json!({ "points": [[0, 0], ["x", 1]] }), "`points` must be a list of [x, y] points"),
|
||||
] {
|
||||
let e = s.execute("qleader", &bad).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -43,12 +43,14 @@ fn insertion_snaps_to_a_multileader_text() {
|
||||
#[test]
|
||||
fn geometric_center_of_a_closed_spline() {
|
||||
let mut s = Session::new();
|
||||
// A closed fit spline symmetric about (5,5): its centroid is the centre.
|
||||
// A closed fit spline through the corners of a square: the centroid of its area, as AutoCAD
|
||||
// 2024 gives it (MASSPROP of its region; the curve is not symmetric, its tangent where it
|
||||
// closes comes from the first points).
|
||||
s.execute("spline", &json!({"fit": [[0, 5], [5, 0], [10, 5], [5, 10]], "closed": true})).unwrap();
|
||||
let c = Vec2::new(5.0, 5.0);
|
||||
let c = Vec2::new(5.02693946, 5.04916453);
|
||||
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, c + Vec2::new(0.05, 0.0), 0.5, mode::GCEN, None, false).expect("a geometric center");
|
||||
assert_eq!(hit.mode, mode::GCEN);
|
||||
assert!(hit.point.dist(c) < 1e-3, "{:?}", hit.point);
|
||||
assert!(hit.point.dist(c) < 1e-5, "{:?}", hit.point);
|
||||
// An open spline has none.
|
||||
let mut s = Session::new();
|
||||
s.execute("spline", &json!({"fit": [[0, 5], [5, 0], [10, 5], [5, 10]]})).unwrap();
|
||||
|
||||
@@ -21,6 +21,29 @@ fn logged(s: &Session, text: &str) -> bool {
|
||||
|
||||
const FIT: &str = "0,0 1,0.2 5,3 6,3.1 9,0";
|
||||
|
||||
#[test]
|
||||
fn a_click_on_the_last_point_adds_no_fit_point() {
|
||||
// AutoCAD 2024's SPLINE leaves a click on the point before out (measured with
|
||||
// accoreconsole): no repeated fit point, so no kink.
|
||||
let mut s = Session::new();
|
||||
s.cmdline("spline 0,0 5,0 5,0 10,5").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(last_spline(&s).fit, vec![Vec2::ZERO, Vec2::new(5.0, 0.0), Vec2::new(10.0, 5.0)]);
|
||||
// Nor does the preview add one with the cursor on the last point: it shows the curve a
|
||||
// click there would leave, not a corner.
|
||||
let mut s = Session::new();
|
||||
s.cmdline("spline 0,0 5,0 10,5").unwrap();
|
||||
let shown: Vec<Vec<Vec2>> = s
|
||||
.preview(Vec2::new(10.0, 5.0))
|
||||
.into_iter()
|
||||
.filter_map(|e| match e.kind {
|
||||
EntityKind::Spline(sp) => Some(sp.fit),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(shown, vec![vec![Vec2::ZERO, Vec2::new(5.0, 0.0), Vec2::new(10.0, 5.0)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knots_option_sets_the_parametrisation_and_is_remembered() {
|
||||
let mut s = Session::new();
|
||||
@@ -130,7 +153,9 @@ fn object_option_converts_polylines() {
|
||||
assert_eq!(doc.model.iter().count(), 1, "converted in place");
|
||||
let EntityKind::Spline(sp) = last(&s) else { panic!("not converted") };
|
||||
assert_eq!(sp.fit.len(), n);
|
||||
assert!(sp.eval(0.0).near(Vec2::ZERO, 1e-9) && sp.eval(1.0).near(Vec2::new(30.0, 10.0), 1e-9));
|
||||
// Chord-length knots run over the length of the fit points, not 0..1.
|
||||
let (lo, hi) = sp.domain();
|
||||
assert!(sp.eval(lo).near(Vec2::ZERO, 1e-9) && sp.eval(hi).near(Vec2::new(30.0, 10.0), 1e-9));
|
||||
|
||||
// JSON form: a closed polyline becomes a closed spline; arcs are refused.
|
||||
let sq = s.execute("pline", &json!({"vertices": [[0, 20], [10, 20], [10, 30], [0, 30]], "closed": true})).unwrap()["handle"].clone();
|
||||
@@ -172,6 +197,27 @@ fn json_form_takes_the_fit_options() {
|
||||
assert_eq!(sp.fit_opts.end_tangent, Some(-Vec2::Y));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_keeps_a_closed_spline_seam() {
|
||||
// As AutoCAD 2024's REVERSE (accoreconsole, `entget`): the curve and its fit points still start
|
||||
// at (0,0), the other fit points turn round, and so does the tangent where it closes; a
|
||||
// fit-point grip or SPLINEDIT edit then rebuilds the same reversed curve.
|
||||
let mut s = Session::new();
|
||||
s.cmdline("spline 0,0 4,0 6,3 1,4 c").unwrap();
|
||||
let before = last_spline(&s);
|
||||
let h = s.doc().unwrap().model.iter().last().map(|e| e.handle.hex()).unwrap();
|
||||
s.execute("reverse", &json!({ "handle": h })).unwrap();
|
||||
let sp = last_spline(&s);
|
||||
let fit = [Vec2::ZERO, Vec2::new(1.0, 4.0), Vec2::new(6.0, 3.0), Vec2::new(4.0, 0.0)];
|
||||
assert_eq!(sp.fit, fit);
|
||||
assert_eq!(sp.fit_opts.start_tangent, before.fit_opts.start_tangent.map(|t| -t));
|
||||
let (lo, hi) = sp.domain();
|
||||
assert!(sp.eval(lo).near(Vec2::ZERO, 1e-12) && sp.eval(hi).near(Vec2::ZERO, 1e-12));
|
||||
s.execute("splinedit", &json!({ "handle": h, "option": "move", "index": 2, "to": [6, 3] })).unwrap();
|
||||
let again = last_spline(&s);
|
||||
assert!(again.control.iter().zip(&sp.control).all(|(a, b)| a.near(*b, 1e-9)), "{:?} vs {:?}", again.control, sp.control);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cv_method_keeps_cv_on_enter_and_can_switch_back_to_fit() {
|
||||
for entry in ["spline.cv", "spline m cv"] {
|
||||
|
||||
@@ -23,6 +23,7 @@ fn install() {
|
||||
});
|
||||
set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
|
||||
}
|
||||
|
||||
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
|
||||
@@ -117,6 +118,60 @@ fn legacy_visualstyles_warn_only_for_2007_dwg() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A linetype with more dash elements than a DWG counts is saved with its first 255, and each
|
||||
/// way of writing a DWG says so in one note (#1923, F-05); a DXF keeps it whole and says nothing.
|
||||
#[test]
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
fn a_dwg_save_notes_the_linetypes_it_cuts() {
|
||||
use cadcraft_engine::doc::{Common, DashElement, EntityKind, Line, Linetype, Space};
|
||||
use cadcraft_engine::geom::Vec3;
|
||||
install();
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dir = TempDir::new("ltype-notes");
|
||||
let linetype = |name: &str, n: usize| Linetype {
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
pattern: (0..n).map(|i| DashElement::dash(if i % 2 == 0 { 1.0 } else { -0.5 })).collect(),
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
d.linetypes.extend([linetype("LONG", 256), linetype("FITS", 255)]);
|
||||
// Lines drawn with it in model space and on a sheet, so WBLOCK and LAYOUT SAVEAS keep it.
|
||||
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
|
||||
let common = Common { linetype: "LONG".into(), ..Common::default() };
|
||||
let model_line = d.add(&Space::Model, common.clone(), line.clone()).unwrap();
|
||||
d.add(&Space::Paper("Layout1".into()), common, line).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "ltypes.dxf", None);
|
||||
let one_note = |r: &Value| matches!(r["warnings"].as_array().map(Vec::as_slice), Some([note]) if note.as_str().is_some_and(|t| t.contains("1 linetype") && t.contains("255")));
|
||||
let notes_since = |s: &Session, n: usize| s.log[n..].iter().filter(|l| l.contains("dash elements")).count();
|
||||
let dwg = dir.path_str("out.dwg");
|
||||
let writes = [
|
||||
("saveas", json!({ "path": dwg })),
|
||||
("document.bytes", json!({ "format": "dwg" })),
|
||||
("export", json!({ "format": "dwg" })),
|
||||
("wblock", json!({ "path": dir.path_str("all.dwg"), "name": "*" })),
|
||||
("layout.saveas", json!({ "name": "Layout1", "path": dir.path_str("sheet.dwg") })),
|
||||
("-wblock", json!({ "path": dir.path_str("line.dwg"), "handles": [model_line.0] })),
|
||||
];
|
||||
for (cmd, p) in writes {
|
||||
let n = s.log.len();
|
||||
let r = s.execute(cmd, &p).unwrap();
|
||||
assert!(one_note(&r), "{cmd}: {r}");
|
||||
assert_eq!(notes_since(&s, n), 1, "{cmd}: {:?}", &s.log[n..]);
|
||||
}
|
||||
// -WBLOCK at the command line says it too (a DWG file has no precision prompt).
|
||||
let n = s.log.len();
|
||||
let path = dir.path_str("typed.dwg").replace('\\', "/");
|
||||
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"*\")")).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(notes_since(&s, n), 1, "{:?}", &s.log[n..]);
|
||||
let back = cadcraft_io::read(&std::fs::read(&dwg).unwrap(), "out.dwg").unwrap();
|
||||
assert_eq!(back.linetype("LONG").map(|l| l.pattern.len()), Some(255));
|
||||
let n = s.log.len();
|
||||
let r = s.execute("saveas", &json!({ "path": dir.path_str("out.dxf") })).unwrap();
|
||||
assert!(r.get("warnings").is_none() && !s.log[n..].iter().any(|l| l.contains("dash elements")), "{r} {:?}", &s.log[n..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_no_version_writes_is_not_reported() {
|
||||
install();
|
||||
|
||||
@@ -64,6 +64,14 @@ mod tests {
|
||||
let _ = crate::ttf::fallback_for('\u{65E5}');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookups_cached_per_thread_see_a_font_registered_later() {
|
||||
// Asked before it exists (cached as missing), then registered: found.
|
||||
assert!(crate::ttf::find("CADCraft Late Test").is_none());
|
||||
crate::ttf::register_static("cadcraftlatetest-regular", &TINY_SFNT);
|
||||
assert!(crate::ttf::find("CADCraft Late Test").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_barred_family_is_embedded() {
|
||||
// AGENTS.md: no Adobe fonts. Noto Sans CJK is Source Han Sans; `build.rs` skips them.
|
||||
|
||||
+202
-4
@@ -22,11 +22,13 @@
|
||||
//! Fonts) are searched first: a font placed there wins over an installed one with the same file
|
||||
//! name.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock};
|
||||
|
||||
use cadcraft_geom::Vec2;
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
use skrifa::instance::{LocationRef, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
use skrifa::raw::FileRef;
|
||||
@@ -498,6 +500,8 @@ pub fn rescan() {
|
||||
g.face_names.clear();
|
||||
drop(g);
|
||||
GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
// The per-thread lookup caches start over too: the folders' fonts are gone from the shared tables.
|
||||
changed();
|
||||
// SHX files in the same folders: the SHX font table looks there too.
|
||||
crate::shx::set_font_dirs(shx_dirs(&user_dirs()));
|
||||
}
|
||||
@@ -835,6 +839,7 @@ pub fn register(name: &str, bytes: Vec<u8>) {
|
||||
g.registered.insert(k);
|
||||
g.resolved.clear();
|
||||
g.fallback = Fallback::default();
|
||||
changed();
|
||||
}
|
||||
|
||||
/// Register font bytes that live for the whole process under a name; they are copied only when
|
||||
@@ -848,6 +853,7 @@ pub(crate) fn register_static(name: &str, bytes: &'static [u8]) {
|
||||
g.paths.insert(k, Source::Static(bytes));
|
||||
g.resolved.clear();
|
||||
g.fallback = Fallback::default();
|
||||
changed();
|
||||
}
|
||||
|
||||
/// Normalise a style font name ("arial.ttf", "Arial", "ARIALBD.TTF") to a lookup key.
|
||||
@@ -867,9 +873,98 @@ fn is_stroke_name(k: &str) -> bool {
|
||||
|| k == "romans"
|
||||
}
|
||||
|
||||
/// Bumped whenever a font lookup can answer differently (a font registered, FONTALT or
|
||||
/// FONTFALLBACK changed), so the per-thread caches start over.
|
||||
static LOOKUP_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn changed() {
|
||||
// Release: a thread that sees the new generation also sees what changed.
|
||||
LOOKUP_GENERATION.fetch_add(1, Ordering::Release);
|
||||
}
|
||||
|
||||
/// The generation now, taken before a lookup whose answer [`keep`] may cache.
|
||||
fn lookup_generation() -> u64 {
|
||||
LOOKUP_GENERATION.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// `f` on this thread's cache, only when lookups haven't changed since `seen` ([`lookup_generation`]
|
||||
/// before the lookup): an answer found while a font was being registered may be the old one, and
|
||||
/// is used once but not kept.
|
||||
fn keep(seen: u64, f: impl FnOnce(&mut Local)) {
|
||||
LOCAL.with(|l| {
|
||||
let mut l = l.borrow_mut();
|
||||
// Kept under `seen` itself: should lookups change after this check, the next lookup
|
||||
// finds a newer generation and starts over without it.
|
||||
if lookup_generation() != seen {
|
||||
return;
|
||||
}
|
||||
if l.generation != seen {
|
||||
*l = Local { generation: seen, ..Local::default() };
|
||||
}
|
||||
f(&mut l);
|
||||
});
|
||||
}
|
||||
|
||||
/// Most entries each per-thread cache holds before it starts over.
|
||||
const MAX_LOCAL: usize = 8192;
|
||||
|
||||
/// Per-thread answers of [`find`] (by the name as given) and [`fallback_for`]. Display lists are
|
||||
/// built on all cores and look a font up for every text and a fallback for every character a
|
||||
/// text's font lacks (all of a CJK text's): through the shared tables each lookup took global
|
||||
/// locks, so text-heavy drawings spent most of their build waiting on them (#662, #666).
|
||||
#[derive(Default)]
|
||||
struct Local {
|
||||
generation: u64,
|
||||
find: HashMap<String, Option<Face>>,
|
||||
fallback: HashMap<char, Option<Face>>,
|
||||
/// FONTALT, asked for every text whose font isn't installed.
|
||||
alt: Option<String>,
|
||||
/// Glyph outlines, in front of the shared [`glyph_cache`] (whose lock every core reads).
|
||||
glyphs: HashMap<GlyphCacheKey, Arc<GlyphOutline>>,
|
||||
/// The points of the outlines in `glyphs`, held within [`MAX_LOCAL_GLYPH_POINTS`].
|
||||
glyph_points: usize,
|
||||
}
|
||||
|
||||
/// Most outline points each thread keeps in front of the shared cache: a part of its budget, since
|
||||
/// every core has its own and they keep outlines alive after the shared cache lets them go. An
|
||||
/// outline above a quarter of it is read from the shared cache each time.
|
||||
const MAX_LOCAL_GLYPH_POINTS: usize = MAX_SHAPED_POINTS / 16;
|
||||
|
||||
thread_local! {
|
||||
static LOCAL: RefCell<Local> = RefCell::new(Local::default());
|
||||
}
|
||||
|
||||
/// `f` on this thread's cache, emptied first when lookups changed since it was filled.
|
||||
fn local<R>(f: impl FnOnce(&mut Local) -> R) -> R {
|
||||
LOCAL.with(|l| {
|
||||
let mut l = l.borrow_mut();
|
||||
let generation = lookup_generation();
|
||||
if l.generation != generation {
|
||||
*l = Local { generation, ..Local::default() };
|
||||
}
|
||||
f(&mut l)
|
||||
})
|
||||
}
|
||||
|
||||
/// A face of an installed (or registered) font by file name or family name. Stroke-font names
|
||||
/// (".shx", empty) return `None`.
|
||||
pub fn find(name: &str) -> Option<Face> {
|
||||
if let Some(r) = local(|l| l.find.get(name).cloned()) {
|
||||
return r;
|
||||
}
|
||||
let seen = lookup_generation();
|
||||
let r = find_shared(name);
|
||||
keep(seen, |l| {
|
||||
if l.find.len() >= MAX_LOCAL {
|
||||
l.find.clear();
|
||||
}
|
||||
l.find.insert(name.to_string(), r.clone());
|
||||
});
|
||||
r
|
||||
}
|
||||
|
||||
/// [`find`] through the shared table.
|
||||
fn find_shared(name: &str) -> Option<Face> {
|
||||
let k = key(name);
|
||||
if is_stroke_name(&k) {
|
||||
return None;
|
||||
@@ -919,12 +1014,19 @@ fn split_list(s: &str) -> Vec<String> {
|
||||
/// FONTALT: the font used for a text style font that can't be found. Empty = the built-in
|
||||
/// stroke font.
|
||||
pub fn font_alt() -> String {
|
||||
prefs().alt.clone()
|
||||
if let Some(a) = local(|l| l.alt.clone()) {
|
||||
return a;
|
||||
}
|
||||
let seen = lookup_generation();
|
||||
let a = prefs().alt.clone();
|
||||
keep(seen, |l| l.alt = Some(a.clone()));
|
||||
a
|
||||
}
|
||||
|
||||
/// Set FONTALT ("" or "." clears it).
|
||||
pub fn set_font_alt(name: &str) {
|
||||
prefs().alt = clean_name(name);
|
||||
changed();
|
||||
}
|
||||
|
||||
/// FONTFALLBACK: fonts tried first for characters a text's font lacks, comma-separated.
|
||||
@@ -935,6 +1037,7 @@ pub fn fallback_fonts() -> String {
|
||||
/// Set FONTFALLBACK from a comma- or semicolon-separated list ("" or "." clears it).
|
||||
pub fn set_fallback_fonts(list: &str) {
|
||||
prefs().fallback = split_list(list);
|
||||
changed();
|
||||
}
|
||||
|
||||
/// Characters worth a fallback search (not spaces, controls or private-use code points).
|
||||
@@ -949,6 +1052,22 @@ pub fn fallback_for(c: char) -> Option<Face> {
|
||||
if !wants_fallback(c) {
|
||||
return None;
|
||||
}
|
||||
if let Some(r) = local(|l| l.fallback.get(&c).cloned()) {
|
||||
return r;
|
||||
}
|
||||
let seen = lookup_generation();
|
||||
let r = fallback_shared(c);
|
||||
keep(seen, |l| {
|
||||
if l.fallback.len() >= MAX_LOCAL {
|
||||
l.fallback.clear();
|
||||
}
|
||||
l.fallback.insert(c, r.clone());
|
||||
});
|
||||
r
|
||||
}
|
||||
|
||||
/// [`fallback_for`] through the shared tables.
|
||||
fn fallback_shared(c: char) -> Option<Face> {
|
||||
let (list, alt) = {
|
||||
let p = prefs();
|
||||
(p.fallback.clone(), p.alt.clone())
|
||||
@@ -969,6 +1088,8 @@ pub fn fallback_for(c: char) -> Option<Face> {
|
||||
pub(crate) struct GlyphOutline {
|
||||
pub(crate) contours: Arc<[Vec<Vec2>]>,
|
||||
pub(crate) points: usize,
|
||||
/// The extent of `contours`, found once as the outline is built (empty when it has none).
|
||||
bounds: Bounds2,
|
||||
pub(crate) advance: f64,
|
||||
pub(crate) cap: f64,
|
||||
/// The font maps the character (false: the missing-glyph shape).
|
||||
@@ -988,9 +1109,10 @@ enum GlyphKey {
|
||||
/// Cached glyph outlines keyed by (font bytes address, length, face, glyph). Fonts live for the
|
||||
/// whole process in the font table, so the address identifies them. A read-write lock: display
|
||||
/// lists are built on all cores and nearly every lookup is a hit, which a mutex serialized.
|
||||
type GlyphCacheKey = (usize, usize, u32, GlyphKey);
|
||||
#[derive(Default)]
|
||||
struct GlyphCache {
|
||||
glyphs: HashMap<(usize, usize, u32, GlyphKey), Arc<GlyphOutline>>,
|
||||
glyphs: HashMap<GlyphCacheKey, Arc<GlyphOutline>>,
|
||||
points: usize,
|
||||
}
|
||||
|
||||
@@ -1163,10 +1285,45 @@ pub fn glyph_contours(face: &Face, gid: u16) -> Arc<[Vec<Vec2>]> {
|
||||
glyph_by_id(face, u32::from(gid)).contours.clone()
|
||||
}
|
||||
|
||||
/// The extent of [`glyph_contours`] in the same font units (empty for a glyph without ink), so
|
||||
/// renderers can test a placement against a view without visiting the outline's points.
|
||||
pub fn glyph_bounds(face: &Face, gid: u16) -> Bounds2 {
|
||||
glyph_by_id(face, u32::from(gid)).bounds
|
||||
}
|
||||
|
||||
/// Load or build a glyph outline with bounded flattening, retaining its advance even when contours are discarded.
|
||||
/// Cache insertion clears existing entries when the glyph-count or aggregate point allowance would be exceeded.
|
||||
fn outline(face: &Face, k: GlyphKey) -> Arc<GlyphOutline> {
|
||||
let key = (face.bytes.as_ptr() as usize, face.bytes.len(), face.index, k);
|
||||
if let Some(g) = local(|l| l.glyphs.get(&key).cloned()) {
|
||||
return g;
|
||||
}
|
||||
let g = outline_shared(face, key);
|
||||
local(|l| l.keep_glyph(key, &g));
|
||||
g
|
||||
}
|
||||
|
||||
impl Local {
|
||||
/// Keep an outline in front of the shared cache, within [`MAX_LOCAL`] entries and
|
||||
/// [`MAX_LOCAL_GLYPH_POINTS`] points (started over when either would be passed); an outline
|
||||
/// above a quarter of the points isn't kept.
|
||||
fn keep_glyph(&mut self, key: GlyphCacheKey, g: &Arc<GlyphOutline>) {
|
||||
if g.points > MAX_LOCAL_GLYPH_POINTS / 4 {
|
||||
return;
|
||||
}
|
||||
if self.glyphs.len() >= MAX_LOCAL || self.glyph_points.saturating_add(g.points) > MAX_LOCAL_GLYPH_POINTS {
|
||||
self.glyphs.clear();
|
||||
self.glyph_points = 0;
|
||||
}
|
||||
if self.glyphs.insert(key, g.clone()).is_none() {
|
||||
self.glyph_points = self.glyph_points.saturating_add(g.points);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`outline`] through the shared cache.
|
||||
fn outline_shared(face: &Face, key: GlyphCacheKey) -> Arc<GlyphOutline> {
|
||||
let k = key.3;
|
||||
if let Some(g) = glyph_cache().read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&key) {
|
||||
return g.clone();
|
||||
}
|
||||
@@ -1184,7 +1341,8 @@ fn outline(face: &Face, k: GlyphKey) -> Arc<GlyphOutline> {
|
||||
let advance = f64::from(f.glyph_metrics(Size::new(UPEM), LocationRef::default()).advance_width(gid).unwrap_or(UPEM * 0.5));
|
||||
let (cap, mapped, gid) = (cap_height(&f), mapped.is_some(), gid.to_u32());
|
||||
let points = pen.contours.iter().map(Vec::len).sum();
|
||||
let g = Arc::new(GlyphOutline { points, contours: pen.contours.into(), advance, cap, mapped, gid, face: Some(face.clone()) });
|
||||
let bounds = Bounds2::from_points(pen.contours.iter().flatten().copied());
|
||||
let g = Arc::new(GlyphOutline { points, bounds, contours: pen.contours.into(), advance, cap, mapped, gid, face: Some(face.clone()) });
|
||||
let mut cache = glyph_cache().write().unwrap_or_else(PoisonError::into_inner);
|
||||
if cache.glyphs.len() >= MAX_CACHED_GLYPHS || cache.points.saturating_add(points) > MAX_SHAPED_POINTS {
|
||||
cache.glyphs.clear();
|
||||
@@ -1601,6 +1759,46 @@ mod geometry_budget_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod local_cache_tests {
|
||||
use super::*;
|
||||
|
||||
/// An answer looked up while lookups changed (a font registered meanwhile) is not kept: the
|
||||
/// thread asks again instead of keeping a stale "not found".
|
||||
#[test]
|
||||
fn a_lookup_overtaken_by_a_change_is_not_kept() {
|
||||
let seen = lookup_generation();
|
||||
changed();
|
||||
keep(seen, |l| l.alt = Some("stale".into()));
|
||||
assert_ne!(local(|l| l.alt.clone()), Some("stale".to_string()));
|
||||
let now = lookup_generation();
|
||||
keep(now, |l| l.alt = Some("fresh".into()));
|
||||
// Kept unless yet another change came in between (other tests may register fonts).
|
||||
let cached = local(|l| l.alt.clone());
|
||||
if lookup_generation() == now {
|
||||
assert_eq!(cached, Some("fresh".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Each thread's outlines stay within [`MAX_LOCAL_GLYPH_POINTS`], and an outline too large
|
||||
/// for it isn't kept.
|
||||
#[test]
|
||||
fn a_threads_outlines_stay_within_their_point_budget() {
|
||||
let mut l = Local::default();
|
||||
let key = |i: u32| (0usize, 0usize, 0u32, GlyphKey::Id(i));
|
||||
let big = MAX_LOCAL_GLYPH_POINTS / 8;
|
||||
let g = Arc::new(GlyphOutline { points: big, cap: 1.0, ..Default::default() });
|
||||
for i in 0..100 {
|
||||
l.keep_glyph(key(i), &g);
|
||||
assert!(l.glyph_points <= MAX_LOCAL_GLYPH_POINTS, "{}", l.glyph_points);
|
||||
assert_eq!(l.glyph_points, l.glyphs.len() * big);
|
||||
}
|
||||
let huge = Arc::new(GlyphOutline { points: MAX_LOCAL_GLYPH_POINTS / 2, cap: 1.0, ..Default::default() });
|
||||
l.keep_glyph(key(500), &huge);
|
||||
assert!(!l.glyphs.contains_key(&key(500)), "an outline above a quarter of the budget isn't kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod scan_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -94,6 +94,21 @@ fn elevate_bezier(p: &[H]) -> Vec<H> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A closed spline's fit points in the other direction, still from the seam: the first point
|
||||
/// (with its repeats, a kink) stays first and the rest turn round, as AutoCAD 2024's REVERSE
|
||||
/// leaves them; a repeated closing point stays last.
|
||||
fn reversed_loop(fit: &[Vec2]) -> Vec<Vec2> {
|
||||
let Some(seam) = fit.first().copied() else { return Vec::new() };
|
||||
let at_seam = |q: &&Vec2| q.near(seam, 1e-12);
|
||||
let lead = fit.iter().take_while(at_seam).count();
|
||||
let trail = fit.iter().skip(lead).rev().take_while(at_seam).count();
|
||||
let middle = fit.get(lead..fit.len() - trail).unwrap_or(&[]);
|
||||
let mut out = fit.get(..lead).unwrap_or(&[]).to_vec();
|
||||
out.extend(middle.iter().rev());
|
||||
out.extend(fit.get(fit.len() - trail..).unwrap_or(&[]));
|
||||
out
|
||||
}
|
||||
|
||||
/// Basis functions of degree `p` in `n[..=p]` and of degree `p - 1` in `lower[..p]` for `p >= 1`,
|
||||
/// in one Cox-de Boor sweep: the degree `p - 1` values are the state just before the last step,
|
||||
/// so they match [`basis`] exactly. `left` and `right` are scratch of `p + 1` values; the outputs
|
||||
@@ -346,7 +361,7 @@ impl Spline {
|
||||
}
|
||||
|
||||
/// Reversed direction: control points, weights, fit points and knots (and the fit end
|
||||
/// tangents swap ends and turn round).
|
||||
/// tangents swap ends and turn round). A closed spline still starts at its first fit point.
|
||||
pub fn reversed(&self) -> Spline {
|
||||
let (lo, hi) = (self.knots.first().copied().unwrap_or(0.0), self.knots.last().copied().unwrap_or(1.0));
|
||||
Spline {
|
||||
@@ -354,7 +369,7 @@ impl Spline {
|
||||
knots: self.knots.iter().rev().map(|k| lo + hi - k).collect(),
|
||||
control: self.control.iter().rev().copied().collect(),
|
||||
weights: self.weights.iter().rev().copied().collect(),
|
||||
fit: self.fit.iter().rev().copied().collect(),
|
||||
fit: if self.closed { reversed_loop(&self.fit) } else { self.fit.iter().rev().copied().collect() },
|
||||
closed: self.closed,
|
||||
fit_opts: crate::FitOptions {
|
||||
start_tangent: self.fit_opts.end_tangent.map(|t| -t),
|
||||
@@ -846,13 +861,25 @@ mod tests {
|
||||
assert!(s.split_at(0.0).is_none() && s.split_at(f64::NAN).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_fit_list_reverses_from_its_seam() {
|
||||
let (a, b, c, d) = (Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0));
|
||||
assert_eq!(reversed_loop(&[a, b, c, d]), [a, d, c, b]);
|
||||
// A kink at the seam stays first, a repeated closing point last.
|
||||
assert_eq!(reversed_loop(&[a, a, b, c, d]), [a, a, d, c, b]);
|
||||
assert_eq!(reversed_loop(&[a, b, c, d, a]), [a, d, c, b, a]);
|
||||
assert_eq!(reversed_loop(&[a, a]), [a, a]);
|
||||
assert!(reversed_loop(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periodic_spline_clamps_to_the_same_curve() {
|
||||
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 1.0), Vec2::new(5.0, 4.0), Vec2::new(1.0, 5.0)];
|
||||
let p = Spline::from_fit(&fit, true);
|
||||
assert!(p.is_periodic());
|
||||
// Uniform parameters: the control points wrap round (a chord-length fit is clamped).
|
||||
let p = Spline::fit_with(&fit, true, crate::FitOptions { knots: crate::KnotParam::Uniform, ..Default::default() });
|
||||
assert!(p.wraps() && p.is_periodic());
|
||||
let c = p.clamped().unwrap();
|
||||
assert!(!c.is_periodic());
|
||||
assert!(!c.wraps() && c.is_periodic(), "the same smooth closed curve");
|
||||
let ((plo, phi), (clo, chi)) = (p.domain(), c.domain());
|
||||
for i in 0..=20 {
|
||||
let f = f64::from(i) / 20.0;
|
||||
|
||||
@@ -43,10 +43,10 @@ impl Spline {
|
||||
Spline::fit_with(fit, false, FitOptions::default())
|
||||
}
|
||||
|
||||
/// Smooth closed (periodic) cubic interpolation through fit points. Chord-length parameters
|
||||
/// include the closing chord; the knot vector is the periodic (unclamped) extension and the
|
||||
/// first `degree` control points repeat at the end, so the curve has continuous tangent and
|
||||
/// curvature at the seam. A repeated closing fit point is dropped.
|
||||
/// Smooth closed cubic interpolation through fit points, as AutoCAD 2024 builds it: through
|
||||
/// the fit points and back to the first, with chord-length parameters, clamped, and with the
|
||||
/// same first derivative at both ends (see `Spline::fit_with`). A repeated closing fit point
|
||||
/// is dropped.
|
||||
pub fn from_fit_points_closed(fit: &[Vec2]) -> Spline {
|
||||
Spline::fit_with(fit, true, FitOptions::default())
|
||||
}
|
||||
@@ -56,11 +56,31 @@ impl Spline {
|
||||
Spline::fit_with(fit, closed, FitOptions::default())
|
||||
}
|
||||
|
||||
/// Closed with an unclamped (periodic) knot vector, as DXF flags it (group 70 bit 2).
|
||||
/// Closed and smooth where it closes: AutoCAD's "periodic" (DXF group 70 bit 2), which
|
||||
/// AutoCAD 2024 sets from the curve itself. Either the control points wrap round
|
||||
/// ([`Spline::wraps`]), or the knots are clamped and the curve has the same first derivative
|
||||
/// at both ends, as in AutoCAD's closed fit-point spline. The same direction with another
|
||||
/// length is not enough: AutoCAD clears the bit then too.
|
||||
pub fn is_periodic(&self) -> bool {
|
||||
self.wraps() || (self.closed && self.is_valid() && self.closes_smoothly())
|
||||
}
|
||||
|
||||
/// Closed with an unclamped knot vector: the first `degree` control points repeat at the end,
|
||||
/// so the control points wrap round the seam (the knot shape; see [`Spline::is_periodic`]
|
||||
/// for the curve's).
|
||||
pub fn wraps(&self) -> bool {
|
||||
self.closed && self.knots.first() != self.knots.get(self.degree)
|
||||
}
|
||||
|
||||
/// The ends meet with the same first derivative (to 1e-9 of its length). The spline must be
|
||||
/// valid.
|
||||
fn closes_smoothly(&self) -> bool {
|
||||
let (lo, hi) = self.domain();
|
||||
let (d0, d1) = (self.derivative(lo), self.derivative(hi));
|
||||
let speed = d0.len().max(d1.len());
|
||||
speed > 0.0 && d0.near(d1, 1e-9 * speed) && self.eval(lo).near(self.eval(hi), 1e-9 * speed * (hi - lo))
|
||||
}
|
||||
|
||||
pub fn is_valid(&self) -> bool {
|
||||
let n = self.control.len();
|
||||
n > self.degree
|
||||
|
||||
@@ -550,22 +550,39 @@ fn fits_are_bit_identical_to_the_dense_solver() {
|
||||
let tolerant = FitOptions { tolerance: 0.5, ..FitOptions::default() };
|
||||
let tangents = FitOptions { start_tangent: Some(Vec2::new(0.0, 1.0)), end_tangent: Some(Vec2::new(1.0, -1.0)), ..FitOptions::default() };
|
||||
let chord = FitOptions { knots: crate::KnotParam::Chord, ..FitOptions::default() };
|
||||
// Chord-length knots fit open curves with `chord_interpolate` and closed ones with
|
||||
// `chord_closed`; the others with `interpolate`, whose end tangents add rows of their own, and
|
||||
// with the cyclic matrix.
|
||||
let sqrt = FitOptions { knots: crate::KnotParam::SqrtChord, ..FitOptions::default() };
|
||||
let uniform = FitOptions { knots: crate::KnotParam::Uniform, ..FitOptions::default() };
|
||||
let sqrt_tangents = FitOptions { knots: crate::KnotParam::SqrtChord, ..tangents };
|
||||
for n in [3, 4, 5, 7, 12, 30, 100] {
|
||||
for round in 0..4 {
|
||||
let zero_every = [0, 2, 3, 1][round];
|
||||
let pts = fit_points(n, &mut seed, zero_every);
|
||||
for closed in [false, true] {
|
||||
for (name, opts) in [("default", FitOptions::default()), ("tolerance", tolerant), ("tangents", tangents), ("chord", chord)] {
|
||||
for (name, opts) in [
|
||||
("default", FitOptions::default()),
|
||||
("tolerance", tolerant),
|
||||
("tangents", tangents),
|
||||
("chord", chord),
|
||||
("sqrt", sqrt),
|
||||
("uniform", uniform),
|
||||
("sqrt tangents", sqrt_tangents),
|
||||
] {
|
||||
assert_fit_unchanged(&pts, closed, opts, &format!("n={n} closed={closed} {name} zero_every={zero_every}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Large point sets: open interpolation (banded) and a closed one (full bandwidth), and a
|
||||
// tolerance fit at the size the approximation search still accepts.
|
||||
// Large point sets: open and closed interpolation with chord-length and square-root knots (the
|
||||
// closed square-root one is the cyclic matrix, full bandwidth), and a tolerance fit at the size
|
||||
// the approximation search still accepts.
|
||||
let big = fit_points(1000, &mut seed, 0);
|
||||
assert_fit_unchanged(&big, false, FitOptions::default(), "n=1000 open");
|
||||
assert_fit_unchanged(&big, false, sqrt, "n=1000 open sqrt");
|
||||
assert_fit_unchanged(&big[..150], true, FitOptions::default(), "n=150 closed");
|
||||
assert_fit_unchanged(&big[..150], true, sqrt, "n=150 closed sqrt");
|
||||
assert_fit_unchanged(&big[..300], false, tolerant, "n=300 tolerance");
|
||||
// Repeated points are kinks, which fit each piece on its own.
|
||||
let mut kinked = fit_points(40, &mut seed, 0);
|
||||
|
||||
+640
-39
@@ -67,10 +67,13 @@ impl KnotParam {
|
||||
pub struct FitOptions {
|
||||
#[serde(default)]
|
||||
pub knots: KnotParam,
|
||||
/// Unit tangent direction at the first fit point; `None` lets the end follow the points.
|
||||
/// Tangent at the first fit point; `None` lets the end follow the points. SPLINE, SPLINEDIT
|
||||
/// and the JSON options give a unit direction; one read from a file keeps its length through
|
||||
/// refits and transforms ([`Spline::fit_with_end_derivatives`]). A closed spline with
|
||||
/// chord-length knots keeps its tangent where it closes here and as the end tangent.
|
||||
#[serde(default)]
|
||||
pub start_tangent: Option<Vec2>,
|
||||
/// Unit tangent direction at the last fit point.
|
||||
/// Tangent at the last fit point, as the start one.
|
||||
#[serde(default)]
|
||||
pub end_tangent: Option<Vec2>,
|
||||
/// Largest allowed distance between the curve and a fit point; 0 passes through them.
|
||||
@@ -79,14 +82,22 @@ pub struct FitOptions {
|
||||
}
|
||||
|
||||
impl FitOptions {
|
||||
/// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative
|
||||
/// tolerance: what a spline stores.
|
||||
/// Normalised tangents (non-finite directions and those too short to normalise dropped) and a
|
||||
/// finite, non-negative tolerance: what [`Spline::fit_with`] stores.
|
||||
pub fn sanitized(self) -> FitOptions {
|
||||
let dir = |t: Option<Vec2>| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized);
|
||||
let o = self.sanitized_keeping_length();
|
||||
// `normalized` gives zero for a direction too short to scale to a unit.
|
||||
let unit = |t: Option<Vec2>| t.map(Vec2::normalized).filter(|d| d.len() > 0.5);
|
||||
FitOptions { start_tangent: unit(o.start_tangent), end_tangent: unit(o.end_tangent), ..o }
|
||||
}
|
||||
|
||||
/// As [`FitOptions::sanitized`], but the tangents keep their length.
|
||||
pub fn sanitized_keeping_length(self) -> FitOptions {
|
||||
let valid = |t: Option<Vec2>| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12);
|
||||
FitOptions {
|
||||
knots: self.knots,
|
||||
start_tangent: dir(self.start_tangent),
|
||||
end_tangent: dir(self.end_tangent),
|
||||
start_tangent: valid(self.start_tangent),
|
||||
end_tangent: valid(self.end_tangent),
|
||||
tolerance: if self.tolerance.is_finite() { self.tolerance.max(0.0) } else { 0.0 },
|
||||
}
|
||||
}
|
||||
@@ -103,31 +114,34 @@ const MAX_INTERP_POINTS: usize = 4_096;
|
||||
|
||||
impl Spline {
|
||||
/// Build a spline through (or, with a tolerance, near) `fit`, open or closed. Closed curves
|
||||
/// are periodic and ignore end tangents; a tolerance approximates them with fewer periodic
|
||||
/// are smooth where they close and ignore the end tangents given. With chord-length knots
|
||||
/// they are clamped as AutoCAD 2024 builds them, and keep AutoCAD's tangent where they close
|
||||
/// as both end tangents (which [`Spline::refit`] then keeps, as AutoCAD keeps 12/13);
|
||||
/// otherwise their knots are periodic. A tolerance approximates them with fewer periodic
|
||||
/// control points. A fit point given twice in a row is a kink (SPLINEDIT Fit data Kink): the
|
||||
/// curve passes through it with a corner (a knot of full multiplicity) and the pieces on
|
||||
/// either side are fitted on their own.
|
||||
pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
|
||||
let opts = opts.sanitized();
|
||||
let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None };
|
||||
let mut s = if let Some(s) = kinked {
|
||||
s
|
||||
} else {
|
||||
// Repeats at the ends of an open curve are no corners: fit without them.
|
||||
let (pts, _) = kinks(fit, false);
|
||||
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) };
|
||||
if pts.len() != fit.len() && !closed {
|
||||
s.fit = fit.to_vec();
|
||||
}
|
||||
s
|
||||
};
|
||||
s.fit_opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts };
|
||||
s
|
||||
let opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts };
|
||||
fit_sanitized(fit, closed, opts.sanitized())
|
||||
}
|
||||
|
||||
/// As [`Spline::fit_with`], but an end tangent is the end derivative itself, length included
|
||||
/// (per unit of chord with chord-length knots), as AutoCAD 2024 rebuilds a SPLINE stored with
|
||||
/// fit data only (DXF 12/13): with 12 = (0, 3) the second control point is three times as far
|
||||
/// from the first as with (0, 1). `fit_with`, behind SPLINE and the JSON options, takes
|
||||
/// tangents as directions. A closed spline with chord-length knots takes the start tangent
|
||||
/// (its stored tangent where it closes) at both ends, as AutoCAD keeps it through fit-point
|
||||
/// edits, REVERSE and DXF.
|
||||
pub fn fit_with_end_derivatives(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
|
||||
fit_sanitized(fit, closed, opts.sanitized_keeping_length())
|
||||
}
|
||||
|
||||
/// Rebuild from new fit points with this spline's knot parametrisation, tangents and tolerance.
|
||||
/// The tangents count as stored, so one read from a file keeps its length, as in AutoCAD's
|
||||
/// SPLINEDIT Fit data Move.
|
||||
pub fn refit(&self, fit: &[Vec2], closed: bool) -> Spline {
|
||||
Spline::fit_with(fit, closed, self.fit_opts)
|
||||
Spline::fit_with_end_derivatives(fit, closed, self.fit_opts)
|
||||
}
|
||||
|
||||
/// Which knot parametrisation produced this spline's knots from its fit points (DXF files
|
||||
@@ -190,12 +204,26 @@ impl Spline {
|
||||
.unwrap_or(KnotParam::Chord)
|
||||
}
|
||||
|
||||
/// Apply an affine map to the control and fit points and turn the end tangents with it.
|
||||
/// Apply an affine map to the control and fit points and turn the end tangents with it. A
|
||||
/// tangent keeps its length, as in AutoCAD, where SCALE 2 leaves 12 = (0, 3) as it is. A map
|
||||
/// that flattens a tangent's direction (to under EPS of the map's largest axis scale) drops it.
|
||||
pub fn transform(&mut self, m: &Mat3) {
|
||||
for c in self.control.iter_mut().chain(self.fit.iter_mut()) {
|
||||
*c = m.apply(*c);
|
||||
}
|
||||
let turn = |t: Option<Vec2>| t.map(|v| m.apply_vec(v).normalized()).filter(|v| v.len() > 0.5);
|
||||
// The map's largest axis scale: a direction it shrinks to under EPS of that is flattened.
|
||||
// Not `scale_factor`, which is 0 for a singular map and would keep rounding noise.
|
||||
let scale = Vec2::new(m.a, m.b).len().max(Vec2::new(m.c, m.d).len());
|
||||
let turn = |t: Option<Vec2>| {
|
||||
t.and_then(|v| {
|
||||
let w = m.apply_vec(v);
|
||||
let (lv, lw) = (v.len(), w.len());
|
||||
// Scaled by lengths, not through `normalized`, which zeroes a short tangent. A map
|
||||
// that flattens the tangent's direction drops it; an invertible uniform scale,
|
||||
// however small, does not.
|
||||
(lw.is_finite() && lw > crate::EPS * scale * lv).then(|| w / lw * lv)
|
||||
})
|
||||
};
|
||||
self.fit_opts.start_tangent = turn(self.fit_opts.start_tangent);
|
||||
self.fit_opts.end_tangent = turn(self.fit_opts.end_tangent);
|
||||
}
|
||||
@@ -224,10 +252,32 @@ fn chord_length(pts: &[Vec2]) -> f64 {
|
||||
pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum()
|
||||
}
|
||||
|
||||
/// [`Spline::fit_with`] with `opts` already sanitized.
|
||||
fn fit_sanitized(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
|
||||
let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None };
|
||||
let mut s = if let Some(s) = kinked {
|
||||
s
|
||||
} else {
|
||||
// Repeats at the ends of an open curve are no corners: fit without them.
|
||||
let (pts, _) = kinks(fit, false);
|
||||
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance, opts.start_tangent) } else { open_fit(&pts, opts) };
|
||||
if pts.len() != fit.len() && !closed {
|
||||
s.fit = fit.to_vec();
|
||||
}
|
||||
s
|
||||
};
|
||||
// A closed spline keeps only the tangent its fit used where it closes.
|
||||
s.fit_opts = if closed { FitOptions { start_tangent: s.fit_opts.start_tangent, end_tangent: s.fit_opts.end_tangent, ..opts } } else { opts };
|
||||
s
|
||||
}
|
||||
|
||||
fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
|
||||
let n = fit.len();
|
||||
let tangents = opts.start_tangent.is_some() || opts.end_tangent.is_some();
|
||||
if n < 2 || (n == 2 && !tangents) {
|
||||
// Two points without tangents are a line, except that AutoCAD 2024's chord-length fit makes
|
||||
// it a cubic ([`chord_interpolate`]: control points at the thirds), with a fit tolerance too.
|
||||
let chord_fit = opts.knots == KnotParam::Chord;
|
||||
if n < 2 || (n == 2 && !tangents && !chord_fit) {
|
||||
let mut s = if n < 2 {
|
||||
Spline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], control: fit.to_vec(), ..Spline::default() }
|
||||
} else {
|
||||
@@ -237,7 +287,8 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
|
||||
return s;
|
||||
}
|
||||
let u = params(fit, opts.knots, false);
|
||||
// Tangents are directions; the derivative's length is the curve length in parameter space.
|
||||
// A tangent is the derivative per unit of chord (a unit direction unless read from a file):
|
||||
// per unit of the normalised parameter it is that times the chord length.
|
||||
let len = chord_length(fit).max(1e-12);
|
||||
let d0 = opts.start_tangent.map(|t| t * len);
|
||||
let d1 = opts.end_tangent.map(|t| t * len);
|
||||
@@ -255,7 +306,131 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
|
||||
if n > MAX_INTERP_POINTS {
|
||||
return through_control();
|
||||
}
|
||||
interpolate(fit, &u, d0, d1).unwrap_or_else(through_control)
|
||||
// No approximation (none asked for, too few or too many points for one, or none within the
|
||||
// tolerance): the curve passes through the points. With chord-length knots it is AutoCAD
|
||||
// 2024's interpolation (measured without a tolerance, and for two points with one); the other
|
||||
// parametrisations interpolate with normalised knots.
|
||||
let chord = if opts.knots == KnotParam::Chord { chord_interpolate(fit, opts.start_tangent, opts.end_tangent) } else { None };
|
||||
chord.or_else(|| interpolate(fit, &u, d0, d1)).unwrap_or_else(through_control)
|
||||
}
|
||||
|
||||
/// AutoCAD 2024's cubic through fit points with chord-length parameters, as it builds a fit-point
|
||||
/// spline: the parameters are the running chord length, not normalised, and they are the interior
|
||||
/// knots themselves; two control points more than fit points meet the end conditions. An end with
|
||||
/// a tangent has it as its first derivative, length included (one per unit of chord for a unit
|
||||
/// direction); an end without one has no curvature (second derivative 0). `None` for fewer than
|
||||
/// two points or two in the same place.
|
||||
fn chord_interpolate(fit: &[Vec2], d0: Option<Vec2>, d1: Option<Vec2>) -> Option<Spline> {
|
||||
let n = fit.len();
|
||||
if n < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut t = Vec::with_capacity(n);
|
||||
let mut total = 0.0;
|
||||
t.push(total);
|
||||
for w in fit.windows(2) {
|
||||
let (a, b) = (w.first()?, w.get(1)?);
|
||||
let d = a.dist(*b);
|
||||
if !(d > 0.0 && d.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
total += d;
|
||||
t.push(total);
|
||||
}
|
||||
let p = 3;
|
||||
let m = n + 2;
|
||||
let mut knots = vec![0.0; p + 1];
|
||||
knots.extend(t.get(1..n - 1)?.iter().copied());
|
||||
knots.extend([total; 4]);
|
||||
let k = |i: usize| knots.get(i).copied().unwrap_or(0.0);
|
||||
let mut a = vec![vec![0.0; m]; m];
|
||||
let (mut xs, mut ys) = (vec![0.0; m], vec![0.0; m]);
|
||||
let mut row = 0;
|
||||
let mut put = |coeffs: &[(usize, f64)], rhs: Vec2, a: &mut Vec<Vec<f64>>| {
|
||||
if let Some(r) = a.get_mut(row) {
|
||||
for (j, v) in coeffs {
|
||||
if let Some(c) = r.get_mut(*j) {
|
||||
*c += *v;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(x), Some(y)) = (xs.get_mut(row), ys.get_mut(row)) {
|
||||
(*x, *y) = (rhs.x, rhs.y);
|
||||
}
|
||||
row += 1;
|
||||
};
|
||||
// At the start the first derivative is 3 (P1 - P0) / k(4), and the second derivative is 0
|
||||
// when (P1 - P0) / k(4) = (P2 - P1) / k(5); the end mirrors it. Each end's row sits next to
|
||||
// that end's point rows, so the system stays banded for `solve`.
|
||||
let (s1, s2) = (1.0 / (k(p + 1) - k(1)), 1.0 / (k(p + 2) - k(2)));
|
||||
match d0 {
|
||||
Some(d) => put(&[(0, -3.0 * s1), (1, 3.0 * s1)], d, &mut a),
|
||||
None => put(&[(0, s1), (1, -(s1 + s2)), (2, s2)], Vec2::ZERO, &mut a),
|
||||
}
|
||||
for (ti, q) in t.iter().zip(fit) {
|
||||
let span = find_span(m - 1, p, *ti, &knots);
|
||||
let coeffs: Vec<(usize, f64)> = basis(span, *ti, p, &knots).into_iter().enumerate().map(|(j, v)| (span + j - p, v)).collect();
|
||||
put(&coeffs, *q, &mut a);
|
||||
}
|
||||
let (e1, e2) = (1.0 / (k(m + p - 1) - k(m - 1)), 1.0 / (k(m + p - 2) - k(m - 2)));
|
||||
match d1 {
|
||||
Some(d) => put(&[(m - 2, -3.0 * e1), (m - 1, 3.0 * e1)], d, &mut a),
|
||||
None => put(&[(m - 3, e2), (m - 2, -(e1 + e2)), (m - 1, e1)], Vec2::ZERO, &mut a),
|
||||
}
|
||||
let (cx, cy) = (solve(a.clone(), xs)?, solve(a, ys)?);
|
||||
let control: Vec<Vec2> = cx.into_iter().zip(cy).map(|(x, y)| Vec2::new(x, y)).collect();
|
||||
if control.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
Some(Spline { degree: p, knots, control, fit: fit.to_vec(), ..Spline::default() })
|
||||
}
|
||||
|
||||
/// The unit tangent AutoCAD 2024 gives a closed fit-point spline where it closes: the derivative
|
||||
/// at the first point of the cubic through the first four points of the loop (the fit points and
|
||||
/// back to the first), with square-root-of-chord parameters. `None` with fewer than four, or two
|
||||
/// together.
|
||||
fn closing_tangent(ring: &[Vec2]) -> Option<Vec2> {
|
||||
let q: [Vec2; 4] = [*ring.first()?, *ring.get(1)?, *ring.get(2)?, *ring.get(3)?];
|
||||
let mut t = [0.0; 4];
|
||||
for i in 1..4 {
|
||||
let step = q[i - 1].dist(q[i]).sqrt();
|
||||
if !(step > 0.0 && step.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
t[i] = t[i - 1] + step;
|
||||
}
|
||||
// Derivatives of the Lagrange basis polynomials at t[0].
|
||||
let mut d = q[0] * (1..4).map(|j| 1.0 / (t[0] - t[j])).sum::<f64>();
|
||||
for i in 1..4 {
|
||||
let c = (1..4).filter(|j| *j != i).fold(1.0 / (t[i] - t[0]), |c, j| c * (t[0] - t[j]) / (t[i] - t[j]));
|
||||
d += q[i] * c;
|
||||
}
|
||||
// Divided by its length, not `normalized`, which gives zero for a short one (a small drawing).
|
||||
let len = d.len();
|
||||
(len > 0.0 && len.is_finite()).then(|| d / len)
|
||||
}
|
||||
|
||||
/// AutoCAD 2024's closed fit-point spline with chord-length parameters: the open cubic through
|
||||
/// the fit points and back to the first ([`chord_interpolate`]), clamped, with the same first
|
||||
/// derivative at both ends: `tangent`, else the unit one from [`closing_tangent`]. It keeps that
|
||||
/// tangent as both end tangents, as AutoCAD keeps it (DXF 12/13) through fit-point edits. `pts`
|
||||
/// is without its closing point.
|
||||
fn chord_closed(pts: &[Vec2], tangent: Option<Vec2>) -> Option<Spline> {
|
||||
if pts.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let mut ring = pts.to_vec();
|
||||
ring.push(*pts.first()?);
|
||||
let d = match tangent {
|
||||
Some(t) => t,
|
||||
None => closing_tangent(&ring)?,
|
||||
};
|
||||
let mut s = chord_interpolate(&ring, Some(d), Some(d))?;
|
||||
s.fit = pts.to_vec();
|
||||
s.closed = true;
|
||||
s.fit_opts.start_tangent = Some(d);
|
||||
s.fit_opts.end_tangent = Some(d);
|
||||
Some(s)
|
||||
}
|
||||
|
||||
/// Global interpolation: one control point per fit point plus one per end-derivative
|
||||
@@ -501,9 +676,13 @@ fn kinked_fit(fit: &[Vec2], closed: bool, opts: FitOptions) -> Option<Spline> {
|
||||
// Ends of an open curve are corners anyway, so only interior kinks count.
|
||||
let interior = |i: usize| closed || (i > 0 && i + 1 < n);
|
||||
let first = (0..n).find(|i| kink.get(*i).copied().unwrap_or(false) && interior(*i))?;
|
||||
let mut stored = fit.to_vec();
|
||||
if closed {
|
||||
pts.rotate_left(first);
|
||||
kink.rotate_left(first);
|
||||
// The curve starts at its first kink, so the fit points do too (each kink given twice):
|
||||
// a closed spline starts at its first fit point, which DXF and refits rely on.
|
||||
stored = pts.iter().zip(&kink).flat_map(|(q, k)| std::iter::repeat_n(*q, if *k { 2 } else { 1 })).collect();
|
||||
pts.push(*pts.first()?);
|
||||
kink.push(true);
|
||||
}
|
||||
@@ -539,7 +718,7 @@ fn kinked_fit(fit: &[Vec2], closed: bool, opts: FitOptions) -> Option<Spline> {
|
||||
control.extend(piece.control.iter().skip(usize::from(j > 0)).copied());
|
||||
at += len / total.max(1e-300);
|
||||
}
|
||||
let s = Spline { degree: p, knots, control, fit: fit.to_vec(), closed, ..Spline::default() };
|
||||
let s = Spline { degree: p, knots, control, fit: stored, closed, ..Spline::default() };
|
||||
s.is_valid().then_some(s)
|
||||
}
|
||||
|
||||
@@ -656,7 +835,7 @@ fn periodic_least_squares(pts: &[Vec2], t: &[f64], m: usize, p: usize) -> Option
|
||||
}
|
||||
|
||||
#[expect(clippy::many_single_char_names, reason = "Closed interpolation keeps the NURBS Book parameter, degree and matrix notation.")]
|
||||
fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> Spline {
|
||||
fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64, tangent: Option<Vec2>) -> Spline {
|
||||
let mut pts = fit.to_vec();
|
||||
if pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
|
||||
pts.pop();
|
||||
@@ -683,6 +862,13 @@ fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> Spline {
|
||||
{
|
||||
return s;
|
||||
}
|
||||
// Interpolation: AutoCAD's with chord-length knots, also when the tolerance is too small to
|
||||
// approximate with (AutoCAD writes 44 = 1e-10 for none).
|
||||
if kind == KnotParam::Chord
|
||||
&& let Some(s) = chord_closed(&pts, tangent)
|
||||
{
|
||||
return s;
|
||||
}
|
||||
let m = n + p;
|
||||
let knots = periodic_knots(&t, n, p);
|
||||
// Interpolation at t_i; control index k and k + n are the same unknown.
|
||||
@@ -717,7 +903,9 @@ mod tests {
|
||||
|
||||
fn passes_through(s: &Spline, fit: &[Vec2], tol: f64) -> bool {
|
||||
let u = params(fit, s.fit_opts.knots, s.closed);
|
||||
fit.iter().zip(&u).all(|(f, t)| s.eval(*t).dist(*f) < tol)
|
||||
// The parameters run over the spline's domain (chord-length knots are not normalised).
|
||||
let (lo, hi) = s.domain();
|
||||
fit.iter().zip(&u).all(|(f, t)| s.eval(lo + t * (hi - lo)).dist(*f) < tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -746,6 +934,8 @@ mod tests {
|
||||
for k in KnotParam::ALL {
|
||||
let s = Spline::fit_with(&fit, true, FitOptions { knots: k, ..FitOptions::default() });
|
||||
assert!(s.is_valid() && s.is_periodic() && passes_through(&s, &fit, 1e-3), "closed {k:?}");
|
||||
// Chord-length knots are clamped, as AutoCAD 2024 builds them; the others wrap round.
|
||||
assert_eq!(s.wraps(), k != KnotParam::Chord, "closed {k:?}");
|
||||
assert_eq!(s.infer_knot_param(), k);
|
||||
}
|
||||
}
|
||||
@@ -764,9 +954,11 @@ mod tests {
|
||||
let end = (s.eval(hi) - s.eval(hi - h)).normalized();
|
||||
assert!(start.near(Vec2::new(0.0, 1.0), 1e-4), "{start:?}");
|
||||
assert!(end.near(Vec2::new(1.0, -1.0).normalized(), 1e-4), "{end:?}");
|
||||
// One tangent only, and two fit points with tangents (a cubic Bezier).
|
||||
// One tangent only: the other end has no curvature, so still two control points more
|
||||
// than fit points (as AutoCAD 2024 builds it, `chord_fits_match_autocad_2024`); and two
|
||||
// fit points with tangents (a cubic Bezier).
|
||||
let one = Spline::fit_with(&fit, false, FitOptions { start_tangent: Some(Vec2::Y), ..FitOptions::default() });
|
||||
assert!(one.is_valid() && one.control.len() == fit.len() + 1 && passes_through(&one, &fit, 1e-3));
|
||||
assert!(one.is_valid() && one.control.len() == fit.len() + 2 && passes_through(&one, &fit, 1e-3));
|
||||
let two = [Vec2::ZERO, Vec2::new(4.0, 0.0)];
|
||||
let b = Spline::fit_with(
|
||||
&two,
|
||||
@@ -774,9 +966,309 @@ mod tests {
|
||||
FitOptions { start_tangent: Some(Vec2::Y), end_tangent: Some(Vec2::new(0.0, -1.0)), ..FitOptions::default() },
|
||||
);
|
||||
assert!(b.is_valid() && b.degree == 3 && b.control.len() == 4);
|
||||
assert!(b.eval(0.5).y > 0.5, "the tangents bow the curve up");
|
||||
// Closed curves ignore tangents.
|
||||
assert_eq!(Spline::fit_with(&fit, true, opts).fit_opts.start_tangent, None);
|
||||
let (blo, bhi) = b.domain();
|
||||
assert!(b.eval((blo + bhi) / 2.0).y > 0.5, "the tangents bow the curve up");
|
||||
// A new closed curve ignores the tangents given: with chord-length knots it keeps its own
|
||||
// where it closes, with periodic knots none. A refit (a stored tangent) takes the start
|
||||
// one at both ends.
|
||||
let own = Spline::fit_with(&fit, true, FitOptions::default());
|
||||
let c = Spline::fit_with(&fit, true, opts);
|
||||
assert_eq!(c, own);
|
||||
let u = Spline::fit_with(&fit, true, FitOptions { knots: KnotParam::Uniform, ..opts });
|
||||
assert_eq!((u.fit_opts.start_tangent, u.fit_opts.end_tangent), (None, None));
|
||||
let r = Spline::fit_with_end_derivatives(&fit, true, FitOptions { start_tangent: Some(Vec2::Y), ..FitOptions::default() });
|
||||
let (lo, hi) = r.domain();
|
||||
assert_eq!((r.fit_opts.start_tangent, r.fit_opts.end_tangent), (Some(Vec2::Y), Some(Vec2::Y)));
|
||||
assert!(r.derivative(lo).near(Vec2::Y, 1e-9) && r.derivative(hi).near(Vec2::Y, 1e-9) && r.is_periodic());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chord_fits_match_autocad_2024() {
|
||||
// The control points AutoCAD 2024 builds (accoreconsole, `entget`) for a SPLINE stored
|
||||
// with these fit points only, with a start tangent (0, 1) only and with an end tangent
|
||||
// (0.6, -0.8) only. The knots are the running chord length, not normalised, with the fit
|
||||
// points' own as the interior ones; an end without a tangent has no second derivative.
|
||||
let fit = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(8.0, 2.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
|
||||
let none = [
|
||||
(0.0, 0.0),
|
||||
(1.382372321772683, -0.2385675034006123),
|
||||
(4.310283884394332, -0.7438615842143153),
|
||||
(7.681946892002376, 3.278160343960215),
|
||||
(12.35784449278344, -0.2891721570669931),
|
||||
(14.110931758619, 2.556721307187103),
|
||||
(15.0, 4.0),
|
||||
];
|
||||
let start = [
|
||||
(0.0, 0.0),
|
||||
(0.0, 1.3333333333333002),
|
||||
(5.032653247327764, -1.5652705405003644),
|
||||
(7.49793879823205, 3.4873966488309946),
|
||||
(12.40378970003823, -0.34141662738096556),
|
||||
(14.12639202373297, 2.539141380790994),
|
||||
(15.0, 4.0),
|
||||
];
|
||||
let end = [
|
||||
(0.0, 0.0),
|
||||
(1.381988814451124, -0.2629235571276922),
|
||||
(4.309088095530778, -0.8198045875666935),
|
||||
(7.687216672987758, 3.6128373151524897),
|
||||
(12.33964126060851, -1.445235877194591),
|
||||
(14.15147186257614, 5.131370849898474),
|
||||
(15.0, 4.0),
|
||||
];
|
||||
let chords: Vec<f64> = fit.windows(2).map(|w| w[0].dist(w[1])).collect();
|
||||
let interior = [chords[0], chords[0] + chords[1], chords[0] + chords[1] + chords[2]];
|
||||
let total: f64 = chords.iter().sum();
|
||||
let cases = [
|
||||
(FitOptions::default(), none),
|
||||
(FitOptions { start_tangent: Some(Vec2::Y), ..FitOptions::default() }, start),
|
||||
(FitOptions { end_tangent: Some(Vec2::new(0.6, -0.8)), ..FitOptions::default() }, end),
|
||||
];
|
||||
for (opts, want) in cases {
|
||||
let s = Spline::fit_with(&fit, false, opts);
|
||||
assert_eq!(s.control.len(), want.len());
|
||||
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)), "{:?}", s.control);
|
||||
assert_eq!(s.knots.len(), 11);
|
||||
assert!(s.knots[..4].iter().all(|k| *k == 0.0) && s.knots[7..].iter().all(|k| (k - total).abs() < 1e-12));
|
||||
assert!(s.knots[4..7].iter().zip(interior).all(|(k, w)| (k - w).abs() < 1e-12), "{:?}", s.knots);
|
||||
}
|
||||
// Two fit points, drawn with SPLINE: a cubic with its control points at the thirds and
|
||||
// knots 0 and the length, four times each (AutoCAD 2024's `entget`).
|
||||
let two = [Vec2::new(-0.7167548102689167, -5.126502360792934), Vec2::new(0.039252452435714846, 5.571959062465009)];
|
||||
let s = Spline::fit_with(&two, false, FitOptions::default());
|
||||
let want = [
|
||||
(-0.7167548102689167, -5.126502360792933),
|
||||
(-0.4647523893673729, -1.560348553040286),
|
||||
(-0.212749968465829, 2.005805254712361),
|
||||
(0.03925245243571484, 5.571959062465008),
|
||||
];
|
||||
assert!(s.degree == 3 && s.control.len() == 4, "{s:?}");
|
||||
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)), "{:?}", s.control);
|
||||
let length = 10.72513980357368;
|
||||
assert!(
|
||||
s.knots.len() == 8 && s.knots[..4].iter().all(|k| *k == 0.0) && s.knots[4..].iter().all(|k| (k - length).abs() < 1e-9),
|
||||
"{:?}",
|
||||
s.knots
|
||||
);
|
||||
// A fit tolerance makes no difference to two points: AutoCAD 2024 with Fit tolerance 1
|
||||
// from (0,0) to (10,5) has the same cubic, control points at the thirds, knots 0 and √125.
|
||||
let two = [Vec2::ZERO, Vec2::new(10.0, 5.0)];
|
||||
let s = Spline::fit_with(&two, false, FitOptions { tolerance: 1.0, ..FitOptions::default() });
|
||||
let want = [(0.0, 0.0), (10.0 / 3.0, 5.0 / 3.0), (20.0 / 3.0, 10.0 / 3.0), (10.0, 5.0)];
|
||||
assert!(s.degree == 3 && s.control.len() == 4, "{s:?}");
|
||||
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)), "{:?}", s.control);
|
||||
let length = 125f64.sqrt();
|
||||
assert!(
|
||||
s.knots.len() == 8 && s.knots[..4].iter().all(|k| *k == 0.0) && s.knots[4..].iter().all(|k| (k - length).abs() < 1e-9),
|
||||
"{:?}",
|
||||
s.knots
|
||||
);
|
||||
assert_eq!(s.fit_opts.tolerance, 1.0);
|
||||
// The same curve as without a tolerance.
|
||||
let exact = Spline::fit_with(&two, false, FitOptions::default());
|
||||
assert_eq!((&s.control, &s.knots, s.degree), (&exact.control, &exact.knots, exact.degree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_chord_fits_match_autocad_2024() {
|
||||
// The control points and knots AutoCAD 2024 builds for SPLINE through these points and
|
||||
// Close (accoreconsole, `entget`, the default tangent): the open chord-length cubic through
|
||||
// the points and back to the first, clamped, with the same unit tangent at both ends. That
|
||||
// tangent comes from the first four points of the loop only: the last two cases share it.
|
||||
let a4 = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0)];
|
||||
let b3 = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
|
||||
let c5 = [a4[0], a4[1], a4[2], a4[3], Vec2::new(-2.0, 2.0)];
|
||||
let c5b = [a4[0], a4[1], a4[2], a4[3], Vec2::new(-1.0, 1.0)];
|
||||
let cases: [(&[Vec2], &[(f64, f64)], (f64, f64)); 4] = [
|
||||
(
|
||||
&a4,
|
||||
&[
|
||||
(0.0, 0.0),
|
||||
(0.9768273968569969, -0.9075163990404586),
|
||||
(4.110440110427768, -0.7122257786209955),
|
||||
(7.696509078097733, 3.854015801004462),
|
||||
(0.3665121443407813, 5.739691001923484),
|
||||
(-1.006890633809635, 0.9354464925559993),
|
||||
(0.0, 0.0),
|
||||
],
|
||||
(0.7326205476427477, -0.6806372992803439),
|
||||
),
|
||||
(
|
||||
&b3,
|
||||
&[
|
||||
(0.0, 0.0),
|
||||
(1.175326912235153, -0.6295906822321484),
|
||||
(5.619959780685314, -1.4331768242180658),
|
||||
(2.310179647706573, 5.2420172430121),
|
||||
(-1.059425361874152, 0.567505371835594),
|
||||
(0.0, 0.0),
|
||||
],
|
||||
(0.8814951841763651, -0.4721930116741209),
|
||||
),
|
||||
(
|
||||
&c5,
|
||||
&[
|
||||
(0.0, 0.0),
|
||||
(0.9768273968569857, -0.9075163990405031),
|
||||
(4.161096925358192, -0.7652522140755877),
|
||||
(7.509998209072992, 4.049251260863201),
|
||||
(1.553476197327273, 4.730697783233012),
|
||||
(-3.373822964706317, 2.2285807243904117),
|
||||
(-0.6907212763663778, 0.6417109997994999),
|
||||
(0.0, 0.0),
|
||||
],
|
||||
(0.7326205476427394, -0.6806372992803528),
|
||||
),
|
||||
(
|
||||
&c5b,
|
||||
&[
|
||||
(0.0, 0.0),
|
||||
(0.9768273968569822, -0.9075163990405031),
|
||||
(4.136366708588512, -0.7312571003463972),
|
||||
(7.601051194287697, 3.9240863010656994),
|
||||
(1.118388923026953, 5.328785600648075),
|
||||
(-1.947013227175678, 1.4046091221343886),
|
||||
(-0.3453606381831876, 0.3208554998997215),
|
||||
(0.0, 0.0),
|
||||
],
|
||||
(0.7326205476427366, -0.6806372992803559),
|
||||
),
|
||||
];
|
||||
for (fit, want, tangent) in cases {
|
||||
let s = Spline::fit_with(fit, true, FitOptions::default());
|
||||
assert!(s.is_valid() && s.closed && s.degree == 3, "{s:?}");
|
||||
assert_eq!(s.control.len(), want.len());
|
||||
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(*x, *y), 1e-9)), "{:?}", s.control);
|
||||
// Knots: zeros, the running chord length round the loop at the fit points after the
|
||||
// first, and its total four times.
|
||||
let mut run = vec![0.0];
|
||||
for (a, b) in fit.iter().zip(fit.iter().skip(1).chain([&fit[0]])) {
|
||||
run.push(run.last().unwrap() + a.dist(*b));
|
||||
}
|
||||
let total = *run.last().unwrap();
|
||||
let want_knots: Vec<f64> = [0.0; 3].into_iter().chain(run[..fit.len()].iter().copied()).chain([total; 4]).collect();
|
||||
assert_eq!(s.knots.len(), want_knots.len());
|
||||
assert!(s.knots.iter().zip(&want_knots).all(|(k, w)| (k - w).abs() < 1e-12), "{:?}", s.knots);
|
||||
// The tangent where it closes is the first derivative at both ends, so the curve is
|
||||
// periodic (smooth where it closes) with clamped knots.
|
||||
let (lo, hi) = s.domain();
|
||||
let d = Vec2::new(tangent.0, tangent.1);
|
||||
assert!(s.derivative(lo).near(d, 1e-9) && s.derivative(hi).near(d, 1e-9), "{:?} {:?}", s.derivative(lo), s.derivative(hi));
|
||||
assert!(s.is_periodic() && !s.wraps());
|
||||
assert!(s.fit_opts.start_tangent.is_some_and(|t| t.near(d, 1e-12)) && s.fit_opts.end_tangent == s.fit_opts.start_tangent);
|
||||
assert_eq!(s.fit, fit, "the first fit point is not repeated");
|
||||
assert_eq!(s.infer_knot_param(), KnotParam::Chord);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_splines_keep_their_closing_tangent_as_in_autocad() {
|
||||
// AutoCAD 2024 (accoreconsole, `entget`) on SPLINE (0,0) (4,0) (6,3) (1,4) Close: its
|
||||
// tangent where it closes, D, stays 12 and 13 through edits; here it stays both end
|
||||
// tangents.
|
||||
let fit = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0)];
|
||||
let s = Spline::fit_with(&fit, true, FitOptions::default());
|
||||
let d = Vec2::new(0.7326205476427478, -0.6806372992803439);
|
||||
let near = |a: &[Vec2], b: &[(f64, f64)]| a.len() == b.len() && a.iter().zip(b).all(|(p, (x, y))| p.near(Vec2::new(*x, *y), 1e-9));
|
||||
assert!(s.fit_opts.start_tangent.is_some_and(|t| t.near(d, 1e-12)) && s.fit_opts.end_tangent == s.fit_opts.start_tangent);
|
||||
// SPLINEDIT Fit data Move of (1, 4) to (1, 5) keeps D, though the first four points of the
|
||||
// loop, which give a new spline its tangent, change.
|
||||
let up = Vec2::new(1.0, 5.0);
|
||||
let moved = s.refit(&[fit[0], fit[1], fit[2], up], true);
|
||||
let want = [
|
||||
(0.0, 0.0),
|
||||
(0.9768273968569969, -0.9075163990404586),
|
||||
(4.139797324573113, -0.6528392109186482),
|
||||
(7.666093574908103, 3.731946546410586),
|
||||
(-0.03708934486751076, 7.208547566545824),
|
||||
(-1.245215489496467, 1.156860956903188),
|
||||
(0.0, 0.0),
|
||||
];
|
||||
assert!(near(&moved.control, &want), "{:?}", moved.control);
|
||||
assert!(moved.fit_opts.start_tangent.is_some_and(|t| t.near(d, 1e-12)));
|
||||
// REVERSE: the seam stays the first fit point, the others turn round, and so does D.
|
||||
let r = s.reversed();
|
||||
assert_eq!(r.fit, [fit[0], fit[3], fit[2], fit[1]]);
|
||||
assert!(r.fit_opts.start_tangent.is_some_and(|t| t.near(-d, 1e-12)) && r.fit_opts.end_tangent == r.fit_opts.start_tangent);
|
||||
let want = [
|
||||
(0.0, 0.0),
|
||||
(-1.006890633809634, 0.9354464925559991),
|
||||
(0.3665121443407817, 5.739691001923484),
|
||||
(7.696509078097734, 3.854015801004462),
|
||||
(4.110440110427767, -0.7122257786209955),
|
||||
(0.9768273968569975, -0.907516399040459),
|
||||
(0.0, 0.0),
|
||||
];
|
||||
assert!(near(&r.control, &want), "{:?}", r.control);
|
||||
let knots = [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
4.12310562561766,
|
||||
9.222125139210444,
|
||||
12.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
];
|
||||
assert!(r.knots.len() == knots.len() && r.knots.iter().zip(knots).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", r.knots);
|
||||
// ... and a move after it keeps the turned tangent: the moved curve, reversed.
|
||||
let rm = r.refit(&[fit[0], up, fit[2], fit[1]], true);
|
||||
let want = [
|
||||
(0.0, 0.0),
|
||||
(-1.245215489496467, 1.156860956903188),
|
||||
(-0.03708934486751225, 7.208547566545823),
|
||||
(7.666093574908103, 3.731946546410587),
|
||||
(4.139797324573113, -0.6528392109186484),
|
||||
(0.9768273968569966, -0.9075163990404583),
|
||||
(0.0, 0.0),
|
||||
];
|
||||
assert!(near(&rm.control, &want), "{:?}", rm.control);
|
||||
// SPLINEDIT Fit data Delete keeps D too, even of the first fit point, where the curve then
|
||||
// closes at the next one.
|
||||
let want = [
|
||||
(4.0, 0.0),
|
||||
(4.880500316661478, -0.8180242275162029),
|
||||
(8.321543841772677, 4.998519358162528),
|
||||
(-2.146496779397366, 4.974687083605885),
|
||||
(2.778965753928753, 1.134395498800573),
|
||||
(4.0, 0.0),
|
||||
];
|
||||
assert!(near(&s.refit(&fit[1..], true).control, &want));
|
||||
let want = [
|
||||
(0.0, 0.0),
|
||||
(0.9768273968569969, -0.9075163990404586),
|
||||
(6.486660720359312, -1.195604109659142),
|
||||
(0.6839072671675914, 6.97368772380304),
|
||||
(-1.006890633809635, 0.9354464925559993),
|
||||
(0.0, 0.0),
|
||||
];
|
||||
assert!(near(&s.refit(&[fit[0], fit[1], fit[3]], true).control, &want));
|
||||
// SPLINEDIT Open keeps the fit points and D as both end tangents.
|
||||
let o = s.refit(&fit, false);
|
||||
let want = [
|
||||
(0.0, 0.0),
|
||||
(0.9768273968569969, -0.9075163990404586),
|
||||
(3.849239755252805, -0.7101778392295987),
|
||||
(8.658209992380792, 3.846475592325253),
|
||||
(-0.2452154894964675, 5.156860956903188),
|
||||
(1.0, 4.0),
|
||||
];
|
||||
assert!(near(&o.control, &want), "{:?}", o.control);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_closing_derivative_still_gives_a_tangent() {
|
||||
// A loop 1e-20 across: the derivative of the cubic through its first points is about
|
||||
// 1e-10 long, short enough for `normalized` to make it zero (a cusp where it closes).
|
||||
let ring = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0), Vec2::ZERO];
|
||||
let d = closing_tangent(&ring).unwrap();
|
||||
let small: Vec<Vec2> = ring.iter().map(|q| *q * 1e-20).collect();
|
||||
assert!(closing_tangent(&small).is_some_and(|t| t.near(d, 1e-12)), "{:?}", closing_tangent(&small));
|
||||
// Two points together give none.
|
||||
assert!(closing_tangent(&[Vec2::ZERO, Vec2::ZERO, Vec2::X, Vec2::Y]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -833,9 +1325,10 @@ mod tests {
|
||||
assert!(s.eval(lo).near(s.eval(hi), 1e-9), "still closed");
|
||||
assert_eq!(s.fit, fit);
|
||||
assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits());
|
||||
// Too tight a tolerance interpolates.
|
||||
// Too tight a tolerance interpolates, as AutoCAD 2024 builds the closed spline (the curve
|
||||
// without a tolerance, which keeps the one asked for).
|
||||
let tiny = Spline::fit_with(&fit, true, FitOptions { tolerance: 1e-9, ..FitOptions::default() });
|
||||
assert_eq!(tiny.control.len(), exact.control.len());
|
||||
assert_eq!((&tiny.knots, &tiny.control, tiny.fit_opts.tolerance), (&exact.knots, &exact.control, 1e-9));
|
||||
// Every parametrisation approximates.
|
||||
for k in KnotParam::ALL {
|
||||
let s = Spline::fit_with(&fit, true, FitOptions { tolerance: tol, knots: k, ..FitOptions::default() });
|
||||
@@ -878,6 +1371,20 @@ mod tests {
|
||||
let (lo, hi) = s.domain();
|
||||
assert!(s.eval(lo).near(Vec2::ZERO, 1e-9) && s.eval(hi).near(Vec2::ZERO, 1e-9));
|
||||
assert!(c.iter().all(|q| on_curve(&s, *q)));
|
||||
// A kink further on: the curve starts there, and so do its fit points (the seam is the
|
||||
// first fit point, which DXF and refits take it to be), also once reversed.
|
||||
let k = Vec2::new(4.0, 0.0);
|
||||
let c = [Vec2::ZERO, k, k, Vec2::new(4.0, 4.0), Vec2::new(0.0, 4.0)];
|
||||
let s = Spline::fit_with(&c, true, FitOptions::default());
|
||||
assert_eq!(s.fit, [k, k, Vec2::new(4.0, 4.0), Vec2::new(0.0, 4.0), Vec2::ZERO]);
|
||||
let (lo, hi) = s.domain();
|
||||
assert!(s.eval(lo).near(k, 1e-9) && s.eval(hi).near(k, 1e-9));
|
||||
assert_eq!(s.refit(&s.fit, true).control, s.control, "a refit gives the same curve");
|
||||
let r = s.reversed();
|
||||
assert_eq!(r.fit, [k, k, Vec2::ZERO, Vec2::new(0.0, 4.0), Vec2::new(4.0, 4.0)]);
|
||||
let (rlo, rhi) = r.domain();
|
||||
let again = r.refit(&r.fit, true);
|
||||
assert!(again.eval(again.domain().0).near(k, 1e-9) && (0..=8).all(|i| on_curve(&again, r.eval(rlo + (rhi - rlo) * i as f64 / 8.0))));
|
||||
// Kinks at the ends of an open curve change nothing.
|
||||
let e = [Vec2::ZERO, Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(4.0, 0.0)];
|
||||
let plain = Spline::fit_with(&e[1..], false, FitOptions::default());
|
||||
@@ -915,6 +1422,19 @@ mod tests {
|
||||
}
|
||||
let tight: Vec<Vec2> = (0..8).map(|i| Vec2::new(f64::from(i) * 1e-13, 0.0)).collect();
|
||||
let _ = Spline::fit_with(&tight, true, FitOptions { tolerance: 1.0, ..FitOptions::default() });
|
||||
// A file's tangent keeps its length, however extreme.
|
||||
let kept = Spline::fit_with_end_derivatives(&fit, false, bad);
|
||||
assert!(kept.is_valid() && kept.fit_opts.start_tangent.is_none() && kept.fit_opts.end_tangent.is_none());
|
||||
for len in [1e-11, 1e150, 1e308, f64::MAX] {
|
||||
for knots in KnotParam::ALL {
|
||||
for tolerance in [0.0, 0.5] {
|
||||
let t = Some(Vec2::new(len, -len));
|
||||
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { knots, start_tangent: t, end_tangent: t, tolerance });
|
||||
s.transform(&Mat3::scale(2.0, 0.5));
|
||||
let _ = s.refit(&fit, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Above the interpolation cap the fit points become control points instead of a dense
|
||||
@@ -951,6 +1471,87 @@ mod tests {
|
||||
s.transform(&Mat3::rotate(std::f64::consts::FRAC_PI_2));
|
||||
assert!(s.fit_opts.start_tangent.is_some_and(|t| t.near(Vec2::Y, 1e-12)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_tangent_keeps_its_length_through_edits_as_in_autocad() {
|
||||
// AutoCAD 2024 (accoreconsole) on a SPLINE stored with these fit points and 12 = (0, 3).
|
||||
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(8.0, 2.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
|
||||
let t0 = Some(Vec2::new(0.0, 3.0));
|
||||
let s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: t0, ..FitOptions::default() });
|
||||
// SPLINEDIT Fit data Move of the third fit point to (8, 3) refits with (0, 3) as stored.
|
||||
let moved = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(8.0, 3.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
|
||||
let r = s.refit(&moved, false);
|
||||
let autocad = [
|
||||
(0.0, 0.0),
|
||||
(0.0, 4.0),
|
||||
(5.412665758603298, -3.5553537661153),
|
||||
(7.3671281655678, 5.7160776616114),
|
||||
(12.24746922455167, -0.8468238208691),
|
||||
(14.09874022239649, 2.4130068961106),
|
||||
(15.0, 4.0),
|
||||
];
|
||||
assert_eq!(r.control.len(), autocad.len());
|
||||
for (c, (x, y)) in r.control.iter().zip(autocad) {
|
||||
assert!(c.near(Vec2::new(x, y), 1e-9), "{c:?} vs ({x}, {y})");
|
||||
}
|
||||
assert_eq!(r.fit_opts.start_tangent, t0);
|
||||
// MOVE, ROTATE 90, SCALE 2 and MIRROR about y = x turn 12 and keep its length, so a refit
|
||||
// of the moved fit points gives the moved curve.
|
||||
for (m, t) in [
|
||||
(Mat3::translate(Vec2::new(10.0, 0.0)), Vec2::new(0.0, 3.0)),
|
||||
(Mat3::rotate(std::f64::consts::FRAC_PI_2), Vec2::new(-3.0, 0.0)),
|
||||
(Mat3::scale(2.0, 2.0), Vec2::new(0.0, 3.0)),
|
||||
(Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)), Vec2::new(3.0, 0.0)),
|
||||
] {
|
||||
let mut e = s.clone();
|
||||
e.transform(&m);
|
||||
assert!(e.fit_opts.start_tangent.is_some_and(|v| v.near(t, 1e-12)), "{:?} vs {t:?}", e.fit_opts.start_tangent);
|
||||
let again = e.refit(&e.fit, false);
|
||||
assert!(again.control.iter().zip(&e.control).all(|(a, b)| a.near(*b, 1e-9)), "{:?} vs {:?}", again.control, e.control);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_tangents_are_no_zero_directions() {
|
||||
let fit = pts();
|
||||
// A direction too short to scale to a unit is no tangent, not a zero one.
|
||||
let short = Some(Vec2::new(0.0, 1e-10));
|
||||
let s = Spline::fit_with(&fit, false, FitOptions { start_tangent: short, end_tangent: short, ..FitOptions::default() });
|
||||
assert_eq!((s.fit_opts.start_tangent, s.fit_opts.end_tangent), (None, None));
|
||||
// A file's short tangent is kept, and a transform turns it rather than dropping it.
|
||||
let mut f = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: short, ..FitOptions::default() });
|
||||
assert_eq!(f.fit_opts.start_tangent, short);
|
||||
f.transform(&Mat3::rotate(std::f64::consts::FRAC_PI_2));
|
||||
assert!(f.fit_opts.start_tangent.is_some_and(|t| t.near(Vec2::new(-1e-10, 0.0), 1e-24)), "{:?}", f.fit_opts.start_tangent);
|
||||
// A map that flattens its direction drops it.
|
||||
f.transform(&Mat3::scale(0.0, 1.0));
|
||||
assert_eq!(f.fit_opts.start_tangent, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_uniform_scale_keeps_the_tangent_and_a_singular_map_drops_it() {
|
||||
let fit = pts();
|
||||
let t = Some(Vec2::new(100.0, 0.0));
|
||||
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: t, ..FitOptions::default() });
|
||||
// Invertible, however small: the tangent stays, with its length.
|
||||
s.transform(&Mat3::scale(1e-10, 1e-10));
|
||||
assert!(s.fit_opts.start_tangent.is_some_and(|v| v.near(Vec2::new(100.0, 0.0), 1e-9)), "{:?}", s.fit_opts.start_tangent);
|
||||
// A singular map that flattens the direction to rounding noise (0.1 + 0.2 - 0.3) drops it.
|
||||
let flat = Some(Vec2::new(0.1 + 0.2, -0.3));
|
||||
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: flat, ..FitOptions::default() });
|
||||
s.transform(&Mat3 { a: 1.0, b: 1.0, c: 1.0, d: 1.0, e: 0.0, f: 0.0 });
|
||||
assert_eq!(s.fit_opts.start_tangent, None);
|
||||
// So does one that squashes it to under 1e-9 of its largest axis scale, along either axis.
|
||||
for (t, m) in [(Vec2::new(0.0, 3.0), Mat3::scale(1.0, 1e-12)), (Vec2::new(3.0, 0.0), Mat3::scale(1e-12, 1.0))] {
|
||||
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: Some(t), ..FitOptions::default() });
|
||||
s.transform(&m);
|
||||
assert_eq!(s.fit_opts.start_tangent, None, "{t:?}");
|
||||
}
|
||||
// A turned length that overflows gives no tangent rather than NaN.
|
||||
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: Some(Vec2::new(1e10, 0.0)), ..FitOptions::default() });
|
||||
s.transform(&Mat3::scale(1e300, 1e300));
|
||||
assert_eq!(s.fit_opts.start_tangent, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -175,7 +175,7 @@ fn spline_interpolates_fit_points() {
|
||||
assert!(d < 0.05, "fit point {f:?} missed by {d}");
|
||||
}
|
||||
assert!(s.eval(0.0).near(fit[0], 1e-9));
|
||||
assert!(s.eval(1.0).near(fit[4], 1e-9));
|
||||
assert!(s.eval(s.domain().1).near(fit[4], 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -201,6 +201,62 @@ fn closed_spline_is_smooth_at_the_seam() {
|
||||
assert_eq!(Spline::from_fit_points_closed(&dup).fit.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periodic_means_the_same_derivative_where_it_closes() {
|
||||
// AutoCAD 2024 sets group 70 bit 2 from the curve: its closed fit spline through (0,0)
|
||||
// (4,0) (6,3) (1,4), made again without fit data, keeps it with clamped knots; with the
|
||||
// second control point moved along the first leg (the same direction, twice as long), or
|
||||
// across it by a fraction of its length, it drops it (accoreconsole, `entmake` + `entget`;
|
||||
// AutoCAD drops it from 1e-11).
|
||||
let control = vec![
|
||||
Vec2::new(0.0, 0.0),
|
||||
Vec2::new(0.9768273968569969, -0.9075163990404586),
|
||||
Vec2::new(4.110440110427768, -0.7122257786209955),
|
||||
Vec2::new(7.696509078097733, 3.854015801004462),
|
||||
Vec2::new(0.3665121443407813, 5.739691001923484),
|
||||
Vec2::new(-1.006890633809635, 0.9354464925559993),
|
||||
Vec2::new(0.0, 0.0),
|
||||
];
|
||||
let knots = vec![
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
4.0,
|
||||
7.605551275463989,
|
||||
12.70457078905677,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
];
|
||||
let s = Spline { degree: 3, knots, control, closed: true, ..Spline::default() };
|
||||
assert!(s.is_valid() && s.is_periodic() && !s.wraps());
|
||||
let leg = s.control[1] - s.control[0];
|
||||
let moved = |to: Vec2| {
|
||||
let mut m = s.clone();
|
||||
m.control[1] = to;
|
||||
m
|
||||
};
|
||||
assert!(!moved(s.control[0] + leg * 2.0).is_periodic(), "the same direction is not enough");
|
||||
let across = Vec2::new(-leg.y, leg.x) * 1e-7;
|
||||
assert!(!moved(s.control[1] + across).is_periodic());
|
||||
// The last two control points moved together: the same derivative, but the ends apart.
|
||||
let mut apart = s.clone();
|
||||
for c in &mut apart.control[5..] {
|
||||
*c += Vec2::new(0.0, 1e-3);
|
||||
}
|
||||
assert!(!apart.is_periodic(), "the ends must meet");
|
||||
assert!(!Spline { closed: false, ..s.clone() }.is_periodic(), "an open spline is not periodic");
|
||||
// Control points that wrap round (unclamped knots) are periodic too.
|
||||
let w = Spline::fit_with(
|
||||
&[Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)],
|
||||
true,
|
||||
crate::FitOptions { knots: crate::KnotParam::SqrtChord, ..Default::default() },
|
||||
);
|
||||
assert!(w.wraps() && w.is_periodic());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_points() {
|
||||
let e = Ellipse::full(Vec2::ZERO, Vec2::new(4.0, 0.0), 0.5);
|
||||
|
||||
@@ -251,10 +251,23 @@ impl LayerSet {
|
||||
}
|
||||
}
|
||||
|
||||
/// The position of the first layout of each name, so finding the layout of each of many objects
|
||||
/// is a map lookup rather than a scan of the layouts: a file of N layouts and N objects in the
|
||||
/// last of them read in N² name comparisons (#1924). The reader keeps the layouts' names and order
|
||||
/// while it fills them.
|
||||
pub(super) fn layout_positions(d: &Drawing) -> std::collections::BTreeMap<String, usize> {
|
||||
let mut at = std::collections::BTreeMap::new();
|
||||
for (i, l) in d.layouts.iter().enumerate() {
|
||||
at.entry(l.name.clone()).or_insert(i);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// Place the BLOCKS entities: model and paper space blocks go to their space, the rest become
|
||||
/// block definitions.
|
||||
pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx, paper_block_for: &HashMap<String, String>, first_layout: &str) {
|
||||
let mut layers = LayerSet::new(d);
|
||||
let layout_at = layout_positions(d);
|
||||
for (name, base, description, ents, xref) in blocks {
|
||||
let up = name.to_ascii_uppercase();
|
||||
if up == "*MODEL_SPACE" {
|
||||
@@ -265,8 +278,8 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx,
|
||||
continue;
|
||||
}
|
||||
if up.starts_with("*PAPER_SPACE") {
|
||||
let lname = paper_block_for.get(&up).cloned().unwrap_or_else(|| first_layout.to_string());
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
|
||||
let lname = paper_block_for.get(&up).map_or(first_layout, String::as_str);
|
||||
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
for (_, _, e) in ents {
|
||||
l.entities.push(e);
|
||||
}
|
||||
@@ -324,11 +337,12 @@ pub(super) fn place_entities(
|
||||
first_layout: &str,
|
||||
) {
|
||||
let mut layers = LayerSet::new(d);
|
||||
let layout_at = layout_positions(d);
|
||||
for (owner, paper, e) in entities {
|
||||
layers.ensure(d, &e.common.layer);
|
||||
match paper_layout(owner, paper, rx, paper_block_for, first_layout) {
|
||||
Some(lname) => {
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
|
||||
if let Some(l) = layout_at.get(&lname).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.entities.push(e);
|
||||
}
|
||||
}
|
||||
@@ -417,6 +431,7 @@ pub(super) fn apply_sortents(
|
||||
Some(if up.starts_with("*PAPER_SPACE") { paper_for.get(&up).cloned().unwrap_or_else(|| first_layout.to_string()) + "\0paper" } else { up })
|
||||
};
|
||||
let last: HashMap<String, usize> = tables.iter().enumerate().filter_map(|(i, (owner, _))| Some((target(owner)?, i))).collect();
|
||||
let layout_at = layout_positions(d);
|
||||
for (i, (owner, map)) in tables.iter().enumerate() {
|
||||
if target(owner).and_then(|t| last.get(&t)) != Some(&i) {
|
||||
continue;
|
||||
@@ -432,7 +447,7 @@ pub(super) fn apply_sortents(
|
||||
d.model.sort_by_key(key);
|
||||
} else if up.starts_with("*PAPER_SPACE") {
|
||||
let lname = paper_for.get(&up).map(String::as_str).unwrap_or(first_layout);
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
|
||||
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.entities.sort_by_key(key);
|
||||
}
|
||||
} else if let Some(b) = d.blocks.get_mut(name.as_str()) {
|
||||
|
||||
@@ -106,24 +106,47 @@ fn spline(t: &T) -> Spline {
|
||||
let knots = t.all_f(40);
|
||||
let control = t.pts(10);
|
||||
let weights = t.all_f(41);
|
||||
let fit = t.pts(11);
|
||||
let tangent = |c: i32| t.f(c).map(|_| t.p(c).xy());
|
||||
let fit_opts =
|
||||
cadcraft_geom::FitOptions { knots: Default::default(), start_tangent: tangent(12), end_tangent: tangent(13), tolerance: t.fd(44, 0.0) }
|
||||
.sanitized();
|
||||
let mut fit = t.pts(11);
|
||||
let closed = t.i(70).unwrap_or(0) & 1 != 0;
|
||||
// AutoCAD ends a closed spline's fit points with the first again; here it is implied.
|
||||
if closed && fit.len() > 3 && fit.first().zip(fit.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
|
||||
fit.pop();
|
||||
}
|
||||
let tangent = |c: i32| t.f(c).map(|_| t.p(c).xy());
|
||||
// AutoCAD writes no fit tolerance as 1e-10; read as a tolerance, an approximation could meet it.
|
||||
let tolerance = t.fd(44, 0.0);
|
||||
let tolerance = if tolerance <= 1e-10 { 0.0 } else { tolerance };
|
||||
// AutoCAD takes a 12/13 tangent with its length (for a closed spline, its tangent where it
|
||||
// closes), keeps it through fit-point edits and writes it back as it read it.
|
||||
let fit_opts = cadcraft_geom::FitOptions { knots: Default::default(), start_tangent: tangent(12), end_tangent: tangent(13), tolerance }
|
||||
.sanitized_keeping_length();
|
||||
let mut sp = Spline { degree, knots, control, weights, fit: fit.clone(), closed, fit_opts };
|
||||
if !sp.is_valid() && fit.len() >= 2 {
|
||||
sp = Spline::fit_with(&fit, sp.closed, fit_opts);
|
||||
sp = Spline::fit_with_end_derivatives(&fit, sp.closed, fit_opts);
|
||||
} else if !sp.is_valid() && sp.control.len() >= 2 {
|
||||
sp = Spline::from_control(sp.control.clone(), degree);
|
||||
} else if fit.len() >= 3 {
|
||||
// DXF keeps the knots, not how they were spaced: recover it for later refits.
|
||||
sp.fit_opts.knots = sp.infer_knot_param();
|
||||
}
|
||||
// The writer gives every closed spline its curve's tangents where it closes, but only one
|
||||
// built as AutoCAD's closed fit spline keeps them (as `Spline::fit_with` stores them); for the
|
||||
// others a refit takes none, before a save or after it.
|
||||
if sp.closed && !keeps_closing_tangent(&sp) {
|
||||
sp.fit_opts.start_tangent = None;
|
||||
sp.fit_opts.end_tangent = None;
|
||||
}
|
||||
sp
|
||||
}
|
||||
|
||||
/// A closed spline that keeps a tangent where it closes: AutoCAD's closed fit spline, with three
|
||||
/// fit points or more, no kink (a fit point twice in a row) and clamped knots (periodic knots,
|
||||
/// square-root, uniform or within a fit tolerance, wrap round).
|
||||
fn keeps_closing_tangent(sp: &Spline) -> bool {
|
||||
let kinked = sp.fit.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(a, b)| a.near(*b, 1e-12)));
|
||||
sp.fit.len() >= 3 && !kinked && !sp.wraps()
|
||||
}
|
||||
|
||||
pub(super) fn entity_with_table_budget(
|
||||
kind: &str,
|
||||
tags: &[Tag],
|
||||
|
||||
@@ -195,6 +195,7 @@ impl Objects {
|
||||
|
||||
/// Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset.
|
||||
fn apply_layout_ucss(&self, d: &mut Drawing, rx: &Rx) {
|
||||
let layout_at = super::document::layout_positions(d);
|
||||
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
|
||||
@@ -209,7 +210,7 @@ impl Objects {
|
||||
if !usable || (world && ucs_name.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
|
||||
if let Some(l) = layout_at.get(name).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.ucs = Some(Ucs { name: ucs_name, origin: *origin, x_axis: *x, y_axis: *y });
|
||||
}
|
||||
}
|
||||
@@ -348,8 +349,9 @@ impl Objects {
|
||||
}
|
||||
self.apply_mleader_styles(d, rx);
|
||||
crate::dxf_mleader::apply(d, &rx.mleader_fix, &self.names);
|
||||
let layout_at = super::document::layout_positions(d);
|
||||
for (name, view) in &self.layout_views {
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
|
||||
if let Some(l) = layout_at.get(name).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.view = Some(*view);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +114,11 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
// The same for linetypes (first definition wins) and text styles (last definition wins).
|
||||
let mut linetype_names: std::collections::HashSet<String> = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect();
|
||||
let mut style_index: HashMap<String, usize> = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
|
||||
// And for dimension styles (a later record replaces the first of its name, which keeps its
|
||||
// place); ordered by name rather than hashed, so its cost does not depend on hash keys. Built
|
||||
// in reverse, so the first style of a name is the one kept.
|
||||
let mut dim_style_index: std::collections::BTreeMap<String, usize> =
|
||||
d.dim_styles.iter().enumerate().rev().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
|
||||
for (kind, tg) in recs {
|
||||
let t = T(tg);
|
||||
match kind.as_str() {
|
||||
@@ -280,9 +285,12 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
fields.extend(crate::dxf_ext::read_newer_dimvars(tg, &rx.styles, &rx.brs, &rx.ltypes));
|
||||
let mut st = DimStyle { name: name.clone(), annotative: annotative(tg), ..DimStyle::default() };
|
||||
st.apply_fields(&fields);
|
||||
match d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(&name)) {
|
||||
match dim_style_index.get(&name.to_ascii_lowercase()).and_then(|&i| d.dim_styles.get_mut(i)) {
|
||||
Some(x) => *x = st,
|
||||
None => d.dim_styles.push(st),
|
||||
None => {
|
||||
dim_style_index.insert(name.to_ascii_lowercase(), d.dim_styles.len());
|
||||
d.dim_styles.push(st);
|
||||
}
|
||||
}
|
||||
}
|
||||
"VPORT" => vport_record(d, &t, false),
|
||||
|
||||
@@ -156,17 +156,23 @@ pub fn tags(d: &Drawing, version: Version) -> Vec<Tag> {
|
||||
|
||||
/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing.
|
||||
fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::HashSet<cadcraft_doc::Handle>) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
|
||||
let (mut tags, kept, _) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
|
||||
// Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads
|
||||
// them in the layout of the DWG they came from.
|
||||
proxy::proxy_layout(&mut tags, version);
|
||||
(tags, kept)
|
||||
}
|
||||
|
||||
/// The most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in
|
||||
/// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256),
|
||||
/// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so).
|
||||
pub const DWG_MAX_LINETYPE_ELEMENTS: usize = 255;
|
||||
|
||||
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
|
||||
/// version's (MULTILEADER from 2007).
|
||||
/// version's (MULTILEADER from 2007), and its linetypes have at most
|
||||
/// [`DWG_MAX_LINETYPE_ELEMENTS`] elements.
|
||||
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true);
|
||||
let (mut tags, kept, _) = sections::tags_kept_for(d, Version::R2000, dwg, false, true);
|
||||
let mut unwritten = craft_dwg::Unwritten::new();
|
||||
if dwg == Version::R2007 {
|
||||
let omitted = legacy_visualstyles_kept(d, &kept);
|
||||
@@ -186,7 +192,7 @@ pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwri
|
||||
pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
|
||||
let mut lost = craft_dwg::Unwritten::new();
|
||||
if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) {
|
||||
let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true);
|
||||
let (_, kept, _) = sections::tags_kept_for(d, Version::R2000, version, false, true);
|
||||
let omitted = legacy_visualstyles_kept(d, &kept);
|
||||
if omitted != 0 {
|
||||
lost.insert("VISUALSTYLE".into(), omitted);
|
||||
@@ -195,6 +201,24 @@ pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
|
||||
lost
|
||||
}
|
||||
|
||||
/// What a DWG keeps of `d` only in part, as notes for the user: one counting the linetypes with
|
||||
/// more dash elements than a DWG counts, which it saves with their first
|
||||
/// [`DWG_MAX_LINETYPE_ELEMENTS`]. Empty when the DWG keeps every linetype whole.
|
||||
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
|
||||
let max = DWG_MAX_LINETYPE_ELEMENTS;
|
||||
if d.linetypes.iter().all(|l| l.pattern.len() <= max) {
|
||||
return Vec::new();
|
||||
}
|
||||
// The writer decides which linetypes the file holds (an xref's own only when a layer uses
|
||||
// them), so it does the counting; the LTYPE table is the same in every DWG version.
|
||||
let (_, _, cut) = sections::tags_kept_for(d, Version::R2000, Version::R2004, false, true);
|
||||
match cut {
|
||||
0 => Vec::new(),
|
||||
1 => vec![format!("DWG: 1 linetype has more than {max} dash elements; only its first {max} were saved.")],
|
||||
n => vec![format!("DWG: {n} linetypes have more than {max} dash elements; only the first {max} of each were saved.")],
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet<cadcraft_doc::Handle>) -> usize {
|
||||
d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count()
|
||||
}
|
||||
|
||||
@@ -215,20 +215,34 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
w.s(0, "SPLINE");
|
||||
common(w, e, owner, paper, "AcDbSpline");
|
||||
let flags = 8 | i64::from(s.closed) | if s.is_periodic() { 2 } else { 0 } | if s.weights.is_empty() { 0 } else { 4 };
|
||||
// AutoCAD 2024 rebuilds a spline with fit data from its fit points and end tangents,
|
||||
// whatever its flags say. A closed one starts at its first fit point, has it again at
|
||||
// the end and its tangent where it closes at both ends: without the point AutoCAD
|
||||
// opens it, and without the tangents its ends are free. A closed spline without a
|
||||
// stored tangent (periodic knots, a fit tolerance, a kink where it closes) gives the
|
||||
// curve's own. The reader drops one closing point, so it goes after a list that ends
|
||||
// with the first point already (a kink where it closes) too; only three points ending
|
||||
// so, which the reader keeps as they are, go without it.
|
||||
let ends_at_first = s.fit.first().zip(s.fit.last()).is_some_and(|(a, b)| a.near(*b, 1e-12));
|
||||
let closing = s.closed && s.fit.len() > 2 && !(s.fit.len() == 3 && ends_at_first);
|
||||
w.i(70, flags);
|
||||
w.i(71, s.degree as i64);
|
||||
w.i(72, s.knots.len() as i64);
|
||||
w.i(73, s.control.len() as i64);
|
||||
w.i(74, s.fit.len() as i64);
|
||||
w.i(74, (s.fit.len() + usize::from(closing)) as i64);
|
||||
w.f(42, 1e-10);
|
||||
w.f(43, 1e-10);
|
||||
// Fit data: tolerance and end tangents (the knot parametrisation is implied by the knots).
|
||||
if !s.fit.is_empty() {
|
||||
w.f(44, s.fit_opts.tolerance);
|
||||
if let Some(t) = s.fit_opts.start_tangent {
|
||||
let (lo, hi) = s.domain();
|
||||
let seam = |t: f64| Some(s.unit_tangent(t)).filter(|d| *d != Vec2::ZERO);
|
||||
let (t0, t1) = (s.fit_opts.start_tangent, s.fit_opts.end_tangent);
|
||||
let (t0, t1) = if s.closed { (t0.or_else(|| seam(lo)), t1.or_else(|| seam(hi))) } else { (t0, t1) };
|
||||
if let Some(t) = t0 {
|
||||
w.p(12, t.to3(0.0));
|
||||
}
|
||||
if let Some(t) = s.fit_opts.end_tangent {
|
||||
if let Some(t) = t1 {
|
||||
w.p(13, t.to3(0.0));
|
||||
}
|
||||
}
|
||||
@@ -241,7 +255,7 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
w.f(41, *wt);
|
||||
}
|
||||
}
|
||||
for f in &s.fit {
|
||||
for f in s.fit.iter().chain(s.fit.first().filter(|_| closing)) {
|
||||
w.p(11, f.to3(0.0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ pub(super) fn model_ucs(d: &Drawing) -> Ucs {
|
||||
/// style are its overrides and are written instead, so they are kept with the drawing (#3100).
|
||||
fn dim_header_vars(w: &mut W, d: &Drawing) {
|
||||
let name = d.header.str("DIMSTYLE", "Standard");
|
||||
let Some(style) = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&name)) else { return };
|
||||
let Some(style) = d.dim_style(&name) else { return };
|
||||
let mut v = serde_json::to_value(style).unwrap_or_default();
|
||||
if let Some(fields) = v.as_object_mut() {
|
||||
fields.extend(d.dim_overrides());
|
||||
|
||||
@@ -17,9 +17,14 @@ struct TableWritePlan<'a> {
|
||||
version: Version,
|
||||
cx: &'a mut Ctx,
|
||||
ext: cadcraft_geom::Bounds2,
|
||||
/// The most dash elements a linetype is written with (a DWG's count is one byte); `None`
|
||||
/// writes every element.
|
||||
max_dashes: Option<usize>,
|
||||
}
|
||||
|
||||
fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String> {
|
||||
/// The tables; the LTYPE handles by upper-case name, and how many linetypes were written with
|
||||
/// only their first `plan.max_dashes` elements.
|
||||
fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> (HashMap<String, String>, usize) {
|
||||
let d = plan.d;
|
||||
let version = plan.version;
|
||||
let cx = plan.cx;
|
||||
@@ -32,8 +37,13 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
|
||||
// in the STYLE table below: (tag position, style name, is a shape) are filled in there.
|
||||
let mut ltype_handles: HashMap<String, String> = HashMap::new();
|
||||
let mut ltype_style_refs: Vec<(usize, Option<String>, bool)> = Vec::new();
|
||||
let mut linetypes_cut = 0usize;
|
||||
let th = table_head(w, "LTYPE", d.linetypes.len());
|
||||
for lt in &d.linetypes {
|
||||
let pattern = plan.max_dashes.and_then(|max| lt.pattern.get(..max)).unwrap_or(<.pattern);
|
||||
if pattern.len() < lt.pattern.len() {
|
||||
linetypes_cut = linetypes_cut.saturating_add(1);
|
||||
}
|
||||
let h = record_head(w, "LTYPE", &th, "AcDbLinetypeTableRecord");
|
||||
ltype_handles.entry(lt.name.to_ascii_uppercase()).or_insert(h.clone());
|
||||
cx.ltypes.entry(lt.name.to_ascii_uppercase()).or_insert(h);
|
||||
@@ -41,9 +51,9 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
|
||||
w.i(70, if crate::dxf_xref::dependent(<.name) { 48 } else { 0 });
|
||||
w.s(3, <.description);
|
||||
w.i(72, 65);
|
||||
w.i(73, lt.pattern.len() as i64);
|
||||
w.f(40, lt.pattern_length());
|
||||
for el in <.pattern {
|
||||
w.i(73, pattern.len() as i64);
|
||||
w.f(40, pattern.iter().map(|el| el.length.abs()).sum());
|
||||
for el in pattern {
|
||||
w.f(49, el.length);
|
||||
// 74: 2 = text, 4 = shape, + 1 when the rotation is absolute (DXF Reference, LTYPE).
|
||||
let (kind, shape) = match (&el.text, el.shape) {
|
||||
@@ -191,7 +201,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
|
||||
}
|
||||
w.s(0, "ENDTAB");
|
||||
write_dimstyles(w, d, cx, version);
|
||||
ltype_handles
|
||||
(ltype_handles, linetypes_cut)
|
||||
}
|
||||
|
||||
/// The LAYER table; when the drawing has layer states AutoCAD can hold, the table's extension
|
||||
@@ -1056,14 +1066,15 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the
|
||||
/// file ends up in) has, and the foreign objects the file keeps, by their handles in the drawing.
|
||||
/// `bridge`: the text is for the DWG bridge, not a DXF file. The versions alone can't say so: an
|
||||
/// R2000 DWG is bridged from R2000 text.
|
||||
/// R2000 DWG is bridged from R2000 text. The bridge's linetypes keep at most
|
||||
/// [`super::DWG_MAX_LINETYPE_ELEMENTS`] elements; the last value counts those cut.
|
||||
pub(super) fn tags_kept_for(
|
||||
d: &Drawing,
|
||||
version: Version,
|
||||
target: Version,
|
||||
frozen_341: bool,
|
||||
bridge: bool,
|
||||
) -> (Vec<Tag>, std::collections::HashSet<Handle>) {
|
||||
) -> (Vec<Tag>, std::collections::HashSet<Handle>, usize) {
|
||||
// An in-place block edit in progress is not written: the drawing as before it.
|
||||
let committed = d.committed();
|
||||
let d: &Drawing = &committed;
|
||||
@@ -1182,7 +1193,8 @@ pub(super) fn tags_kept_for(
|
||||
|
||||
write_classes(&mut w, &cx, &every);
|
||||
|
||||
let ltype_handles = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model) });
|
||||
let max_dashes = bridge.then_some(super::DWG_MAX_LINETYPE_ELEMENTS);
|
||||
let (ltype_handles, linetypes_cut) = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model), max_dashes });
|
||||
|
||||
// BLOCK_RECORD
|
||||
let th = table_head(&mut w, "BLOCK_RECORD", 1 + ps_brs.len() + user_blocks.len() + dim_defs.len() + arrow_defs.len() + table_defs.len());
|
||||
@@ -1344,7 +1356,7 @@ pub(super) fn tags_kept_for(
|
||||
add_class_instance_counts(&mut w.t, target);
|
||||
mark_xrefs(&mut w.t, d);
|
||||
plot_settings_compatibility(&mut w.t, target);
|
||||
(w.t, kept)
|
||||
(w.t, kept, linetypes_cut)
|
||||
}
|
||||
|
||||
fn plot_settings_compatibility(tags: &mut Vec<Tag>, target: Version) {
|
||||
|
||||
@@ -38,7 +38,7 @@ pub use cadcraft_doc::Format;
|
||||
pub use craft_dxf::Version;
|
||||
pub use dxf_raw::{ObjectRecord, object_records};
|
||||
pub use dxf_read::entity_from_groups;
|
||||
pub use dxf_write::{dwg_compat_lost, entity_groups, proxies_lost};
|
||||
pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost};
|
||||
pub use pdf::{PdfOptions, pdf, plot};
|
||||
|
||||
/// How a drawing is saved as DXF or DWG.
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
|
||||
let d = match (space, margins) {
|
||||
(Space::Paper(n), Some(m)) => {
|
||||
let mut c = d.clone();
|
||||
if let Some(l) = c.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(n)) {
|
||||
if let Some(l) = c.layouts.by_name_mut(n) {
|
||||
l.page.margins_mm = m;
|
||||
}
|
||||
with_margins = c;
|
||||
|
||||
@@ -397,6 +397,60 @@ fn many_distinct_symbol_names_read_quickly() {
|
||||
assert_eq!(d.text_style("ST0").map(|s| s.height), Some(2.0));
|
||||
}
|
||||
|
||||
/// Many distinct dimension style names read in linear time, with the duplicate rule kept: a later
|
||||
/// record of a name in other case replaces the first, which keeps its place and takes the later
|
||||
/// record's name, also the Standard style a drawing starts with (#1924). The names share their
|
||||
/// first 200 bytes, so comparing two costs about that.
|
||||
#[test]
|
||||
fn many_distinct_dimension_style_names_read_quickly() {
|
||||
const N: usize = 20_000;
|
||||
let name = |i: usize| format!("D{}{i:06}", "x".repeat(199));
|
||||
let mut t = String::from("0\nSECTION\n2\nTABLES\n");
|
||||
for i in 0..N {
|
||||
t.push_str(&format!("0\nDIMSTYLE\n2\n{}\n70\n0\n40\n1\n", name(i)));
|
||||
}
|
||||
t.push_str(&format!("0\nDIMSTYLE\n2\n{}\n70\n0\n40\n2\n", name(0).to_ascii_uppercase()));
|
||||
t.push_str("0\nDIMSTYLE\n2\nSTANDARD\n70\n0\n40\n3\n0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "many.dxf").unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let styles: Vec<(&str, f64)> = d.dim_styles.iter().map(|s| (s.name.as_str(), s.scale)).collect();
|
||||
assert_eq!(styles.len(), N + 1);
|
||||
assert_eq!(styles.first(), Some(&("STANDARD", 3.0)));
|
||||
assert_eq!(styles.get(1), Some(&(name(0).to_ascii_uppercase().as_str(), 2.0)));
|
||||
assert_eq!(styles.get(2), Some(&(name(1).as_str(), 1.0)));
|
||||
}
|
||||
|
||||
/// Many layouts with every paper-space object in one of the last of them read in linear time.
|
||||
/// Each object goes to the first layout of its exact name, as before: not to an earlier one whose
|
||||
/// name differs only in case, nor to a later one of the same name (#1924).
|
||||
#[test]
|
||||
fn many_layouts_read_quickly() {
|
||||
const N: usize = 40_000;
|
||||
let name = |i: usize| format!("L{}{i:06}", "x".repeat(47));
|
||||
let last = name(0).to_ascii_uppercase();
|
||||
// Layout N is the active one (its block record is *Paper_Space): paper-space objects without
|
||||
// an owner go to it. It and layout N + 1 have the first layout's name in other case.
|
||||
let mut t = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nBLOCK_RECORD\n0\nBLOCK_RECORD\n5\n1F\n2\n*Paper_Space\n0\nENDTAB\n0\nENDSEC\n");
|
||||
t.push_str("0\nSECTION\n2\nENTITIES\n");
|
||||
for i in 0..N {
|
||||
t.push_str(&format!("0\nLINE\n8\n0\n67\n1\n10\n{i}\n20\n0\n11\n{i}\n21\n1\n"));
|
||||
}
|
||||
t.push_str("0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n");
|
||||
for i in 0..N + 2 {
|
||||
let (n, owner) = if i < N { (name(i), "0") } else { (last.clone(), if i == N { "1F" } else { "0" }) };
|
||||
t.push_str(&format!("0\nLAYOUT\n5\n{:X}\n100\nAcDbPlotSettings\n100\nAcDbLayout\n1\n{n}\n71\n{}\n330\n{owner}\n", 0x1000 + i, i + 1));
|
||||
}
|
||||
t.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "layouts.dxf").unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let objects: Vec<(&str, usize)> = d.layouts.iter().map(|l| (l.name.as_str(), l.entities.len())).collect();
|
||||
assert_eq!(objects.len(), N + 2);
|
||||
assert_eq!(objects.first(), Some(&(name(0).as_str(), 0)));
|
||||
assert_eq!(objects.get(N..), Some(&[(last.as_str(), N), (last.as_str(), 0)][..]));
|
||||
}
|
||||
|
||||
/// Elements with many duplicate attributes are read in bounded time.
|
||||
#[test]
|
||||
fn svg_duplicate_attributes_are_not_rescanned() {
|
||||
|
||||
@@ -14,7 +14,7 @@ use cadcraft_io::{SaveOptions, read, write_with};
|
||||
|
||||
fn three_sheets() -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.layouts = vec![Layout::new("S1", 1), Layout::new("S2", 2), Layout::new("S3", 3)];
|
||||
d.layouts = vec![Layout::new("S1", 1), Layout::new("S2", 2), Layout::new("S3", 3)].into();
|
||||
let line = |a: f64| EntityKind::Line(Line { a: Vec3::new(a, 0.0, 0.0), b: Vec3::new(a + 10.0, 10.0, 0.0) });
|
||||
d.add(&Space::Paper("S1".into()), Common::default(), line(0.0)).unwrap();
|
||||
d.add(&Space::Paper("S2".into()), Common::default(), line(20.0)).unwrap();
|
||||
|
||||
@@ -1,8 +1,29 @@
|
||||
//! A closed fit-point spline is periodic: DXF flags it closed + periodic (group 70 bits 1 and 2)
|
||||
//! and it reads back as the same smooth closed curve.
|
||||
//! and it reads back as the same smooth closed curve. Its fit data is written as AutoCAD 2024
|
||||
//! writes it (the first fit point again at the end, the tangent where it closes as both end
|
||||
//! tangents), so AutoCAD, which rebuilds a spline from its fit data, gets the same curve.
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Space};
|
||||
use cadcraft_geom::{Spline, Vec2};
|
||||
use cadcraft_geom::{FitOptions, KnotParam, Spline, Vec2};
|
||||
|
||||
/// The tags after the AcDbSpline marker, up to the next entity.
|
||||
fn spline_tags(text: &str) -> &str {
|
||||
let marker = "AcDbSpline\r\n";
|
||||
let s = &text[text.find(marker).unwrap() + marker.len()..];
|
||||
&s[..s.find("\r\n 0\r\n").unwrap()]
|
||||
}
|
||||
|
||||
/// The values of group `code` in a tag list, as numbers.
|
||||
fn values(tags: &str, code: &str) -> Vec<f64> {
|
||||
let lines: Vec<&str> = tags.lines().collect();
|
||||
lines.chunks(2).filter(|t| t.first().is_some_and(|c| c.trim() == code)).filter_map(|t| t.get(1)?.trim().parse().ok()).collect()
|
||||
}
|
||||
|
||||
fn read_spline(bytes: &[u8]) -> Spline {
|
||||
let back = cadcraft_io::read(bytes, "a.dxf").unwrap();
|
||||
let Some(EntityKind::Spline(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no spline") };
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_fit_spline_roundtrips_as_periodic() {
|
||||
@@ -12,14 +33,185 @@ fn closed_fit_spline_roundtrips_as_periodic() {
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Spline(sp.clone())).unwrap();
|
||||
let bytes = cadcraft_io::write(&d, "a.dxf").unwrap();
|
||||
let text = String::from_utf8(bytes.clone()).unwrap();
|
||||
let spline = &text[text.find("SPLINE").unwrap()..];
|
||||
assert!(spline.contains("70\r\n11\r\n"), "planar + closed + periodic");
|
||||
let back = cadcraft_io::read(&bytes, "a.dxf").unwrap();
|
||||
let Some(EntityKind::Spline(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no spline") };
|
||||
assert!(r.closed && r.is_periodic());
|
||||
assert_eq!(r.fit.len(), 4);
|
||||
for i in 0..=20 {
|
||||
let t = i as f64 / 20.0;
|
||||
assert!(r.eval(t).near(sp.eval(t), 1e-9));
|
||||
let tags = spline_tags(&text);
|
||||
assert!(tags.contains(" 70\r\n11\r\n"), "planar + closed + periodic");
|
||||
// Five fit points, the first again last; the tangent where it closes at both ends.
|
||||
assert_eq!(values(tags, "74"), [5.0]);
|
||||
assert_eq!(values(tags, "11"), [0.0, 4.0, 4.0, 0.0, 0.0]);
|
||||
assert_eq!(values(tags, "21"), [0.0, 0.0, 3.0, 3.0, 0.0]);
|
||||
let (lo, hi) = sp.domain();
|
||||
let seam = sp.derivative(lo);
|
||||
assert!((seam.len() - 1.0).abs() < 1e-12 && sp.derivative(hi).near(seam, 1e-12));
|
||||
for (x, y) in [("12", "22"), ("13", "23")] {
|
||||
let t = Vec2::new(values(tags, x)[0], values(tags, y)[0]);
|
||||
assert!(t.near(seam, 1e-12), "{x}: {t:?} / {seam:?}");
|
||||
}
|
||||
let r = read_spline(&bytes);
|
||||
assert!(r.closed && r.is_periodic() && !r.wraps());
|
||||
assert_eq!(r.fit.len(), 4, "the closing fit point is implied");
|
||||
assert_eq!((&r.knots, &r.control), (&sp.knots, &sp.control));
|
||||
// Two fit points (no loop to close smoothly) are written and read as they are.
|
||||
let two = Spline::from_fit_points_closed(&[Vec2::ZERO, Vec2::new(4.0, 0.0)]);
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Spline(two.clone())).unwrap();
|
||||
let back = read_spline(&cadcraft_io::write(&d, "c.dxf").unwrap());
|
||||
assert!(back.closed && back.fit == two.fit, "{:?}", back.fit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autocad_closed_fit_spline_roundtrips() {
|
||||
// The SPLINE AutoCAD 2024 writes for SPLINE (0,0) (4,0) (6,3) (1,4) Close (accoreconsole,
|
||||
// `entget`): flags 1067, clamped chord-length knots, five fit points and the tangent where
|
||||
// it closes as 12 and 13.
|
||||
let dxf = " 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nSPLINE\r\n 5\r\n2A\r\n 8\r\n0\r\n100\r\nAcDbSpline\r\n 70\r\n1067\r\n 71\r\n3\r\n 72\r\n11\r\n 73\r\n7\r\n 74\r\n5\r\n 42\r\n1e-09\r\n 43\r\n1e-10\r\n 44\r\n1e-10\r\n 12\r\n0.7326205476427477\r\n 22\r\n-0.6806372992803439\r\n 32\r\n0.0\r\n 13\r\n0.7326205476427477\r\n 23\r\n-0.6806372992803439\r\n 33\r\n0.0\r\n 40\r\n0.0\r\n 40\r\n0.0\r\n 40\r\n0.0\r\n 40\r\n0.0\r\n 40\r\n4.0\r\n 40\r\n7.605551275463989\r\n 40\r\n12.70457078905677\r\n 40\r\n16.82767641467443\r\n 40\r\n16.82767641467443\r\n 40\r\n16.82767641467443\r\n 40\r\n16.82767641467443\r\n 10\r\n0.0\r\n 20\r\n0.0\r\n 30\r\n0.0\r\n 10\r\n0.9768273968569969\r\n 20\r\n-0.9075163990404586\r\n 30\r\n0.0\r\n 10\r\n4.110440110427768\r\n 20\r\n-0.7122257786209955\r\n 30\r\n0.0\r\n 10\r\n7.696509078097733\r\n 20\r\n3.854015801004462\r\n 30\r\n0.0\r\n 10\r\n0.3665121443407813\r\n 20\r\n5.739691001923484\r\n 30\r\n0.0\r\n 10\r\n-1.006890633809635\r\n 20\r\n0.9354464925559993\r\n 30\r\n0.0\r\n 10\r\n0.0\r\n 20\r\n0.0\r\n 30\r\n0.0\r\n 11\r\n0.0\r\n 21\r\n0.0\r\n 31\r\n0.0\r\n 11\r\n4.0\r\n 21\r\n0.0\r\n 31\r\n0.0\r\n 11\r\n6.0\r\n 21\r\n3.0\r\n 31\r\n0.0\r\n 11\r\n1.0\r\n 21\r\n4.0\r\n 31\r\n0.0\r\n 11\r\n0.0\r\n 21\r\n0.0\r\n 31\r\n0.0\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n";
|
||||
let r = read_spline(dxf.as_bytes());
|
||||
let fit = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0)];
|
||||
assert!(r.closed && r.is_periodic() && !r.wraps(), "{r:?}");
|
||||
assert_eq!(r.fit, fit, "the closing fit point is implied");
|
||||
// Its tangent where it closes is kept, as AutoCAD keeps it through fit-point edits.
|
||||
let d = Vec2::new(0.7326205476427477, -0.6806372992803439);
|
||||
assert_eq!((r.fit_opts.start_tangent, r.fit_opts.end_tangent), (Some(d), Some(d)));
|
||||
assert_eq!(r.fit_opts.tolerance, 0.0, "44 = 1e-10 is AutoCAD's no fit tolerance");
|
||||
// The same curve as the one built here from the fit points.
|
||||
let own = Spline::from_fit_points_closed(&fit);
|
||||
assert!(r.control.iter().zip(&own.control).all(|(a, b)| a.near(*b, 1e-12)) && r.control.len() == own.control.len());
|
||||
// A fit-point move rebuilds it as AutoCAD does, though its fit tolerance is 1e-10 (AutoCAD's
|
||||
// none): SPLINEDIT Fit data Move of (1, 4) to (1, 5), which keeps the tangent.
|
||||
let moved = r.refit(&[fit[0], fit[1], fit[2], Vec2::new(1.0, 5.0)], true);
|
||||
let want = [
|
||||
(0.0, 0.0),
|
||||
(0.9768273968569969, -0.9075163990404586),
|
||||
(4.139797324573113, -0.6528392109186482),
|
||||
(7.666093574908103, 3.731946546410586),
|
||||
(-0.03708934486751076, 7.208547566545824),
|
||||
(-1.245215489496467, 1.156860956903188),
|
||||
(0.0, 0.0),
|
||||
];
|
||||
assert!(
|
||||
moved.control.len() == want.len() && moved.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)),
|
||||
"{:?}",
|
||||
moved.control
|
||||
);
|
||||
let in_tags = spline_tags(dxf);
|
||||
// Written back: closed + periodic, and the knots, control points and fit data AutoCAD wrote.
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Spline(r)).unwrap();
|
||||
let text = String::from_utf8(cadcraft_io::write(&d, "b.dxf").unwrap()).unwrap();
|
||||
let out = spline_tags(&text);
|
||||
assert_eq!(values(out, "70"), [11.0]);
|
||||
for code in ["40", "10", "20", "74", "11", "21", "12", "22", "13", "23"] {
|
||||
assert_eq!(values(out, code), values(in_tags, code), "group {code}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_splines_without_a_stored_tangent_reopen_as_they_were() {
|
||||
// Periodic knots, a fit tolerance or a kink: no tangent is kept where the curve closes, though
|
||||
// the file gives the curve's own as 12/13 for AutoCAD. Reopened, the spline still has none, so
|
||||
// SPLINEDIT Open (an open refit) gives free ends, as before the save.
|
||||
let fit = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0), Vec2::new(-1.0, 2.0)];
|
||||
let k = Vec2::new(6.0, 3.0);
|
||||
let cases = [
|
||||
Spline::fit_with(&fit, true, FitOptions { knots: KnotParam::Uniform, ..FitOptions::default() }),
|
||||
Spline::fit_with(&fit, true, FitOptions { tolerance: 0.5, ..FitOptions::default() }),
|
||||
Spline::fit_with(&[fit[0], fit[1], k, k, fit[3], fit[4]], true, FitOptions::default()),
|
||||
];
|
||||
for sp in cases {
|
||||
assert_eq!((sp.fit_opts.start_tangent, sp.fit_opts.end_tangent), (None, None));
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Spline(sp.clone())).unwrap();
|
||||
let bytes = cadcraft_io::write(&d, "k.dxf").unwrap();
|
||||
let text = String::from_utf8(bytes.clone()).unwrap();
|
||||
assert_eq!(values(spline_tags(&text), "12").len(), 1, "12 is written for AutoCAD");
|
||||
let back = read_spline(&bytes);
|
||||
assert_eq!((back.fit_opts.start_tangent, back.fit_opts.end_tangent), (None, None), "{:?}", sp.fit_opts);
|
||||
let (open, again) = (sp.refit(&sp.fit, false), back.refit(&back.fit, false));
|
||||
assert!(open.control.len() == again.control.len() && open.control.iter().zip(&again.control).all(|(a, b)| a.near(*b, 1e-9)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reversed_closed_spline_is_written_as_autocad_reverses_it() {
|
||||
// AutoCAD 2024's REVERSE of SPLINE (0,0) (4,0) (6,3) (1,4) Close (accoreconsole, `entget`):
|
||||
// the seam stays the first fit point, the others turn round, and so does the tangent where it
|
||||
// closes; the knots and control points are reversed. REVERSE and SPLINEDIT Reverse use
|
||||
// `Spline::reversed`.
|
||||
let fit = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0)];
|
||||
let r = Spline::from_fit_points_closed(&fit).reversed();
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Spline(r.clone())).unwrap();
|
||||
let bytes = cadcraft_io::write(&d, "r.dxf").unwrap();
|
||||
let text = String::from_utf8(bytes.clone()).unwrap();
|
||||
let tags = spline_tags(&text);
|
||||
assert_eq!(values(tags, "11"), [0.0, 1.0, 6.0, 4.0, 0.0]);
|
||||
assert_eq!(values(tags, "21"), [0.0, 4.0, 3.0, 0.0, 0.0]);
|
||||
let near = |a: Vec<f64>, b: &[f64], tol: f64| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < tol);
|
||||
for code in ["12", "13"] {
|
||||
assert!(near(values(tags, code), &[-0.7326205476427478], 1e-12), "{code}");
|
||||
}
|
||||
for code in ["22", "23"] {
|
||||
assert!(near(values(tags, code), &[0.6806372992803439], 1e-12), "{code}");
|
||||
}
|
||||
let knots = [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
4.12310562561766,
|
||||
9.222125139210444,
|
||||
12.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
16.82767641467443,
|
||||
];
|
||||
assert!(near(values(tags, "40"), &knots, 1e-12), "{:?}", values(tags, "40"));
|
||||
let xs = [0.0, -1.006890633809634, 0.3665121443407817, 7.696509078097734, 4.110440110427767, 0.9768273968569975, 0.0];
|
||||
let ys = [0.0, 0.9354464925559991, 5.739691001923484, 3.854015801004462, -0.7122257786209955, -0.907516399040459, 0.0];
|
||||
assert!(near(values(tags, "10"), &xs, 1e-9) && near(values(tags, "20"), &ys, 1e-9));
|
||||
// Read back, it is the same spline, and a fit-point move keeps its seam and tangent: AutoCAD's
|
||||
// SPLINEDIT Fit data Move of the second fit point to (1, 5) after REVERSE.
|
||||
let back = read_spline(&bytes);
|
||||
assert_eq!(back, r);
|
||||
let moved = back.refit(&[fit[0], Vec2::new(1.0, 5.0), fit[2], fit[1]], true);
|
||||
let want = [
|
||||
(0.0, 0.0),
|
||||
(-1.245215489496467, 1.156860956903188),
|
||||
(-0.03708934486751225, 7.208547566545823),
|
||||
(7.666093574908103, 3.731946546410587),
|
||||
(4.139797324573113, -0.6528392109186484),
|
||||
(0.9768273968569966, -0.9075163990404583),
|
||||
(0.0, 0.0),
|
||||
];
|
||||
assert!(
|
||||
moved.control.len() == want.len() && moved.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)),
|
||||
"{:?}",
|
||||
moved.control
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_fit_list_ending_with_its_first_point_survives_a_save() {
|
||||
let (a, b, c, d) = (Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(5.0, 3.0), Vec2::new(1.0, 4.0));
|
||||
// A kink where it closes given at the end (as a file can give it), the first point listed
|
||||
// again at the end, three points ending so, the kink at the start as a fit stores it, and three
|
||||
// points. The closing point is written after each but the three ending with the first, which
|
||||
// the reader keeps as they are.
|
||||
for (fit, written) in [
|
||||
(vec![a, b, c, a, a], vec![0.0, 4.0, 5.0, 0.0, 0.0, 0.0]),
|
||||
(vec![a, b, c, d, a], vec![0.0, 4.0, 5.0, 1.0, 0.0, 0.0]),
|
||||
(vec![a, b, a], vec![0.0, 4.0, 0.0]),
|
||||
(vec![a, a, b, c], vec![0.0, 0.0, 4.0, 5.0, 0.0]),
|
||||
(vec![a, b, c], vec![0.0, 4.0, 5.0, 0.0]),
|
||||
] {
|
||||
let mut sp = Spline::fit_with(&[a, a, b, c], true, FitOptions::default());
|
||||
sp.fit = fit.clone();
|
||||
let mut dr = Drawing::new_metric();
|
||||
dr.add(&Space::Model, Common::default(), EntityKind::Spline(sp)).unwrap();
|
||||
let bytes = cadcraft_io::write(&dr, "a.dxf").unwrap();
|
||||
let text = String::from_utf8(bytes.clone()).unwrap();
|
||||
assert_eq!(values(spline_tags(&text), "11"), written, "{fit:?}");
|
||||
// Read back with the same points, so a refit keeps the kink where it closes.
|
||||
assert_eq!(read_spline(&bytes).fit, fit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ fn drawing() -> Drawing {
|
||||
let mut layout = Layout::new("Sheet", 1);
|
||||
layout.limits = Some((Vec2::new(1.038, 0.694), Vec2::new(9.506, 6.681)));
|
||||
layout.page.image_origin = Some(Vec2::new(-1.054, -0.71));
|
||||
d.layouts = vec![layout];
|
||||
d.layouts = vec![layout].into();
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! A DWG counts a linetype's dash elements in one byte (acadrust 0.6.6 writes and reads the
|
||||
//! count with `write_byte` / `read_byte`), so a linetype saved as DWG keeps its first 255
|
||||
//! elements instead of a count that wrapped past 255, and one note says how many linetypes were
|
||||
//! cut (#1923, F-05; the DXF cap of #3482 lets 256 through).
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use cadcraft_doc::{DashElement, Drawing, Layer, Linetype};
|
||||
use cadcraft_io::{DWG_MAX_LINETYPE_ELEMENTS as MAX, SaveOptions, Version, dwg_notes};
|
||||
|
||||
/// Element `i`: a dash `(i + 1) / 100` long for even `i`, a gap that long for odd `i`.
|
||||
fn length(i: usize) -> f64 {
|
||||
let l = (i + 1) as f64 / 100.0;
|
||||
if i.is_multiple_of(2) { l } else { -l }
|
||||
}
|
||||
|
||||
/// A linetype `name` of `elements` elements.
|
||||
fn linetype(name: &str, elements: usize) -> Linetype {
|
||||
Linetype { name: name.into(), description: format!("{name} dashes"), pattern: (0..elements).map(|i| DashElement::dash(length(i))).collect() }
|
||||
}
|
||||
|
||||
/// A drawing with linetypes of these names and element counts.
|
||||
fn drawing(linetypes: &[(&str, usize)]) -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.linetypes.extend(linetypes.iter().map(|(name, n)| linetype(name, *n)));
|
||||
d
|
||||
}
|
||||
|
||||
/// The element lengths of linetype `name` in `d`.
|
||||
fn lengths(d: &Drawing, name: &str) -> Option<Vec<f64>> {
|
||||
d.linetype(name).map(|l| l.pattern.iter().map(|e| e.length).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_keeps_the_first_255_dash_elements_of_a_longer_linetype() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = drawing(&[("FULL", MAX), ("OVER", MAX + 1), ("LONG", 300)]);
|
||||
let first = (0..MAX).map(length).collect::<Vec<_>>();
|
||||
for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2010, Version::R2013, Version::R2018] {
|
||||
let options = SaveOptions { version: Some(version), binary: false };
|
||||
let dwg = cadcraft_io::write_with(&d, "ltypes.dwg", &options).expect("save as DWG");
|
||||
let back = cadcraft_io::read(&dwg, "ltypes.dwg").expect("reopen");
|
||||
for name in ["FULL", "OVER", "LONG"] {
|
||||
assert_eq!(lengths(&back, name).as_ref(), Some(&first), "{name} {version:?}");
|
||||
}
|
||||
// The record's total length is that of the elements it keeps.
|
||||
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().expect("acadrust reads the DWG");
|
||||
let long = doc.line_types.iter().find(|l| l.name == "LONG").expect("LONG");
|
||||
let kept: f64 = first.iter().map(|l| l.abs()).sum();
|
||||
assert!((long.pattern_length - kept).abs() < 1e-9, "{version:?}: {} for {kept}", long.pattern_length);
|
||||
}
|
||||
}
|
||||
|
||||
/// One note counts the linetypes a DWG cuts; linetypes that fit get none.
|
||||
#[test]
|
||||
fn one_note_counts_the_linetypes_a_dwg_cuts() {
|
||||
assert_eq!(dwg_notes(&drawing(&[("FULL", MAX), ("SHORT", 4)])), Vec::<String>::new());
|
||||
let one = dwg_notes(&drawing(&[("FULL", MAX), ("OVER", MAX + 1)]));
|
||||
assert!(matches!(one.as_slice(), [note] if note.contains("1 linetype ") && note.contains(&MAX.to_string())), "{one:?}");
|
||||
let two = dwg_notes(&drawing(&[("OVER", MAX + 1), ("FULL", MAX), ("LONG", 300)]));
|
||||
assert!(matches!(two.as_slice(), [note] if note.contains("2 linetypes")), "{two:?}");
|
||||
}
|
||||
|
||||
/// An xref's own linetype is saved only when a layer uses it, so only then is it counted.
|
||||
#[test]
|
||||
fn an_xref_linetype_the_file_leaves_out_is_not_counted() {
|
||||
let mut d = drawing(&[("SITE|LONG", 300)]);
|
||||
assert_eq!(dwg_notes(&d), Vec::<String>::new());
|
||||
d.layers.push(Layer { linetype: "SITE|LONG".into(), ..Layer::new("SITE|WALLS") });
|
||||
assert!(matches!(dwg_notes(&d).as_slice(), [note] if note.contains("1 linetype ")), "{:?}", dwg_notes(&d));
|
||||
}
|
||||
@@ -51,6 +51,8 @@ mod layout_plot_window;
|
||||
mod leader_vertex_elevation;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod low_handseed;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod ltype_dwg_dash_count;
|
||||
mod ltype_element_cap;
|
||||
mod minsert_marker;
|
||||
mod mleader_content;
|
||||
|
||||
@@ -195,7 +195,7 @@ pub(super) fn assert_layer_states(a: &Drawing, b: &Drawing, context: &str) {
|
||||
|
||||
pub(super) fn layouts() -> Case {
|
||||
let mut drawing = cases::drawing();
|
||||
drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)];
|
||||
drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)].into();
|
||||
for (index, layout) in drawing.layouts.iter_mut().enumerate() {
|
||||
layout.page.paper_mm = Some(true);
|
||||
// PageSetup stores portrait dimensions; landscape is a separate orientation flag.
|
||||
|
||||
@@ -25,8 +25,12 @@ fn fit_options_roundtrip_through_dxf() {
|
||||
assert!(r.fit_opts.start_tangent.is_some_and(|t| t.near(Vec2::Y, 1e-9)));
|
||||
assert!(r.fit_opts.end_tangent.is_some_and(|t| t.near(Vec2::new(1.0, -1.0).normalized(), 1e-9)));
|
||||
assert_eq!(r.control.len(), sp.control.len());
|
||||
// Over the whole curve: chord-length knots run to the fit points' length, not to 1.
|
||||
let (lo, hi) = sp.domain();
|
||||
let (rlo, rhi) = r.domain();
|
||||
assert!((rlo - lo).abs() < 1e-9 && (rhi - hi).abs() < 1e-9, "{:?} vs {:?}", r.domain(), (lo, hi));
|
||||
for i in 0..=20 {
|
||||
let t = i as f64 / 20.0;
|
||||
let t = lo + (hi - lo) * f64::from(i) / 20.0;
|
||||
assert!(r.eval(t).near(sp.eval(t), 1e-9));
|
||||
}
|
||||
// Closed (periodic) splines keep their parametrisation too.
|
||||
@@ -60,5 +64,75 @@ fn fit_data_is_written_with_the_documented_groups() {
|
||||
let dxf = "0\r\nSECTION\r\n2\r\nENTITIES\r\n0\r\nSPLINE\r\n8\r\n0\r\n100\r\nAcDbSpline\r\n70\r\n8\r\n71\r\n3\r\n74\r\n3\r\n12\r\n0.0\r\n22\r\n1.0\r\n32\r\n0.0\r\n11\r\n0.0\r\n21\r\n0.0\r\n31\r\n0.0\r\n11\r\n4.0\r\n21\r\n0.0\r\n31\r\n0.0\r\n11\r\n8.0\r\n21\r\n2.0\r\n31\r\n0.0\r\n0\r\nENDSEC\r\n0\r\nEOF\r\n";
|
||||
let back = cadcraft_io::read(dxf.as_bytes(), "b.dxf").unwrap();
|
||||
let Some(EntityKind::Spline(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no spline") };
|
||||
assert!(r.is_valid() && r.fit_opts.start_tangent == Some(Vec2::Y) && r.control.len() == 4);
|
||||
// Three fit points and a start tangent: five control points, the other end without a second
|
||||
// derivative, as AutoCAD 2024 builds it.
|
||||
assert!(r.is_valid() && r.fit_opts.start_tangent == Some(Vec2::Y) && r.control.len() == 5);
|
||||
}
|
||||
|
||||
/// A SPLINE stored with fit points and end tangents only.
|
||||
fn fit_only_dxf(fit: &[(f64, f64)], start: Option<(f64, f64)>, end: Option<(f64, f64)>) -> String {
|
||||
let mut s =
|
||||
format!("0\r\nSECTION\r\n2\r\nENTITIES\r\n0\r\nSPLINE\r\n8\r\n0\r\n100\r\nAcDbSpline\r\n70\r\n8\r\n71\r\n3\r\n74\r\n{}\r\n", fit.len());
|
||||
for (code, t) in [(12, start), (13, end)] {
|
||||
if let Some((x, y)) = t {
|
||||
s += &format!("{code}\r\n{x:?}\r\n{}\r\n{y:?}\r\n{}\r\n0.0\r\n", code + 10, code + 20);
|
||||
}
|
||||
}
|
||||
for (x, y) in fit {
|
||||
s += &format!("11\r\n{x:?}\r\n21\r\n{y:?}\r\n31\r\n0.0\r\n");
|
||||
}
|
||||
s + "0\r\nENDSEC\r\n0\r\nEOF\r\n"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fit_only_spline_takes_its_end_tangents_with_their_length() {
|
||||
// AutoCAD 2024 (accoreconsole, entget of the spline it builds): each stored tangent is the end
|
||||
// derivative as it stands, so 12 = (0, 3) is not 12 = (0, 1), and 13 = (1, -1) is not a unit.
|
||||
let fit = [(0.0, 0.0), (4.0, 0.0), (8.0, 2.0), (12.0, 1.0), (15.0, 4.0)];
|
||||
let total = 16.83788226773652;
|
||||
let knots = [0.0, 0.0, 0.0, 0.0, 4.0, 8.47213595499958, 12.59524158061724, total, total, total, total];
|
||||
let cases = [
|
||||
(
|
||||
Some((0.0, 3.0)),
|
||||
None,
|
||||
[
|
||||
(0.0, 0.0),
|
||||
(0.0, 4.0),
|
||||
(5.032653247327764, -2.9587578599554),
|
||||
(7.49793879823205, 3.8423576404002),
|
||||
(12.40378970003823, -0.4300472739512),
|
||||
(14.12639202373297, 2.5093177413937),
|
||||
(15.0, 4.0),
|
||||
],
|
||||
),
|
||||
(
|
||||
Some((0.0, 2.0)),
|
||||
Some((1.0, -1.0)),
|
||||
[
|
||||
(0.0, 0.0),
|
||||
(0.0, 2.6666666666666),
|
||||
(5.051273572432346, -2.3615552390813),
|
||||
(7.426977592306234, 4.0442234834397),
|
||||
(12.64672696003663, -1.6844325426585),
|
||||
(13.5857864376269, 5.4142135623731),
|
||||
(15.0, 4.0),
|
||||
],
|
||||
),
|
||||
];
|
||||
let v = |t: Option<(f64, f64)>| t.map(|(x, y)| Vec2::new(x, y));
|
||||
for (start, end, control) in cases {
|
||||
let back = cadcraft_io::read(fit_only_dxf(&fit, start, end).as_bytes(), "c.dxf").unwrap();
|
||||
let Some(EntityKind::Spline(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no spline") };
|
||||
assert_eq!(r.knots.len(), knots.len());
|
||||
assert!(r.knots.iter().zip(knots).all(|(a, b)| (a - b).abs() < 1e-9), "{:?}", r.knots);
|
||||
assert_eq!(r.control.len(), control.len());
|
||||
for (c, (x, y)) in r.control.iter().zip(control) {
|
||||
assert!(c.near(Vec2::new(x, y), 1e-9), "{start:?} {end:?}: {c:?} vs ({x}, {y})");
|
||||
}
|
||||
// The tangents are kept as stored, and written back so.
|
||||
assert_eq!((r.fit_opts.start_tangent, r.fit_opts.end_tangent), (v(start), v(end)));
|
||||
let again = roundtrip(&r);
|
||||
assert_eq!((again.fit_opts.start_tangent, again.fit_opts.end_tangent), (v(start), v(end)));
|
||||
assert!(again.control.iter().zip(&r.control).all(|(a, b)| a.near(*b, 1e-12)));
|
||||
}
|
||||
}
|
||||
|
||||
+29
-20
@@ -1,6 +1,7 @@
|
||||
use super::blocks::{insert, proxy, sub_ctx};
|
||||
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
|
||||
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
|
||||
use super::linetype::Layout;
|
||||
use super::props::{resolve, transparency};
|
||||
use super::text_entity::{mtext, place_text_entity};
|
||||
use super::{
|
||||
@@ -89,11 +90,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
};
|
||||
let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12);
|
||||
let lw = if b.opts.lineweights { lw } else { 0.0 };
|
||||
// Stroke a polyline with the entity's linetype.
|
||||
let stroke = |b: &mut Builder, pts: &[Vec2]| match lt.as_ref().filter(|_| b.opts.linetypes) {
|
||||
// Stroke a run with the entity's linetype, laid out as `how` says.
|
||||
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
|
||||
Some(lt) => {
|
||||
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
|
||||
for dash in linetype::apply(pts, lt, ltscale, min) {
|
||||
for dash in linetype::apply_as(pts, lt, ltscale, min, how) {
|
||||
if dash.len() == 1 {
|
||||
if let Some(p) = dash.first() {
|
||||
b.point(ctx, rgb, *p);
|
||||
@@ -104,13 +105,31 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
}
|
||||
// Text and shapes embedded in the linetype (shapes when their SHX file is found).
|
||||
if b.opts.text {
|
||||
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min) {
|
||||
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
|
||||
b.shaped(ctx, rgb, lw, &sh);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => b.polyline(ctx, rgb, lw, pts),
|
||||
};
|
||||
let stroke = |b: &mut Builder, pts: &[Vec2]| stroke_as(b, pts, Layout::Open);
|
||||
// A polyline's centre line: with PLINEGEN the pattern runs along the whole of it (stretched
|
||||
// around a closed one from its second vertex, as AutoCAD lays it); otherwise it restarts at
|
||||
// every vertex.
|
||||
let centre_line = |b: &mut Builder, p: &cadcraft_doc::LwPolyline| {
|
||||
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
|
||||
if p.plinegen && p.closed {
|
||||
stroke_as(b, &pl.tessellate(tol), Layout::Closed { anchor: wide::second_vertex_at(p, tol) });
|
||||
} else if !b.opts.linetypes || p.plinegen || lt.is_none() {
|
||||
stroke(b, &pl.tessellate(tol));
|
||||
} else {
|
||||
for s in pl.segments() {
|
||||
let mut pts = Vec::new();
|
||||
s.tessellate(tol, &mut pts);
|
||||
stroke(b, &pts);
|
||||
}
|
||||
}
|
||||
};
|
||||
match &e.kind {
|
||||
EntityKind::Text(t) => {
|
||||
if !b.opts.text {
|
||||
@@ -180,22 +199,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
|
||||
stroke(b, &pl.tessellate(tol));
|
||||
}
|
||||
}
|
||||
EntityKind::LwPolyline(p) => {
|
||||
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
|
||||
if !b.opts.linetypes || p.plinegen || lt.is_none() {
|
||||
stroke(b, &pl.tessellate(tol));
|
||||
} else {
|
||||
for s in pl.segments() {
|
||||
let mut pts = Vec::new();
|
||||
s.tessellate(tol, &mut pts);
|
||||
stroke(b, &pts);
|
||||
}
|
||||
// Fill off: the centre line, dashed as a polyline without width is.
|
||||
centre_line(b, p);
|
||||
}
|
||||
}
|
||||
EntityKind::LwPolyline(p) => centre_line(b, p),
|
||||
EntityKind::Solid(s) | EntityKind::Trace(s) => {
|
||||
let c = &s.corners;
|
||||
let q = [c[0].xy(), c[1].xy(), c[3].xy(), c[2].xy()];
|
||||
@@ -249,15 +257,16 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
s.tessellate(tol, &mut pts);
|
||||
stroke(b, &pts);
|
||||
}
|
||||
// Closed runs from angle 0 (or the ellipse's start parameter).
|
||||
Prim::Circle(c) => {
|
||||
let mut pts = Vec::new();
|
||||
c.tessellate(tol, &mut pts);
|
||||
stroke(b, &pts);
|
||||
stroke_as(b, &pts, Layout::Closed { anchor: 0.0 });
|
||||
}
|
||||
Prim::Ellipse(el) => {
|
||||
let mut pts = Vec::new();
|
||||
el.tessellate(tol, &mut pts);
|
||||
stroke(b, &pts);
|
||||
stroke_as(b, &pts, if el.is_full() { Layout::Closed { anchor: 0.0 } } else { Layout::Open });
|
||||
}
|
||||
Prim::Spline(s) => stroke(b, &s.tessellate(tol)),
|
||||
Prim::Point(p) => b.point(ctx, rgb, p),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user